I have an if statement in my Controller which decides whether a checkbox is checked or not.
It works fine in the if statement and changes the properties, but when i go to send it back to the view these changes aren't saved.
Controller
public ActionResult GetUserRights(string userLogin)
{
if (userLogin != null)
{
Manager manager = new Manager();
var userlogin = manager.GetUserData(userLogin);
var userrights = userlogin.RightsId.Select(s => new { id = s, text = s });
var rightdetails = manager.GetAllRightsRows();
var rightsDetails = from r in rightdetails
orderby r.Id
select new RightDetail
{
RightID = r.Id,
RightDescription = r.Description,
RightName = r.Name,
ParentID = r.ParentId,
TypeColor = r.TypeColor,
Value = r.Value,
Checked = false
};
foreach (var userright in userrights)
{
foreach (var rightdets in rightsDetails)
{
if(rightdets.RightID == userright.id)
{
rightdets.Checked = true;
break;
}
}
}
return View("_RightsTreeListPartial", rightsDetails); <==== ALL CHECKED
PROPERTIES ARE false EVEN THOUGH SOME ARE BEING CHANGED IN THE IF STATEMENT.
}
return View("Index");
}
Let me know if you need any more info.
Thanks
With an IEnumerable, I am not sure of the reason why, but you cannot edit an item using an if statement so the code below is correct and does what it is supposed to, however as it is IEnumerable non of the changes are saved, also the process below is very heavy and long winded for what we need to do.
Original Code
foreach (var userright in userrights)
{
foreach (var rightdets in rightsDetails)
{
if(rightdets.RightID == userright.id)
{
rightdets.Checked = true;
break;
}
}
}
The new code takes a lot less time and will therefore improve the wait time. Firstly the IEnumerable is converted to a List, then, using a for-loop, the data is iterated through until a match is found, then within an if statement the item is changed (using original code and just converting from IEnumerable to List should work but I wouldn't recommend using it).
New Code
var rightdetail = rightsDetails.ToList();
foreach (var userright in userrights)
{
for (var i = 0; i < rightdetail.Count(); i++)
{
if (rightdetail[i].RightID == userright.id)
{
rightdetail[i].Checked = true;
break;
}
}
}
Related
I am writing ASP.NET Custom Component, I want to update my view with following code below:
#if (Model.TableDatasource != null){
//Write some thing to html page example: tables or span
}
At the first, Model.TableDatasource is null, user choose information and Controller Review View(Model) like this:
var model = new PrintDeliveryTicketModel()
{
PlantList = CommonHelper.GetPlantList(),
};
if (request == null)
{
return View(model);
}
else
{
var currentPlant = JsonConvert.DeserializeObject<PlantList>(request);
var FullModel = new PrintDeliveryTicketModel()
{
PlantList = CommonHelper.GetPlantList(),
CurrentPlant = JsonConvert.DeserializeObject<PlantList>(request),
DriverList = JsonConvert.DeserializeObject<List<Drivers>>(CommonHelper.GetDriver(currentPlant.CodePlant, currentPlant.PlantNo.Value).Content.ReadAsStringAsync().Result),
CustomerList = JsonConvert.DeserializeObject<List<Customer>>(CommonHelper.GetCustomer().Content.ReadAsStringAsync().Result),
RecipeList = JsonConvert.DeserializeObject<List<Recipe>>(CommonHelper.GetRecipe(currentPlant.CodePlant, currentPlant.PlantNo.Value).Content.ReadAsStringAsync().Result),
SitesList = JsonConvert.DeserializeObject<List<Site>>(CommonHelper.GetSite().Content.ReadAsStringAsync().Result),
// TruckList = JsonConvert.DeserializeObject<List<Truck>>(CommonHelper.GetTruck().Content.ReadAsStringAsync().Result)
};
return View(FullModel);
}
At the Debug time, I notice that break-point stop at return View(FullMode) and Break-point at ViewFile(cshtml) has value. but nothing printed at view.
Hope some help.
I am implementing CoinPayments IPN in my application and I have trouble with passing data to the method that take their Callback. I have tried like everything I could find: TempData, SessionVariables, tried to implement it somewhere in forms and maybe Request it but that didn`t work for me. So I also tried to implement it with Global static variables. And it worked! But then came another issue: if more than one user were to buy something from website at the same time or even in between any callbacks their data will get mixed. So here I am, trying again to make Session Variables work and have no clue why they are not working as I used them before. Probably what I can think of is that because its a callback from CoinPayments and I handle something wrongly.
Here is the code I have right now: Tho I tried different variations like implementing Session in Get Payment method. Now I ended up with it and it still comes out as null in POST METHOD.
Class for handling Session Variables:
public static class MyGlobalVariables
{
public static int TokenChoice
{
get
{
if (System.Web.HttpContext.Current.Session["TokenChoice"] == null)
{
return -1;
}
else
{
return (int)System.Web.HttpContext.Current.Session["TokenChoice"];
}
}
set
{
System.Web.HttpContext.Current.Session["TokenChoice"] = value;
}
}
public static int PaymentChoice
{
get
{
if (System.Web.HttpContext.Current.Session["PaymentChoice"] == null)
{
return -1;
}
else
{
return (int)System.Web.HttpContext.Current.Session["PaymentChoice"];
}
}
set
{
System.Web.HttpContext.Current.Session["PaymentChoice"] = value;
}
}
public static string CurrentUser
{
get
{
System.Web.HttpContext.Current.Session["CurrentUser"] = System.Web.HttpContext.Current.User.Identity.Name;
return (string)System.Web.HttpContext.Current.Session["CurrentUser"];
}
}
}
Class that returns view where you click on CoinPayments button:
public ActionResult Payment(int tokenChoice, int paymentChoice)
{
ViewBag.Payment = paymentChoice;
MyGlobalVariables.PaymentChoice = paymentChoice;
MyGlobalVariables.TokenChoice = tokenChoice;
return View();
}
Callback class that handles Callback from CoinPayments:
[HttpPost]
public ActionResult Payment()
{
NameValueCollection nvc = Request.Form;
var merchant_id = id;
var ipn_secret = secret;
var order_total = MyGlobalVariables.PaymentChoice;
if (String.IsNullOrEmpty(nvc["ipn_mode"]) || nvc["ipn_mode"] != "hmac")
{
Trace.WriteLine("IPN Mode is not HMAC");
return View();
}
if (String.IsNullOrEmpty(HTTP_HMAC))
{
Trace.WriteLine("No HMAC signature sent");
return View();
}
if (String.IsNullOrEmpty(nvc["merchant"]) || nvc["merchant"] != merchant_id.Trim())
{
Trace.WriteLine("No or incorrect Merchant ID passed");
return View();
}
//var hmac = hash_hmac("sha512", request, ipn_secret.Trim());
var txn_id = nvc["txn_id"];
var item_name = nvc["item_name"];
var item_number = nvc["item_number"];
var amount1 = nvc["amount1"];
var amount2 = float.Parse(nvc["amount2"], CultureInfo.InvariantCulture.NumberFormat);
var currency1 = nvc["currency1"];
var currency2 = nvc["currency2"];
var status = Convert.ToInt32(nvc["status"]);
var status_text = nvc["status_text"];
Trace.WriteLine(status);
if (currency1 != "USD") {
Trace.WriteLine("Original currency mismatch!");
return View();
}
if (Convert.ToInt32(amount1) < Convert.ToInt32(order_total))
{
Trace.WriteLine("Amount is less than order total!");
return View();
}
if (status >= 100 || status == 2) {
using (MyDatabaseEntities1 dc = new MyDatabaseEntities1())
{
var account = dc.Users.Where(a => a.Username == MyGlobalVariables.CurrentUser).FirstOrDefault();
if (account != null && account.Paid == 0)
{
Trace.WriteLine("Payment Completed");
Trace.WriteLine("Tokens to add: " + MyGlobalVariables.TokenChoice);
account.Tokens += MyGlobalVariables.TokenChoice;
account.Paid = 1;
dc.Configuration.ValidateOnSaveEnabled = false;
dc.SaveChanges();
}
}
} else if (status < 0)
{
Trace.WriteLine(
"payment error, this is usually final but payments will sometimes be reopened if there was no exchange rate conversion or with seller consent");
} else {
using (MyDatabaseEntities1 dc = new MyDatabaseEntities1())
{
var account = dc.Users.Where(a => a.Username == MyGlobalVariables.CurrentUser).FirstOrDefault();
if (account != null)
{
account.Paid = 0;
dc.Configuration.ValidateOnSaveEnabled = false;
dc.SaveChanges();
}
}
Trace.WriteLine("Payment is pending");
}
return View();
}
As you can see there are only 3 variables I need to handle.
Also someone might ask why I use Session Variable for Current.User?
Well for some reason Callback method can not read Current.User as it return null. And well... nothing really changed as for now.
If you have ever experienced something like that or can find an issue I would be so thankful since I wasted already over 2 days on that issue.
EDIT:
After some testing I found out variables works fine if I run Post method on my own. So the problem is with handling callback from CoinPayments. Is there a specific way to deal with this?
I get this error when running this code. I have looked for solution though I don't like the idea of using MARS as people have suggested as it may contain a lot of data, is there any other option here? Also can I edit a variable in a database without rewriting all of them as I do here, will this save server power or make no difference?
There is already an open DataReader associated with this Command which must be closed first.
public ActionResult CheckLinks(Link model)
{
var userId = User.Identity.GetUserId();
var UserTableID = db.UserTables.Where(c => c.ApplicationUserId == userId).First().ID;
foreach (var item in db.Links.Where(p => p.UserTable.ID == UserTableID))
{
string pageContent = null;
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(item.Obdomain);
HttpWebResponse myres = (HttpWebResponse)myReq.GetResponse();
using (StreamReader sr = new StreamReader(myres.GetResponseStream()))
{
pageContent = sr.ReadToEnd();
}
string live = "";
if (pageContent.Contains(item.Obpage))
{
live = "Yes";
}
else { live = "No"; }
var link = new Link { Obdomain = item.Obdomain, ClientID = item.ClientID, Obpage = item.Obpage, BuildDate = item.BuildDate, Anchor = item.Anchor, IdentifierID = item.IdentifierID, live = (Link.Live)Enum.Parse(typeof(Link.Live), live), UserTableID = item.UserTableID };
db.Entry(link).State = EntityState.Modified;
db.SaveChanges();
}
return RedirectToAction("Index");
}
Entity Framework allows only one active command per context at a time. You should add .ToList() at the end of the following statement:
db.Links.Where(p => p.UserTable.ID == UserTableID).ToList();
So your code could look like this:
var items = db.Links.Where(p => p.UserTable.ID == UserTableID).ToList();
foreach (var item in items)
I'm wondering how I could get a list of members of an AD group.
Checking if an entered password of a user is correct works perfectly fine. For this I'm using Novell's Ldap.NetStandard:
private bool IsUserValid(string userName,string userPassword)
{
try{
using (var connection = new LdapConnection { SecureSocketLayer = false })
{
connection.Connect("test.local", LdapConnection.DEFAULT_PORT);
connection.Bind(userDn, userPassword);
if (connection.Bound)
{
return true;
}
}
}
catch (LdapException ex)
{
Console.WriteLine(ex.Massage);
}
return false;
}
What I want now is something like this:
bool isUserInGroup("testUser","testGroup");
The problem is I can't get my method working:
public bool IsUserMemberOfGroup(string userName,string groupName)
{
var ldapConn = GetConnection();
var searchBase = "";
var filter = $"(&(objectClass=group)(cn={groupName}))";
var search = ldapConn.Search(searchBase, LdapConnection.SCOPE_BASE, filter, null, false);
while (search.hasMore())
{
var nextEntry = search.next();
if (nextEntry.DN == userName)
return true;
}
return false;
}
What ever I'm doing, I'm not getting back any value from my Ldap.Search()...
Now there is an implementation of System.DirectoryServices.AccountManagement for .NET Core 2. It is available via nuget.
With this package you are able to things like that:
using (var principalContext = new PrincipalContext(ContextType.Domain, "YOUR AD DOMAIN"))
{
var domainUsers = new List<string>();
var userPrinciple = new UserPrincipal(principalContext);
// Performe search for Domain users
using (var searchResult = new PrincipalSearcher(userPrinciple))
{
foreach (var domainUser in searchResult.FindAll())
{
if (domainUser.DisplayName != null)
{
domainUsers.Add(domainUser.DisplayName);
}
}
}
}
This performs a search for the user in your domain.Nearly the same is possible for searching your group. The way I used to search my AD (description in my question) is now obsolet:
Checking if an entered password of a user is correct works perfectly
fine. For this I'm using Novell's Ldap.NetStandard:
How about:
HttpContext.User.IsInRole("nameOfYourAdGroup");
(namespace System.Security.Claims)
When I try to save the events to the store I get the following exception:
The commit must be uniquely identified.\r\nParameter name: attempt
But my code always generates a new New Guid for the commit (as per NEventStore example)
public void Save(Guid aggregateId, IEnumerable<Event> events, int expectedVersion)
{
var eventList = events as IList<Event> ?? events.ToList();
using (var scope = new TransactionScope())
using (var stream = store.OpenStream(aggregateId, 0, int.MaxValue))
{
if(stream.StreamRevision != expectedVersion)
throw new ConcurrencyException();
foreach (var #event in eventList)
{
stream.Add(new EventMessage { Body = #event });
}
stream.CommitChanges(Guid.NewGuid());
scope.Complete();
}
foreach (var #event in eventList)
{
publisher.Publish(#event);
}
}
Does anyone have any idea why this is happening?
The message is misleading. It is thrown here when this check...
attempt.StreamId != Guid.Empty && attempt.CommitId != Guid.Empty
Is false. So it should say: both the CommitId and StreamId must not be empty.