J2ME -- failed to retrieve record from the RMS - record

i have been facing some problem with displaying the record from RMS. Im doing some e-wallet application for the j2me and here is my source code. it tell me that the recordwith#id has been added but I failed to retrieve and display the income amount from the users.
this the code for my RMS
//variable for record store
RecordStore ew_rs;
public static int addCount = 0;
public static int editCount = 0;
public static int deleteCount = 0;
public addIncome(){
this("tmpfile");
}
public addIncome(String filename) {
super();
try{
ew_rs = RecordStore.openRecordStore(filename, true);
ew_rs.addRecordListener(this);
} catch (RecordStoreException e){
e.printStackTrace();
}
}
public void closeRMS(){
try {
if (ew_rs.getNumRecords() > 0) {
ew_rs.closeRecordStore();
} else {
ew_rs.closeRecordStore();
RecordStore.deleteRecordStore(ew_rs.getName());
}
} catch (RecordStoreNotOpenException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (RecordStoreException e) {
e.printStackTrace();
}
}
//variable declaration for income adding
int ew_incomeID;
float ew_incomeAmount=0;
public addIncome(int incomeID, float incomeAmount){
this.ew_incomeID = incomeID;
this.ew_incomeAmount = incomeAmount;
}
public int getIncID(){
return ew_incomeID;
}
public void setIncID(int incomeID){
this.ew_incomeID = incomeID;
}
public float getIncAmt(){
return ew_incomeAmount;
}
public void setIncAmt(float incomeAmt){
this.ew_incomeAmount = incomeAmt;
}
public void recordAdded(RecordStore recordStore, int recordId) {
addCount++;
try {
System.out.println("Record with ID# " + recordId +
" added in Record Store " + recordStore.getName());
} catch (RecordStoreNotOpenException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void recordChanged(RecordStore recordStore, int recordId) {
editCount++;
try {
System.out.println("Record with ID# " + recordId +
" changed in Record Store " + recordStore.getName());
} catch (RecordStoreNotOpenException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void recordDeleted(RecordStore recordStore, int recordId) {
deleteCount++;
try {
System.out.println("Record with ID# " + recordId +
" deleted in Record Store " + recordStore.getName());
} catch (RecordStoreNotOpenException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//add income
public void addIncomeFunction(int id , float IncAmt){
id = getIncID();
IncAmt = getIncAmt();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(baos);
int convertAmt = Float.floatToIntBits(IncAmt);
try {
out.writeUTF(String.valueOf(id));
out.writeInt(convertAmt);
}catch (IOException e) {
e.printStackTrace();
}
byte[] b = baos.toByteArray();
try {
ew_rs.addRecord(b, 0, b.length);
} catch (RecordStoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
baos.close();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//retrieve income
public byte[] getIncome(){
byte[] read = null;
try{
read = new byte[ew_rs.getSize()];
RecordEnumeration re = ew_rs.enumerateRecords(null, null, false);
ByteArrayInputStream bais = new ByteArrayInputStream(re.nextRecord());
DataInputStream in = new DataInputStream(bais);
for (int i = 0; i < re.numRecords() && re.hasNextElement(); i++) {
try {
in.readInt();
Float.intBitsToFloat(in.readInt());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}catch (RecordStoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return read;
}
public RecordEnumeration enumerate(){
try {
return ew_rs.enumerateRecords(null, null, false);
} catch (RecordStoreNotOpenException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
}
and the code for my display
MainMenu m;
addIncome income;
public Display d;
private static final Command cmdOk = new Command("Ok", Command.OK, 1);
private static final Command cmdBack = new Command("Back", Command.OK, 1);
public BalanceForm(MainMenu m){
this("Balance", m);
this.addCommand(cmdOk);
this.addCommand(cmdBack);
this.setCommandListener(this);
}
public BalanceForm(String arg0, MainMenu m){
super(arg0);
this.m = m;
}
public void prepareView(Display display){
this.setCommandListener(this);
this.d = display;
}
public void showView(){
d.setCurrent(this);
}
public void commandAction(Command c, Displayable d) {
if (c == cmdBack)
{
m.showMenu();
}
else{
byte[] b = income.getIncome();
ByteArrayInputStream bais = new ByteArrayInputStream(b);
DataInputStream in = new DataInputStream(bais);
try {
System.out.println(in.readInt());
System.out.println(in.readUTF());
//this.append(in.readUTF());
//this.append(String.valueOf(in.readInt()));
} catch (IOException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

Related

Create a Generic AttributeConverter[JDO] with JsonConverter

I´m using JDO + DataNucleus and implement a AttributeConverter with Jackson Json.
Already have a generic method for AttributeConverter:
#Override
public String convertToDatastore(ArrayList<Object> alist) {
String jsonString = null;
try {
jsonString = mapper.writeValueAsString(alist);
} catch (IOException e) {
e.printStackTrace();
}
return jsonString;
}
But, in Deserialize JSON to Object i read that i need to specify the class
public ArrayList<TelephoneNumber> convertToAttribute(String s) {
ArrayList<TelephoneNumber> obj = null;
try
{
obj = mapper.readValue(s, mapper.getTypeFactory().constructCollectionType(
List.class, TelephoneNumber.class));
}
catch (JsonParseException e) { e.printStackTrace();}
catch (JsonMappingException e) { e.printStackTrace(); }
catch (IOException e) { e.printStackTrace(); }
return obj;
}
but jsonString is a arrayList object
how can I do this?
thanks

JList blank, not displaying anything. Have tried everything other websites suggested

Here:
private static DefaultListModel qpape;
//#SuppressWarnings("null")
public void disp() throws SQLException
{
qpape=new DefaultListModel();
jList2=new JList(qpape);
String sql1="SELECT URL from RECORD";
PreparedStatement st = db.conn.prepareStatement(sql1,
Statement.RETURN_GENERATED_KEYS);
ResultSet rs1=st.executeQuery(sql1);
while(rs1.next())
{
String lnk=rs1.getString("URL");
System.out.println(lnk);
//qpape.addElement(lnk);
((DefaultListModel)jList2.getModel()).addElement(lnk);
}
rs1.close();
}
public static void main(String args[]) throws SQLException, IOException {
fetch();
Qpapers obj=new Qpapers();
if(obj!=null) {
obj.disp();
jList2.setModel(qpape);
}
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info :
javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Qpapers.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Qpapers.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Qpapers.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Qpapers.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Qpapers().setVisible(true);
}
});
}
// Variables declaration - do not modify
private static javax.swing.JList jList2;
private javax.swing.JScrollPane jScrollPane2;
// End of variables declaration
}

calling alarm from a service

I designed my service as it will make an alarm when user will go to a certain location.
But it crashes when it go to the certain making the alarm.
public class CheckDestinationService extends Service {
Calendar calender;
double late,longe;
int dis;
String loc;
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 0;
private static final float LOCATION_DISTANCE = 0;
private class LocationListener implements android.location.LocationListener {
Location mLastLocation;
public LocationListener(String provider) {
mLastLocation = new Location(provider);
}
public void onLocationChanged(Location location) {
mLastLocation.set(location);
final double currlat;
final double currlong;
float[] DistanceArray = new float[1];
currlat = location.getLatitude();
currlong = location.getLongitude();
android.location.Location.distanceBetween(currlat,currlong,late,longe,DistanceArray);
float Distance = DistanceArray[0];
//Toast.makeText(getApplicationContext(), "asdf "+String.valueOf(Distance), Toast.LENGTH_SHORT).show();
Log.d("asdfasdas", String.valueOf(currlat)+","+String.valueOf(currlong)+" "+String.valueOf(Distance));
if (Distance<=dis && Distance!=0 && dis!=0)
{
dis = 0;
Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Toast.makeText(getApplicationContext(), "Reached "+String.valueOf(Distance), Toast.LENGTH_SHORT).show();
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(),0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager am = (AlarmManager)getSystemService(Activity.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, calender.getTimeInMillis(),pendingIntent);
//stopSelf();
}
/*final Handler handler = new Handler();
Runnable r = new Runnable() {
public void run() {
// TODO Auto-generated method stub
Intent intent = null;
intent.putExtra("lat", currlat);
intent.putExtra("long", currlong);
intent.putExtra("dis", dis);
intent.putExtra("loc", loc);
Toast.makeText(getApplicationContext(), "Sending", Toast.LENGTH_SHORT).show();
sendBroadcast(intent);
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(r, 1000);*/
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
LocationListener[] mLocationListeners = new LocationListener[] {
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER)
};
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
late = intent.getDoubleExtra("lat", 0);
longe = intent.getDoubleExtra("long", 0);
dis = intent.getIntExtra("dis", 0);
loc = intent.getStringExtra("loc");
Toast.makeText(getApplicationContext(), "Destination Set to: "+loc+
" and Minimum Distance: "+
String.valueOf(dis) , Toast.LENGTH_SHORT).show();
return START_STICKY;
}
#Override
public void onCreate() {
initializeLocationManager();
try {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[1]);
} catch (java.lang.SecurityException ex) {
} catch (IllegalArgumentException ex) {
}
try {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[0]);
} catch (java.lang.SecurityException ex) {
} catch (IllegalArgumentException ex) {
}
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(getApplicationContext(), "Service Destroyed", Toast.LENGTH_SHORT).show();
if (mLocationManager != null) {
for (int i = 0; i < mLocationListeners.length; i++) {
try {
mLocationManager.removeUpdates(mLocationListeners[i]);
} catch (Exception ex) {
}
}
}
}
private void initializeLocationManager() {
if (mLocationManager == null) {
mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
}
}
and my AlarmReceiver class is
public class AlarmReceiver extends Activity {
private MediaPlayer mMediaPlayer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.alarmreceiver);
Button stopAlarm = (Button) findViewById(R.id.stopAlarm);
stopAlarm.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View arg0, MotionEvent arg1) {
stopService(new Intent(AlarmReceiver.this, CheckDestinationService.class));
mMediaPlayer.stop();
finish();
return false;
}
});
playSound(this, getAlarmUri());
}
private void playSound(Context context, Uri alert) {
mMediaPlayer = new MediaPlayer();
try {
mMediaPlayer.setDataSource(context, alert);
final AudioManager audioManager = (AudioManager) context
.getSystemService(Context.AUDIO_SERVICE);
if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) {
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
mMediaPlayer.prepare();
mMediaPlayer.start();
}
} catch (IOException e) {
System.out.println("OOPS");
}
}
//Get an alarm sound. Try for an alarm. If none set, try notification,
//Otherwise, ringtone.
private Uri getAlarmUri() {
Uri alert = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_ALARM);
if (alert == null) {
alert = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
if (alert == null) {
alert = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
}
}
return alert;
}
#Override
public void onBackPressed() {
//MainActivity.iMinDistance = 0;
stopService(new Intent(AlarmReceiver.this, CheckDestinationService.class));
mMediaPlayer.stop();
finish();
}
}
I tested AlarmReceiver class from other activites and it worked properly
but it not working from the service.
please help!!
initalize Calendar
calender = Calendar.getInstance()

Fieldable.tokenStreamValue() returns null for tokenized field

I use lucene for N-Gram matching. I set a field to be analyzed using an N-Gram analyzer. I want to see how the tokens resulting from the analysis look like to make sure the n-grams are being correctly computed.
If I call the method Fieldable.tokenStreamValue() on the analyzed field of a document, I get null, while calling Fieldable.isTokenized() returns true.
I must add that the results of querying are consistent with n-grams being correctly generated.
Any explanations for this? I am essentially trying to do what is mentioned here:
How can I read a Lucene document field tokens after they are analyzed?
Here is the full code:
public class TestLuceneNgram {
public static class NGramQuery extends BooleanQuery {
public NGramQuery(final String queryTerm) throws IOException {
StringReader strReader = new StringReader(queryTerm);
TokenStream tokens = new NGramTokenizer(strReader);
CharTermAttribute termAtt = (CharTermAttribute) tokens
.addAttribute(CharTermAttribute.class);
while (tokens.incrementToken()) {
System.out.println(termAtt);
Term t = new Term("NGRAM_FIELD", termAtt.toString());
add(new TermQuery(t), BooleanClause.Occur.SHOULD);
}
}
}
public static class NGramSearcher extends IndexSearcher {
public NGramSearcher(final Directory directory)
throws CorruptIndexException, IOException {
super(IndexReader.open(directory));
}
public TopDocs search(final String term) {
try {
return search(new NGramQuery(term), 10);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
public static class SubWordAnalyzer extends Analyzer {
#Override
public TokenStream tokenStream(final String fieldName,
final Reader reader) {
return new NGramTokenizer(reader);
}
}
public static Directory index(final String[] terms) {
Directory indexDirectory = new RAMDirectory();
IndexWriter indexWriter = null;
try {
indexWriter = new IndexWriter(indexDirectory,
new IndexWriterConfig(Version.LUCENE_32,
new SubWordAnalyzer()));
} catch (CorruptIndexException e) {
e.printStackTrace();
} catch (LockObtainFailedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
for (int i = 0; i < terms.length; ++i) {
Document doc = new Document();
doc.add(new Field("NGRAM_FIELD", terms[i], Field.Store.YES,
Field.Index.ANALYZED,
Field.TermVector.WITH_POSITIONS_OFFSETS));
doc.add(new Field("ORIGINAL_FIELD", terms[i], Field.Store.YES,
Field.Index.NOT_ANALYZED));
try {
indexWriter.addDocument(doc);
} catch (CorruptIndexException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
indexWriter.optimize();
} catch (CorruptIndexException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
indexWriter.close();
} catch (CorruptIndexException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return indexDirectory;
}
/**
* #param args
*/
public static void main(final String[] args) {
String[] terms = new String[] { "the first string", "the second one" };
Directory dir = index(terms);
NGramSearcher ngs = null;
try {
ngs = new NGramSearcher(dir);
} catch (CorruptIndexException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
TopDocs td = ngs.search("second");
System.out.println(td.totalHits);
for (ScoreDoc sd : td.scoreDocs) {
System.out.println(sd.doc + "---" + sd.score);
try {
System.out.println(ngs.doc(sd.doc).getFieldable("NGRAM_FIELD").
tokenStreamValue());
} catch (CorruptIndexException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
The first thing to check is whether you are actually storing this field at index time. If you're just indexing it, this is the expected result.

NHibernate Repository pattern problem

I am using NHibernate and Repository patterns in my application. But not want to use UnitofWork pattern.
There are two types of forms in my app. Collection/Picker forms and Entity forms.
But the problem occurs when a form is ShowDialog()ged from within another form.
Whwn I am doing any database related operation, NHibernate is giving me "a different object with the same identifier value was already associated with the session: XYZ" error. This is caused due to the delayed call of Dispose method by CLR and another part of my problem is in the Session management as far as I guess.
How can I change my repository codes to solve my problem?
Remember, I don't want to expose separate BeginTransaction(), CommitTransaction() like functions in my Repository. These things should be embedded within every Method {SaveOrUpdate(), Save(), Delete, Load(), etc.} as I have already done.
Please tell me how can I get things going with minor changes?
I am doing my things like this:
A picker form works like this,
private void btnPick_Click(object sender, EventArgs e)
{
CourseCollectionForm f = new CourseCollectionForm();
f.FormViewMode = FormViewMode.MultiplePicker;
f.ShowDialog();
int totalCredits = 0;
int totalHours = 0;
FillDataGridViewWithCourses(f.PickedCourseCollection, ref totalCredits, ref totalHours);
FillTotal(totalCredits, totalHours);
}
A Save works like this,
public partial class DepartmentEntityForm : Form
{
private DepartmentRepository _deptRepository = null;
private Department _currentDepartment = null;
private FormViewMode _currentMode = FormViewMode.None;
public DepartmentEntityForm(Department dept, FormViewMode mode)
{
InitializeComponent();
_deptRepository = new DepartmentRepository();
_currentDepartment = dept;
_currentMode = mode;
if(mode == FormViewMode.Edit)
{
MapObjectToControls();
}
}
private void SaveButton_Click(object sender, EventArgs e)
{
Department newDept;
if (mode == FormViewMode.AddNew)
{
newDept = new Department();
}
else if(mode == FormViewMode.Edit)
{
newDept = _currentDepartment;
}
//.............
//.............
_deptRepository.SaveOrUpdate(newDept);
}
}
I declare my individual repositories like this:
FacultyRepository.cs
public class FacultyRepository : Repository<Faculty>
{
}
DepartmentRepository.cs
public class DepartmentRepository : Repository<Department>
{
}
Repository.cs
public class Repository<T> : IRepository<T>
{
ISession _session;
public Repository()
{
_session = SessionFactory.GetOpenSession();
}
public T Get(object id)
{
T obj = default(T);
try
{
if (!_session.Transaction.IsActive)
{
_session.BeginTransaction();
obj = (T)_session.Get<T>(id);
_session.Transaction.Commit();
_session.Flush();
}
else
{
throw new Exception(CustomErrorMessage.TransactionAlreadyInProgress);
}
}
catch (Exception ex)
{
_session.Transaction.Rollback();
_session.Clear();
throw ex;
}
return obj;
}
public IEnumerable<T> Get(string fieldName, object fieldValue)
{
IEnumerable<T> list = null;
try
{
if (!_session.Transaction.IsActive)
{
_session.BeginTransaction();
list = (IEnumerable<T>)_session.CreateCriteria(typeof(T))
.Add(new NHibernate.Expression.EqExpression(fieldName, fieldValue))
.List<T>();
_session.Transaction.Commit();
_session.Flush();
}
else
{
throw new Exception(CustomErrorMessage.TransactionAlreadyInProgress);
}
}
catch (Exception ex)
{
_session.Transaction.Rollback();
_session.Clear();
throw ex;
}
return list;
}
public IEnumerable<T> Get()
{
IEnumerable<T> list = null;
try
{
if (!_session.Transaction.IsActive)
{
_session.BeginTransaction();
list = (IEnumerable<T>)_session.CreateCriteria(typeof(T)).List<T>();
_session.Transaction.Commit();
_session.Flush();
}
else
{
throw new Exception(CustomErrorMessage.TransactionAlreadyInProgress);
}
}
catch (Exception ex)
{
_session.Transaction.Rollback();
_session.Clear();
throw ex;
}
return list;
}
public void SaveOrUpdate(T obj)
{
try
{
if (!_session.Transaction.IsActive)
{
_session.BeginTransaction();
_session.SaveOrUpdateCopy(obj);
_session.Transaction.Commit();
_session.Flush();
}
else
{
throw new Exception(CustomErrorMessage.TransactionAlreadyInProgress);
}
}
catch (Exception ex)
{
_session.Transaction.Rollback();
_session.Clear();
throw ex;
}
}
public void SaveOrUpdate(IEnumerable<T> objs)
{
try
{
if (!_session.Transaction.IsActive)
{
_session.BeginTransaction();
foreach (T obj in objs)
{
_session.SaveOrUpdate(obj);
}
_session.Transaction.Commit();
_session.Flush();
}
else
{
throw new Exception(CustomErrorMessage.TransactionAlreadyInProgress);
}
}
catch (Exception ex)
{
_session.Transaction.Rollback();
_session.Clear();
throw ex;
}
}
public void Delete(T obj)
{
try
{
if (!_session.Transaction.IsActive)
{
_session.BeginTransaction();
_session.Delete(obj);
_session.Transaction.Commit();
_session.Flush();
}
else
{
throw new Exception(CustomErrorMessage.TransactionAlreadyInProgress);
}
}
catch (Exception ex)
{
_session.Transaction.Rollback();
_session.Clear();
throw ex;
}
}
public void Delete(IEnumerable<T> objs)
{
try
{
if (!_session.Transaction.IsActive)
{
_session.BeginTransaction();
foreach (T obj in objs)
{
_session.Delete(obj);
}
_session.Transaction.Commit();
_session.Flush();
}
else
{
throw new Exception(CustomErrorMessage.TransactionAlreadyInProgress);
}
}
catch (Exception ex)
{
_session.Transaction.Rollback();
_session.Clear();
throw ex;
}
}
public void DeleteAll()
{
try
{
if (!_session.Transaction.IsActive)
{
_session.BeginTransaction();
DetachedCriteria criterion = DetachedCriteria.For<T>();
IList<T> list = criterion.GetExecutableCriteria(_session).List<T>();
foreach (T item in list)
{
_session.Delete(item);
}
_session.Transaction.Commit();
_session.Flush();
}
else
{
throw new Exception(CustomErrorMessage.TransactionAlreadyInProgress);
}
}
catch (Exception ex)
{
_session.Transaction.Rollback();
throw ex;
}
}
public void Dispose()
{
if (_session != null)
{
_session.Clear();
_session.Close();
_session = null;
}
}
}
SessionFactory.cs
public class SessionFactory
{
private static ISessionFactory _sessionFactory = null;
private SessionFactory(){}
static SessionFactory()
{
if (_sessionFactory == null)
{
Configuration configuration = new Configuration();
configuration.Configure();
_sessionFactory = configuration.BuildSessionFactory();
}
}
public static ISession GetOpenSession()
{
return _sessionFactory.OpenSession();
}
}
OK guys! It has been long since I posted my question and nobody tends to answer it.
I solved it by making ISession static in the SessionFactory and instead of returning a Open ISession for each Repository, I am returning only one static ISession.