nhibernate difficulty in save - c#

i have this the code and i have this problem
i am trying to save a new user to my web site : the query is succeded but without insertion
ie the table "User" and the table "UserAcl" still without any modification and it is clear that the query is executed
File User.cs:
File Compte.cs
public bool SaveUser(string identification, string acc, string mot, string notify, string nom, string phone, string mail) {
try
{
if (identification == null || acc == null || nom == null || mail == null || mot == null) return false;
ITransaction transaction = User.OpenSession().BeginTransaction();
User u = new User() { Account = acc, Identification = identification, ContactEmail = mail, ContactName = nom, ContactPhone = phone, NotifyEmail = notify, Password = mot };
User.OpenSession().SaveOrUpdate(u);
transaction.Commit();
ITransaction transaction2 = User.OpenSession().BeginTransaction();
Useracl ua = new Useracl { Account = acc, UserID = identification, AccessLevel = 1, AclID = (Useracl.GetUseracl().Count + 1).ToString() };
Useracl.OpenSession().SaveOrUpdate(ua);
transaction2.Commit();
return true;
}
catch { return false; }
}
File Administration.cs
public ActionResult Index()
{
ViewBag.Title = c.GetUserID().Count.ToString();
return View();
}
public ActionResult BeforeRegister()
{
return View();
}
public ActionResult AfterRegister(string Pseudo, string Phone, string Email, string Password, string Notify)
{
bool a = c.SaveUser((c.GetPassword().Count + 1).ToString(), (c.GetPassword().Count + 1).ToString(), Password, Notify, Pseudo, Phone, Email);
if (a)
{
return RedirectToAction("Index", "Administration");
}
else
return RedirectToAction("BeforeRegister", "Administration");
}

First, you could use if (!String.IsNullOrEmpty(myString)) rather than if (myString==null).
Also, you may want to use your sessions within a using block.
bool ret= new bool();
if ((!String.IsNullOrEmpty(foo1)) && (!String.IsNullOrEmpty(foo2)))
{
//ConnectionDB is a public class, with a static method ISessionFactory SessionFactory(), and the method OpenSession() returns an ISession
using (NHibernate.ISession nhSession = ConnectionDB.SessionFactory.OpenSession())
{
try
{
User u = new User();
//set your User
nhSession.Transaction.Begin();
nhSession.Save(u);
nhSession.Transaction.Commit();
nhSession.Close();
ret = true;
}
catch (Exception ex)
{
ret = false;
}
}
return ret;
Now, about the query not inserting, it could be a mapping problem, or maybe you're supressing the exception elsewhere (like your static method User.OpenSession().SaveOrUpdate(u))

Related

JSON Object Empty when is Serialize it C#?

I am using the following Code
public class GetTabelRealizari : ControllerBase
{
public class Realizare
{
String user;
String denumire;
String incasari;
public Realizare(String user, String denumire, String incasari)
{
this.user = user;
this.denumire = denumire;
this.incasari = incasari;
}
public String getUser()
{
return user;
}
public void setUser(String user)
{
this.user = user;
}
public String getDenumire()
{
return denumire;
}
public void setDenumire(String denumire)
{
this.denumire = denumire;
}
public String getIncasari()
{
return incasari;
}
public void setIncasari(String incasari)
{
this.incasari = incasari;
}
}
[HttpPost]
public string Post([FromBody] string[] value)
{
//SSMS connection
string connectionString = "Data Source=DESKTOP-QKC0G7V;Initial Catalog=Restaurant_gest;Integrated Security=True";
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
List<Realizare> realizari = new List<Realizare>();
double incasari;
String incasariString;
SqlCommand command = new SqlCommand("SELECT Users.Username," +
" Tip_Nota_Plata.Denumire," +
" sum(Nota_plata.Suma) as Incasari" +
" from Users" +
" INNER JOIN Nota_plata" +
" INNER JOIN Comandas" +
" ON Nota_plata.Id_comanda = Comandas.Id" +
" ON Comandas.User_Id = Users.Id" +
" INNER JOIN Tip_Nota_Plata" +
" ON Tip_Nota_Plata.Id = Nota_plata.Id_tip_nota" +
" Group by Username, Tip_Nota_Plata.Denumire", connection);
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
incasari = (double)reader["Incasari"];
incasariString = incasari.ToString("#.##");
realizari.Add(new Realizare(reader["Username"].ToString(), reader["Denumire"].ToString(), incasariString));
}
}
return JsonConvert.SerializeObject(realizari);
//return "salut";
}
}
And I am receiving an empty JsonObject. Why?
[{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}]
I keep trying to make it work and I cannot. The list has the objects, i can test it with Console.Writeline(realizari[0].getDenumire()) and it works. I can also serialize a list of strings, it just doesn`t work for objects.
Because the object has no serializable properties.
I'm going to guess you are a Java developer based on this:
String user;
public String getUser()
{
return user;
}
public void setUser(String user)
{
this.user = user;
}
C# has "properties" which, while they compile down to methods very similar to this, the syntax in C# is a bit different. All of the above code can be simplified to a property:
public String User { get; set; }
The usage then becomes simpler as well, allowing for assignments instead of calling a method:
someObject.User = someUser;
In cases where you want to add logic to your getter/setter, you can expand the "auto implemented property" above into a manual one:
private string user;
public string User
{
get { return user; }
set { user = value; }
}
The get and set syntax still tells the compiler that this is a property, but within those blocks you can write any method logic you like. (In the setter value is a keyword for the value being assigned to the property.)

How can I convert ActionResult to List in C#

This is function from my partner:
public ActionResult<string> ReadSmb(string server, string share, string path, string username = "", string password = "")
{
var result = new StringBuilder();
NTStatus status;
SMB1Client client = new SMB1Client(); // SMB2Client can be used as well
bool isConnected = client.Connect(server, SMBTransportType.DirectTCPTransport);
if (isConnected)
{
status = client.Login(String.Empty, username, password);
if (status == NTStatus.STATUS_SUCCESS)
{
List<string> shares = client.ListShares(out status);
ISMBFileStore fileStore = client.TreeConnect(share, out status);
object fileHandle;
FileStatus fileStatus;
if (fileStore is SMB1FileStore)
{ path = #"\\" + path; }
status = fileStore.CreateFile(out fileHandle, out fileStatus,
path,
AccessMask.GENERIC_READ | AccessMask.SYNCHRONIZE,
SMBLibrary.FileAttributes.Normal, ShareAccess.Read,
CreateDisposition.FILE_OPEN,
CreateOptions.FILE_NON_DIRECTORY_FILE | CreateOptions.FILE_SYNCHRONOUS_IO_ALERT,
null);
if (status == NTStatus.STATUS_SUCCESS)
{
using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
{
byte[] data;
long bytesRead = 0;
while (true)
{
status = fileStore.ReadFile(out data, fileHandle, bytesRead, (int)client.MaxReadSize);
if (status != NTStatus.STATUS_SUCCESS && status != NTStatus.STATUS_END_OF_FILE)
{
throw new Exception("Failed to read from file");
}
if (status == NTStatus.STATUS_END_OF_FILE || data.Length == 0)
{
break;
}
bytesRead += data.Length;
stream.Write(data, 0, data.Length);
}
stream.Seek(0, SeekOrigin.Begin);
using (var streamreader = new StreamReader(stream, Encoding.GetEncoding(932)))
{
result.Append(streamreader.ReadToEnd());
streamreader.Close();
}
}
}
else
{
result.AppendLine($"file open : {status.ToString()}");
}
status = fileStore.CloseFile(fileHandle);
status = fileStore.Disconnect();
client.Logoff();
}
else
{
result.AppendLine($"logon : {status.ToString()}");
}
client.Disconnect();
}
else
{
result.AppendLine($"not connected : {server}");
}
return Json(result.ToString());
}
And The results he tried displayed on the screen as follows:
I have the following code:
ActionResult<string> test = TestFunction();
List<string> list = test;
for (int i = 0; i < list.Count; i++ )
{
//do something with list
}
My "ActionResult test" is return Json(result.ToString());
And now, i want to convert from ActionResult to List to loop them and do something with them.
How can I convert or do any thing to loop them?
Thanks for read my post :)
Genuinely? You wouldn't do it this way
It looks like the method from your partner is either supposed to be in a controller directly,
[HttpGet]
public ActionResult<string> ReadSmbstring server, string share, string path, string username = "", string password = ""){
...
}
or the controller method is some hollow shell/passthrough like,
[HttpGet]
public ActionResult<string> Get(...){
return ReadSmb(...);
}
It's going to be harder to work with ReadSmb the way it is, than changing it so it just returns a string, and then passthrough calling it in a controller:
public ActionResult<string> ReadSmb(string server, string share, string path, string username = "", string password = "")
{
...
return result.ToString();
}
[HttpGet]
public ActionResult<string> Get(...){
return Json(ReadSmb(...));
}
Also, I do want to point out that it's going to be hard to work with all round, because it basically prepares what looks like a block of formatted text. There's barely any point in "JSONifying" that, because all it'll do is wrap it in " and turn any " inside it into \"
Json() is intended to work with objects like:
var r = new Person {
Name = "John",
Age = 22,
Address = new Address {
Street = "Infinite Loop",
City = "Cupertino"
}
}
And it'll churn out
{
"name": "John",
"age": 22,
"address": {
"street": "Infinite Loop",
"city": "Cupertino"
}
}
If you made ReadSmb return you some sensible object then it'll be a lot easier to work with, and Json()ing the result will do something reasonable which makes it a lot easier to work with at the other end of the pipe
If ReadSmb returned you a class like:
public class SmbFile{
public string FileName {get; set;}
public string Status {get; set;}
public string B64Content { get => Convert.ToBase64String(_fileContent); }
[JsonIgnore]
public byte[] FileContent { get; set;} //note, properties should not return arrays - doing for convenience of demonstrating a point
}
Then you could inspect the Status, know if there was some bytes data, read it, parse it, whatever youre planning on doing.. and it would Json() fairly sensibly too

Deadlock in Xamarin.Forms

I've got a problem with my Xamarin App. The App uses a custom API to my website. I have not much experience in async/await methods.
The following code shows the App.xaml.cs:
public partial class App : Application
{
public static bool IsUserLoggedIn { get; set; }
public static UserModel currentLoggedInUser { get; set; }
public static List<ActionTypeModel> listTypes;
public static List<ActionSubTypeModel> listSubtypes;
public static List<UserModel> listFriends;
public static List<List<ActionModel>> listActiveActions;
public static List<ActionModel> listLastAction;
public App()
{
this.InitializeComponent();
APIHelper.InitializeClient();
StartApp().Wait();
}
private async Task StartApp()
{
//// DEBUG
//MyAccountStorage.Logout();
string username = await MyAccountStorage.GetUsername().ConfigureAwait(false);
string password = await MyAccountStorage.GetPassword().ConfigureAwait(false);
string user_id = await MyAccountStorage.GetId().ConfigureAwait(false);
if (username != null && password != null)
{
currentLoggedInUser = new UserModel();
if (user_id != null)
currentLoggedInUser.user_id = Convert.ToInt32(user_id);
currentLoggedInUser.username = username;
currentLoggedInUser.password = password;
bool isValid = false;
isValid = await AreCredentialsCorrect(0, currentLoggedInUser.username, currentLoggedInUser.password).ConfigureAwait(false);
if (isValid)
{
IsUserLoggedIn = true;
await FillLists().ConfigureAwait(false);
MainPage = new NavigationPage(await MyPage.BuildMyPage().ConfigureAwait(false));
}
else
{
IsUserLoggedIn = false;
MainPage = new NavigationPage(await LoginPage.BuildLoginPage().ConfigureAwait(false));
}
}
else
{
IsUserLoggedIn = false;
MainPage = new NavigationPage(await LoginPage.BuildLoginPage().ConfigureAwait(false));
}
}
private async Task FillLists()
{
listFriends = await DataControl.GetFriends(App.currentLoggedInUser.user_id, App.currentLoggedInUser.username, App.currentLoggedInUser.password).ConfigureAwait(false);
if (listFriends == null)
listFriends = new List<UserModel>();
listTypes = await DataControl.GetTypes(App.currentLoggedInUser.username, App.currentLoggedInUser.password).ConfigureAwait(false);
if (listTypes == null)
listTypes = new List<ActionTypeModel>();
listActiveActions = new List<List<ActionModel>>();
for (int i = 0; i < listTypes.Count; i++)
listActiveActions.Add(await DataControl.GetActiveActions(listTypes[i].action_type_id, currentLoggedInUser.user_id, currentLoggedInUser.username, currentLoggedInUser.password).ConfigureAwait(false));
listSubtypes = await DataControl.GetSubtypes(App.currentLoggedInUser.username, App.currentLoggedInUser.password).ConfigureAwait(false);
if (listSubtypes == null)
listSubtypes = new List<ActionSubTypeModel>();
listLastAction = await DataControl.GetLastAction(App.currentLoggedInUser.user_id, App.currentLoggedInUser.username, App.currentLoggedInUser.password).ConfigureAwait(false);
if (listLastAction == null)
listLastAction = new List<ActionModel>();
}
public static async Task<bool> AreCredentialsCorrect(int type, string user, string pass, string nick = "", string email = "")
{
List<UserModel> listUsers;
if (type == 1)
listUsers = await DataControl.CheckCredentials(1, user, pass, nick, email).ConfigureAwait(false);
else
listUsers = await DataControl.CheckCredentials(0, user, pass).ConfigureAwait(false);
if (listUsers != null)
if (listUsers.Any())
{
currentLoggedInUser = listUsers.First();
currentLoggedInUser.password = pass;
return true;
}
return false;
}
}
I have the API in DataControl.cs:
public static async Task<List<UserModel>> CheckCredentials(int type, string username, string pass, string email = "", string nickname = "")
{
string password = APIHelper.GetHashSha256(pass);
string url = string.Empty;
if (type == 0)
url = APIHelper.ApiClient.BaseAddress + "/account/login.php?username=" + username + "&password=" + password;
if (type == 1)
{
string nick = string.Empty;
if (string.IsNullOrEmpty(nickname) == false)
nick = "&nickname=" + nickname;
url = APIHelper.ApiClient.BaseAddress + "/account/signup.php?username=" + username + "&password=" + password + "&email=" + email + nick;
}
if (string.IsNullOrEmpty(url))
return null;
using (HttpResponseMessage response = await APIHelper.ApiClient.GetAsync(url).ConfigureAwait(false))
{
if (response.IsSuccessStatusCode)
{
List<UserModel> listUsers = JsonConvert.DeserializeObject<List<UserModel>>(await response.Content.ReadAsStringAsync().ConfigureAwait(false));
return listUsers;
}
else
return null;
}
}
That's one of the different async methods. When I leave out the ConfigureAwait(false), I run into a deadlock. When I add it to the code I run into an error.
Could you please help me.
As #GSerg already wrote, you have to restructure the code. The App constructor must set the MainPage to some page. That one can be empty saying something like "Loading data".
Then you can start a background Task which retrieves the data you need.
When the data has been loaded, then you can update your page with the newly loaded data. But UI updates always have to happen on the UI thread. This is the same on all platforms. So you have to switch back with Device.BeginInvokeOnMainThread(...).
public App()
{
InitializeComponent();
APIHelper.InitializeClient();
MainPage = new LoadingPage();
// start a background thread
Task.Run(async () =>
{
try
{
await StartApp(); // load the data
// go back to the main thread
Device.BeginInvokeOnMainThread(() =>
{
// replace the MainPage with one which shows the loaded data
MainPage = new DataPage();
});
}
catch (Exception ex)
{
// handle the exception
}
});
}
You can use Task.Run(
//call your async method here
);
So in your case:
Task.Run(Startup);

capturing value of parameter

I really need your help on this guys I am stuck and not sure where to start the fix. So i have this form where the user can select a case and parties. I am supposed save and pass along the values of the selected items. I was able to save the case selections but i am having trouble saving the selected party. Here is my code snippets regarding gathering data and saving them.
CONTROLLER:
[HttpPost]
[ValidateInput(false)]
public ActionResult Create(VisitViewModel viewModel, Guid[] associatedCasesSelected, Guid[] selectedParties)
{
if (!ModelState.IsValid)
{
viewModel.Time = _timeEntryHelper.Value;
AddLookupsToViewModel(viewModel);
return View(viewModel);
}
var visitEntry = Mapper.Map<VisitViewModel, VisitEntry>(viewModel);
visitEntry.VisitDate = _timeEntryHelper.AddTimeToDate(visitEntry.VisitDate);
visitEntry.UserId = _currentUser.UserId;
visitEntry.OfficeId = _currentUser.OfficeId;
try
{
_visitEntryService.Create(visitEntry, associatedCasesSelected, selectedParties);
this.FlashInfo(string.Format(Message.ConfirmationMessageCreate, Resources.Entities.Visit.EntityName));
}
catch (RulesException ex)
{
ex.CopyTo(ModelState);
}
if (ModelState.IsValid)
return RedirectToAction("Edit", "Case", new { caseId = viewModel.CaseId });
AddLookupsToViewModel(viewModel);
return View(viewModel);
}
VisitEntryService:
public void Create(VisitEntry visitEntry,IList<Guid>caseIds, IList<Guid>partyIds )
{
EnsureValid(visitEntry);
_visitEntryRepository.Save(visitEntry);
caseIds = AddCurrentCaseToCases(visitEntry.CaseId, caseIds,partyIds);
foreach (var caseId in caseIds.Distinct())
{
var visit = new Visit {CaseId = caseId, VisitEntryId = visitEntry.VisitEntryId};
_visitService.Create(visit);
}
}
VisitEntryRepository:
public void Save(VisitEntry visitEntry)
{
if (visitEntry.VisitEntryId == Guid.Empty)
{
visitEntry.VisitEntryId = Guid.NewGuid();
visitEntry.DateCreated = DateTime.Now;
DataContext.VisitEntries.InsertOnSubmit(visitEntry);
}
else
{
var currentVisitEntry = Get(visitEntry.VisitEntryId);
if (currentVisitEntry == null) throw RepositoryExceptionFactory.Create("VisitEntry", "VisitEntryId");
currentVisitEntry.DateModified = DateTime.Now;
currentVisitEntry.VisitDate = visitEntry.VisitDate;
currentVisitEntry.VisitType =
DataContext.VisitTypes.SingleOrDefault(vt => vt.VisitTypeId == visitEntry.VisitTypeId);
currentVisitEntry.Note = visitEntry.Note;
}
DataContext.SubmitChanges();
}
I am not sure how to get this to save the selected party as it is saving the case information and selected case. Thanks for any feedback!
The save call is a bit earlier so your changes made after your fire SubmitChanges, move the SubmitChanges to the end you should good to go I believe
UPDATE
what I mean is change code like following and see if that helps
CONTROLLER:
[HttpPost]
[ValidateInput(false)]
public ActionResult Create(VisitViewModel viewModel, Guid[] associatedCasesSelected, Guid[] selectedParties)
{
if (!ModelState.IsValid)
{
viewModel.Time = _timeEntryHelper.Value;
AddLookupsToViewModel(viewModel);
return View(viewModel);
}
var visitEntry = Mapper.Map<VisitViewModel, VisitEntry>(viewModel);
visitEntry.VisitDate = _timeEntryHelper.AddTimeToDate(visitEntry.VisitDate);
visitEntry.UserId = _currentUser.UserId;
visitEntry.OfficeId = _currentUser.OfficeId;
try
{
_visitEntryService.Create(visitEntry, associatedCasesSelected, selectedParties);
this.FlashInfo(string.Format(Message.ConfirmationMessageCreate, Resources.Entities.Visit.EntityName));
DataContext.SubmitChanges();
}
catch (RulesException ex)
{
ex.CopyTo(ModelState);
}
if (ModelState.IsValid)
return RedirectToAction("Edit", "Case", new { caseId = viewModel.CaseId });
AddLookupsToViewModel(viewModel);
return View(viewModel);
}
VisitEntryRepository:
public void Save(VisitEntry visitEntry)
{
if (visitEntry.VisitEntryId == Guid.Empty)
{
visitEntry.VisitEntryId = Guid.NewGuid();
visitEntry.DateCreated = DateTime.Now;
DataContext.VisitEntries.InsertOnSubmit(visitEntry);
}
else
{
var currentVisitEntry = Get(visitEntry.VisitEntryId);
if (currentVisitEntry == null) throw RepositoryExceptionFactory.Create("VisitEntry", "VisitEntryId");
currentVisitEntry.DateModified = DateTime.Now;
currentVisitEntry.VisitDate = visitEntry.VisitDate;
currentVisitEntry.VisitType =
DataContext.VisitTypes.SingleOrDefault(vt => vt.VisitTypeId == visitEntry.VisitTypeId);
currentVisitEntry.Note = visitEntry.Note;
}
}

update date in database after user login successfull asp.net mvc

I want to record that last update of user that log in into my website. After they log in success, the laseUpdate filed must change to the current date time.
I have use this code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ICEWeb.Models
{
public class CustomerModels:ItemEntityDataContext
{
public bool ValidateCustomer(string username, string password)
{
bool b = (
this.DataContext
.Customers
.Where(s => s.ActiveInWebLogin == 1
&&
s.WebAccount == username
&&
s.Password == password
)
.SingleOrDefault()
) != null;
if (b == true)
this.UpdateCustomerLastUpdateStatus();
return b;
}
public void UpdateCustomerLastUpdateStatus()
{
Customer c = new Customer();
c.LastWebLogIn = DateTime.Now;
this.DataContext.SaveChanges();
}
}
}
The validateCustomer() is work but it is not update my record(LastWebLogIn).
Can anyone solve this for me?
Thanks.
You should not create a new instance but ise the current instance of the Customers object and update it to the database. Try something like this:
public bool ValidateCustomer(string username, string password)
{
var user = this.DataContext.Customers
.Where(s => s.ActiveInWebLogin == 1 &&
s.WebAccount == username &&
s.Password == password)
.SingleOrDefault();
if (user != null)
{
this.UpdateCustomerLastUpdateStatus(user);
return true;
}
return false;
}
public void UpdateCustomerLastUpdateStatus(Customers c)
{
c.LastWebLogIn = DateTime.Now;
this.DataContext.SaveChanges();
}
Use Table.InsertOnSubmit Method if you want to create new Customer:
var customer = new Customer();
customer.LastWebLogIn = DateTime.Now;
this.DataContext.Customers.InsertOnSubmit(customer);
this.DataContext.SubmitChanges();
If you want to update existing customer you should do following:
var customer = this.DataContext.Customers
.Where(...)
.Single();
customer.LastWebLogIn = DateTime.Now;
this.DataContext.SaveChanges();
You're setting the LastWebLogIn for an unidentified new customer. Take the customer from the database (as per your first method), and update that object (making sure you haven't optimised with a read-only data-context).
Can you try the following code :
public bool ValidateCustomer(string username, string password)
{
var customer = this.DataContext
.Customers
.Where(s => s.ActiveInWebLogin == 1
&&
s.WebAccount == username
&&
s.Password == password
)
.SingleOrDefault()
if (customer != null)
return this.UpdateCustomerLastUpdateStatus(customer);
return false;
}
public void UpdateCustomerLastUpdateStatus(Customer c)
{
try
{
c.LastWebLogIn = DateTime.Now;
this.DataContext.SaveChanges();
return true;
}
Catch(Exception ex)
{
// Log the error
return false;
}
}

Categories

Resources