XNA: Does the position of mouseState matter? - xna

In order to get a single click response from MouseState, I use this line.
currentMouseState.LeftButton == ButtonState.Pressed && oldMouseState.LeftButton == ButtonState.Released)
And at the end of the method I have this line which sets the mouse state.
oldMouseState = currentMouseState;
My question to you is does the position of the above line matter in a method which has multiple loops? Is this:
foreach (blah blah in blahs)
{
if (something is something)
{
if (currentMouseState.LeftButton == ButtonState.Pressed && oldMouseState.LeftButton == ButtonState.Released)
{
do something
}
}
}oldMouseState = currentMouseState;
Different from this?
foreach (blah blah in blahs)
{
if (something is something)
{
if (currentMouseState.LeftButton == ButtonState.Pressed && oldMouseState.LeftButton == ButtonState.Released)
{
do something
}
}oldMouseState = currentMouseState;
}

In your first example, you have your mouseState update outside the FOREACH loop. This makes everything in the FOREACH loop execute before the mouseState updates.
In your second example, you update the mouseState inside of your FOREACH loop, which is strange, but if you did, after the first looped item, the second if statement would fail and you would not "do something".

Related

Handling Next Record nullable reference Controller Code to pass to viewbag

I have researched various nullable reference handling posts, but not finding anything helpful. So what I am doing below to handle this null reference (it's a hack for now to stop the error page from displaying to users) is to essentially return the current id if a next record does not exist in my edit controller.
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var myInClause = new string[] { "a", "c", "k" };
var myQueryResults = await _context.MyClass.FindAsync(id);
int? NextIdObject = (from i in _context.MyClass
where myInClause.Contains(i.RowType) && (i.Id > myclass.Id)
select new { i.Id }).DefaultIfEmpty().First().Id;
if (!NextIdObject.Equals(0))
{
ViewBag.nextID = NextIdObject;
}
else
{
ViewBag.nextID = id;
}
if (myQueryResults == null)
{
return NotFound();
}
return View(myQueryResults);
}
I would prefer to just redirect to the index page (if they hit this error, it means they are done working through a queue anyway, no next record would ever exist here). Or maybe just keep the code as is and display a message on the button to indicate end of list. Any thoughts here. Note, using any +1 increment on the id does not work for me, as I don't need the user to see all id records, just the one's with a/c/k which is why I bring the myInclause variable in. If there is a better way to use the SQL sytanx of "IN" for Linq queries, I am all ears.
I would prefer to just redirect to the index page (if they hit this
error, it means they are done working through a queue anyway, no next
record would ever exist here)
You could use try...catch block simply like
try
{
var myInClause = new string[] { "a", "c", "k" };
var myQueryResults = await _context.MyClass.FindAsync(id);
int NextIdObject = (from i in _context.MyClass
where myInClause.Contains(i.RowType) && (i.Id > myclass.Id)
select new { i.Id }).DefaultIfEmpty().First().Id;
ViewBag.nextID = NextIdObject;
}
catch(Exception ex)
{
return RedirectToAction("Index");
//or return View("Index");
}
return View(myQueryResults);

MVC Session global variable

Here is what I'm trying to achieve. Certain options at the navbar should be available only if the user has "subordinates" in the database.
So, at the navbar I have:
The Approvals should be hidden for some users, but available to others. For those whom it should be available, the user must:
A) Be a Supervisor or,
B) Have a subornidate at the DB table
So, as for "A" it's pretty straightforward. I did:
#if (User.IsInRole("Supervisor"))
{
<li>#Html.ActionLink("Approvals", "Index", "Approval")</li>
}
For "B", I was suggested to use Sessions. Well, great. So I came to the question: how can I make a single request to the DB and assign it to a Session["HasSubordinates"] so I can do this check?
#if (User.IsInRole("Supervisor") || (bool)Session["HasSubordinates"])
{
<li>#Html.ActionLink("Approvals", "Index", "Approval")</li>
}
What I tried was to have:
Session["HasSubordinates"] = _uow.ApprovalService.GetSubordinates(User.Identity.Name).Count() > 0;
for every single controller, but that didn't worked well because sometimes I get null pointer and it looks absolutely rubbish.
I know it may sound like a trivial question for some (or most), but I'm really stuck and I do really appreciate any help.
Looking at your code, getting a user subordinates should only happen once. In your Login method:
Session["HasSubordinates"] = _uow.ApprovalService.GetSubordinates(User.Identity.Name).Count() > 0;
Create a new class to extend IPrincipal:
public class IPrincipalExtensions
{
public bool HasSubordinates(this IPrincipal user)
{
return Session != null && Session["HasSubordinates"] != null && Session["HasSubordinates"] > 0;
}
}
Now, in the View:
#if (User.IsInRole("Supervisor") || User.HasSubordinates() )
{
}
Writing from memory, may have left something out, but this should be the cleanest.
Don't use the session for this. What you need is a child action.
[ChildActionOnly]
public ActionResult Nav()
{
var model = new NavViewModel
{
IsSupervisor = User.IsInRole("Supervisor");
HasSubordinates = _uow.ApprovalService.GetSubordinates(User.Identity.Name).Count() > 0;
}
return ParialView("_Nav", model);
}
Then, just create a partial view, _Nav.cshtml and utilize the properties on the view model to render your nav however you like.
If you want, you can even use output caching on the child action, so it's only evaluated once per user. There's no built-in way to vary the cache by user, so first, you'll need to override the following method in Global.asax:
public override string GetVaryByCustomString(System.Web.HttpContext context, string custom)
{
var args = custom.ToLower().Split(';');
var sb = new StringBuilder();
foreach (var arg in args)
{
switch (arg)
{
case "user":
sb.Append(User.Identity.Name);
break;
case "ajax":
if (context.Request.Headers["X-Requested-With"] != null)
{
// "XMLHttpRequest" will be appended if it's an AJAX request
sb.Append(context.Request.Headers["X-Requested-With"]);
}
break;
default:
continue;
}
}
return sb.ToString();
}
With that, you can then just decorate your child action with:
[OutputCache(Duration = 3600, VaryByCustom = "User")]

Is there a way to flush the contents of a view at some point without using if-else statements?

Is there a way to flush the contents of a view at some point without using if-else statements?
For example, If I'm listing a bunch of records using a table, but I don't need the headers if no rows are found: maybe a message saying, "No data found". I'd like to:
if (records.count == 0) {
<div>No Data</div>
return; //flush/render view
}
//no else
<table><tr><th>......</tr>
foreach (var record in records) {
<tr><td>....</tr>
}
</table>
Makes sense? Or I'm just being lazy: I hate huge chunks of nested code, especially inside a view where indentation is not so sleak.
Try like this, it should work:
#if (records.count == 0)
{
<div>No Data</div>
return;
}
<table>
<tr><th>......</tr>
foreach (var record in records)
{
<tr><td>....</tr>
}
</table>
If the condition (records.count == 0) is satisfied only No Data will be printed on the Razor view and the subsequent code will never be executed and the table will never be shown.

Rhino-ETL Conditional Operation

I want to check the value of a row field value and depending on the value run a specific operation. Can this be done. Part of the code is below
public override IEnumerable<Row> Execute(IEnumerable<Row> rows)
{
foreach (Row row in rows)
{
if (row["ProductAction"] == "Update")
{
_updateProductOperation.Execute(rows);
}
else
{
_addProductOperation.Execute(rows);
}
yield return row;
}
}
Someone answered me on another forum in case any one is interested. They said you'd do this with a branching operation were the one branch would check for "Update" and the other would check for != "Update".

Groovy/Grails code cleanup suggestions, please!

I'm new to Groovy & Grails, and I have a feeling that things don't have to be this ugly... so how can I make this code nicer?
This is a Grails controller class, minus some uninteresting bits. Try not to get too hung up that my Car only has one Wheel - I can deal with that later :-)
changeWheel is an Ajax action.
class MyController {
...
def changeWheel = {
if(params['wheelId']) {
def newWheel = Wheel.findById(params['wheelId'])
if(newWheel) {
def car = Car.findById(params['carId'])
car?.setWheel(newWheel)
if(car?.save()) render 'OK'
}
}
}
}
I'd actually start using Command Objects.
Try this:
class MyController {
def index = {
}
def changeWheel = { CarWheelCommand cmd ->
if(cmd.wheel && cmd.car) {
Car car = cmd.car
car.wheel = cmd.wheel
render car.save() ? 'OK' : 'ERROR'
} else {
render "Please enter a valid Car and wheel id to change"
}
}
}
class CarWheelCommand {
Car car
Wheel wheel
}
and then in your view use 'car.id' and 'wheel.id' instead of 'carId' and 'wheelId'
1) pull
params['wheelId']
and
params['carId']
out into their own defs
2) multiple nested ifs is never optimal. You can get rid of the outermost one by having a validateParams method and rendering some sort of response if wheelId and carId are not set. Or just do
if (carId == null || wheelId == null) {
// params invalid
}
3) Assuming everything is ok you could just do
def newWheel = Wheel.findById...
def car = Car.findById...
if (car != null && newWheel != null) {
car.setWheel(newWheel)
car.save()
render 'OK'
} else {
// either wheel or car is null
}
this gets rid of more nested structures...
4) finally, to make the code self documenting, you can do things like assign the conditional tests to appropriately named variables. So something like
def carAndWheelOk = car != null && newWheel != null
if (carAndWheelOk) {
// do the save
} else {
// car or wheel not ok
}
this might be overkill for two tests, but you only are taking care of one wheel here. If you were dealing with all 4 wheels, this type of things increases readability and maintainability.
Note that this advice works in any language. I don't think you can do too much with groovy's syntactic sugar, but maybe some groovy gurus can offer better advice.
There are a couple of things you could do like move some code to a service or command object. But without altering the structure too much, I (subjectively) think the following would make the code easier to read:
use dot notation instead of array indexing to reference params values (params.wheelId instead of params['wheelId'])
I would invert the if to reduce nesting, I think this makes it more clear what the exceptions are.
For example:
if(!params.wheelId) {
sendError(400, "wheelId is required")
return
}
....
....
if(!newWheel) {
sendError(404, "wheel ${params.wheelId} was not found.")
return
}
Now if you don't mind changing the structure and adding more lines of code...
The act of changing the wheel may be a common occurrence across more than just one controller action. In this case I'd recommend putting the GORM/database logic in a Service class. Then your controller only has to verify it has the correct params inputs and pass those on to the Service to do the actual tire changing. A Service method can be transactional, which you'd want in the case where you might have to dismount the old tire before mounting the new one.
In the Service I would throw exceptions for exceptional cases like when a wheel is not found, a car is not found, or if there's an error changing the tire. Then your controller can catch those and respond with the proper HTTP status codes.

Resources