Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Mr Shiny Pants
Nov 12, 2012
What do you guys use for session handling?

Session handling is not really the right word I guess, what do you use to keep models in memory if you know you need them again later?

It seems a bit of a waste the retrieve the same classes over the course of multiple controllers from the DB, instantiate them, use them and discard them again only to re-instantiate them a bit later.

Just retrieve them again or use some form of caching?

Adbot
ADBOT LOVES YOU

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy
Note that if you're dealing with multiple web servers, caching and cache invalidation becomes a harder problem. However, with just one web server you can either use something as simple as static variables (with thread-safe access), or possibly use the built-in ASP.NET caching.

See:
http://msdn.microsoft.com/en-us/library/vstudio/ms178597%28v=vs.100%29.aspx
http://msdn.microsoft.com/en-us/library/vstudio/18c1wd61%28v=vs.100%29.aspx

wwb
Aug 17, 2004

Measure what the cost is -- you'd be shocked at how efficent modern stuff is. 99% of the time you can make zero real-world performance gains on the back end of your website that are measurable compared to things you can do on the front end like edge caching and compression. My 2c is the best going in proposition is to leave caching for anything longer than a single request until you have measurable performance gains you can get by caching it.

That said the key thing to think about is how long is the object life cycle? And how mutable are things? IE we have configuration objects that get hydrated on start and don't mutate and you can cache the living poo poo out of them. But anything violate is a bitch to cache, or really requires a cache invalidation strategy.

If you are really depending on the object to be there don't use ASP.NET's cache. At least the .NET 2.0 implementation would start ejecting things at the first sign of memory trouble. If you did something really retarded like have a cache callback to re-cache an object on ejection you got nasty loops. It really was written to be an output cache for the pages not a memcached equivalent.

Dr. Poz
Sep 8, 2003

Dr. Poz just diagnosed you with a serious case of being a pussy. Now get back out there and hit them till you can't remember your kid's name.

Pillbug
Mvc Question

My action method takes an int but if a jerk types in a string they get send to a runtime error page. I'd much rather send them to an error page of my design. What's the best way to handle parameter validation of this fashion for action methods?

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy

Dr. Poz posted:

Mvc Question

My action method takes an int but if a jerk types in a string they get send to a runtime error page. I'd much rather send them to an error page of my design. What's the best way to handle parameter validation of this fashion for action methods?

Use int? and check for nulls.

Optionally, if you just want to send them to a custom error page without any special message, use the <customErrors> tag with a redirect in the web.config.

Mr Shiny Pants
Nov 12, 2012

Bognar posted:

Note that if you're dealing with multiple web servers, caching and cache invalidation becomes a harder problem. However, with just one web server you can either use something as simple as static variables (with thread-safe access), or possibly use the built-in ASP.NET caching.

See:
http://msdn.microsoft.com/en-us/library/vstudio/ms178597%28v=vs.100%29.aspx
http://msdn.microsoft.com/en-us/library/vstudio/18c1wd61%28v=vs.100%29.aspx


wwb posted:

Measure what the cost is -- you'd be shocked at how efficent modern stuff is. 99% of the time you can make zero real-world performance gains on the back end of your website that are measurable compared to things you can do on the front end like edge caching and compression. My 2c is the best going in proposition is to leave caching for anything longer than a single request until you have measurable performance gains you can get by caching it.

That said the key thing to think about is how long is the object life cycle? And how mutable are things? IE we have configuration objects that get hydrated on start and don't mutate and you can cache the living poo poo out of them. But anything violate is a bitch to cache, or really requires a cache invalidation strategy.

If you are really depending on the object to be there don't use ASP.NET's cache. At least the .NET 2.0 implementation would start ejecting things at the first sign of memory trouble. If you did something really retarded like have a cache callback to re-cache an object on ejection you got nasty loops. It really was written to be an output cache for the pages not a memcached equivalent.

Thanks I'll take a look and think about it some more. The cache problems you mention are something I would like to avoid.
Some Redis Pub Sub is something that I was thinking about. Publish the update on one server and have the caching server subscribe to that. Bit overkill for now but something that could work in theory.
It just feels wasteful :) I'll benchmark it first.

Another question: I am using Bcrypt.net for my password hashing and it really takes quite awhile to validate the password. I know this is the point of the whole bcrypt library but I was wondering if any of you have used this before and what some sane defaults are.

Mr Shiny Pants fucked around with this message at 20:55 on Aug 6, 2014

Mr. Crow
May 22, 2008

Snap City mayor for life

Mr Shiny Pants posted:

It does not do that for me, maybe only in Chrome?



I would show the dropdown and make it as wide as the widest option.

Tab completion and the possibility to select an item is what I would do.

How to build it in WPF? No clue, sorry.

ComboBox is unfortunately not very extensible, so you may end up having to re-write it (don't make that assumption yet though).

This specific example however probably isn't a big deal.

I would look at it's template, you'll have to copy it to modify what you need to modify but just quickly glancing at it you should be able to tweak it and allow the drop down to always show (IsDropDownOpen).

Something that will probably determine the pain level is and whether or not this is helpful is how the selected value in the pop-up is updated, whether it tries to resolve the selected item after the textbox loses focus or as it's changing, I don't know.

http://msdn.microsoft.com/en-us/library/ms752094(v=vs.110).aspx for the style (template is baked into it).

Dr. Poz
Sep 8, 2003

Dr. Poz just diagnosed you with a serious case of being a pussy. Now get back out there and hit them till you can't remember your kid's name.

Pillbug

Bognar posted:

Use int? and check for nulls.

Optionally, if you just want to send them to a custom error page without any special message, use the <customErrors> tag with a redirect in the web.config.

Perfect. Thanks Bognar!

wwb
Aug 17, 2004

Dr. Poz posted:

Mvc Question

My action method takes an int but if a jerk types in a string they get send to a runtime error page. I'd much rather send them to an error page of my design. What's the best way to handle parameter validation of this fashion for action methods?

Better way is to handle it in routing and constrain your routes rather than just take defaults. At least for public-facing web apps. With attribute routing this is really fun and easy now.

RICHUNCLEPENNYBAGS
Dec 21, 2010
edit: whoops, never mind.

Mr Shiny Pants
Nov 12, 2012
I have to admit the whole DataAnnotation stuff is pretty awesome in MVC5.

All the validation rules you don't need to write by hand, phew.

wwb
Aug 17, 2004

Not as awesome as fluentvalidation.

But they are nice.

Wozbo
Jul 5, 2010
Pet project question:

I'm thinking of doing something along the lines of Delta-Oriented-Architecture (that's the most apt name I can come up with). As long as it's not DOA (heh), I'm thinking of loving around with having multiple machines accessing a shared resource, and it's invisibly handled by deltas.

(extremely) lovely example:

Running resource counter or some poo poo with value of 100.

Actor A tries to set to 125 (delta +25).

Actor B tries to set to 85 (delta -15).

So on and so forth, and my libs would figure out how to apply deltas from people trying to be, like, RESTful. Any libs that do this already (AKA is this a waste of time)? I gave a really poo poo example but I'm basically trying to have fun with a problem that comes with concurrent RESTful APIs.

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy
Sounds very similar to Event Sourcing to me. Changes to the model are described as events, and those events are applied in order. Events can be written to a database or queue extremely quickly and then processed separately. The end result is high scalability at the expense of immediate updates.

You probably won't find too many libraries for this since the events are highly specific to your domain model. Also, for the vast majority of the time you can get away with simple CRUD anyway.

Wozbo
Jul 5, 2010
Yeah I'm thinking of writing something that attempts to do this automatically (not sure of how to insert yet). I'll post any results as I get em. Its just a fartin around project.

aBagorn
Aug 26, 2004
So as part of a side project, I've decided to spin off scraping NFL GameCenter's JSON data into a full fledged .NET API, which I will throw on GitHub and allow for open source usage.

Where I'm running into some trouble, from a conceptual perspective, is storage. The other API that I've seen for this has a script that pulls live game data every 15 minutes (or on request) into a flat file system and then all queries are done off of that. I think there's something to be said for locally storing the data, but I can't decide what storage solution to use. SQL Compact? Flat File JSON? I need to come up with a system that will just allow anyone to grab my DLL(s) and integrate without them having to setup the storage, but, like I said, I'm stuck.

If I'm not explaining this right or anyone needs clarification, let me know.

e:\/ SQLite looks like a pretty nice fit. Looking at sqlite-net (https://github.com/praeclarum/sqlite-net) it looks like it has enough functionality that I could do without a standalone ORM. Thanks a bunch!

aBagorn fucked around with this message at 23:00 on Aug 7, 2014

Chill Callahan
Nov 14, 2012
SQLite should do the job.

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.
I've got a class with some static and some non-static methods, and I'd like to lazily check the existence of system setup / default configurations whenever the class is referenced. Is the following a bad idea for any reason?

C# code:
Class Foo
{
 private static bool initialized = InitClass();
 private static bool InitClass()
 {
  // check that necessary directory structure is in place
  // check that a 'default' foo is in place
  return true;
 }
}
I figure that InitClass() will now be called only when the class is first referenced at runtime for any given run of the program, and will run before any static method or constructor since the class needs to initialize all of its static variables before running any of its meat code.

Mr Shiny Pants
Nov 12, 2012

Bognar posted:

Sounds very similar to Event Sourcing to me. Changes to the model are described as events, and those events are applied in order. Events can be written to a database or queue extremely quickly and then processed separately. The end result is high scalability at the expense of immediate updates.

You probably won't find too many libraries for this since the events are highly specific to your domain model. Also, for the vast majority of the time you can get away with simple CRUD anyway.

To be honest I find CRUD to be not simple at all most of the times. I mean, looking at something like MVC with Entity Framework to do some CRUD operations is pretty complex stuff.

For my own project I first went with Nhibernate, switched to EF and later decided to go with PetaPoco for my DB operations because saving an object graph is hard I guess. It is, don't get me wrong, but that is what your ORM should be doing for you and in my, admittedly limited, experience they don't do a good job. Something as simple as order -> order item makes EF want to reinsert stuff again that it should not be doing. Looking at some blogs I am not the only who has this problem. (Attach object, set model state etc. etc.)

This requires you to jump through hoops with FK keys as strings in your model for one - to many relations. Nhibernate worked better, especially with fluent Nhibernate but all the mapping and lazy loading stuff makes it a complex beast to get going, let alone trying to figure out what broke if it decides to stop working.

With PetaPoco I just insert an order, retrieve the sequencenumber it generated and update the orderitem FK with this number and insert all the items in two stages. It is more work, but it is much simpler to reason about what your data access is doing.

Event Sourcing is pretty awesome, something like Akka persistence makes the whole object - relational impedance mismatch go away. CQRS is also neat.

Sagacity
May 2, 2003
Hopefully my epitaph will be funnier than my custom title.

Mr Shiny Pants posted:

something like Akka persistence makes the whole object - relational impedance mismatch go away. CQRS is also neat.
It gives you a different set of problems, though. It's good to have immutable events, but you will never escape the fact that sometimes you designed your events in the wrong way.

Mr Shiny Pants
Nov 12, 2012

Sagacity posted:

It gives you a different set of problems, though. It's good to have immutable events, but you will never escape the fact that sometimes you designed your events in the wrong way.

True. There is no silver bullet, but if you design something wrong no pattern or architecture is going to help you.

gariig
Dec 31, 2004
Beaten into submission by my fiance
Pillbug

Newf posted:

I've got a class with some static and some non-static methods, and I'd like to lazily check the existence of system setup / default configurations whenever the class is referenced. Is the following a bad idea for any reason?

C# code:
Class Foo
{
 private static bool initialized = InitClass();
 private static bool InitClass()
 {
  // check that necessary directory structure is in place
  // check that a 'default' foo is in place
  return true;
 }
}
I figure that InitClass() will now be called only when the class is first referenced at runtime for any given run of the program, and will run before any static method or constructor since the class needs to initialize all of its static variables before running any of its meat code.

InitClass will be called at startup because the runtime wants to create the variable initialized. It sounds like you want Lazy<T>. Without a better sample it's hard to say if this is good or bad. I'd lean toward not doing it because it's hard to mock out or hide static anything during a unit test.

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy

gariig posted:

InitClass will be called at startup because the runtime wants to create the variable initialized. It sounds like you want Lazy<T>. Without a better sample it's hard to say if this is good or bad. I'd lean toward not doing it because it's hard to mock out or hide static anything during a unit test.

Jon Skeet has a useful post on static variables and initialization:

http://csharpindepth.com/Articles/General/Beforefieldinit.aspx

Long story short, if you really want to continue using statics to do a lazy check, add a static constructor and initialize your variable there. In general, though, it's better to not try to rely on edge case scenarios of the CLR for lazy loading and just implement it yourself. Use Lazy<T> or maybe something like:

C# code:
class Foo
{
    private static bool? _initialized;
    private static bool Initialized
    {
        { get { return _initialized ?? (_initialized = InitClass()).Value; } }
    }

    private bool InitClass() { return true; }
    // ...
}

ljw1004
Jan 18, 2005

rum

gariig posted:

InitClass will be called at startup because the runtime wants to create the variable initialized.

Wait, what? That's not what the link says. It says:

MSDN posted:

As is the case with all class types, the type information for a static class is loaded by the .NET Framework common language runtime (CLR) when the program that references the class is loaded. The program cannot specify exactly when the class is loaded. However, it is guaranteed to be loaded and to have its fields initialized and its static constructor called before the class is referenced for the first time in your program

In practice, the JIT compiles a method only at the first time the method is invoked. At that moment it first chases down every type that's touched by the method, and ensures they're all loaded. The type-load process will invoke all static constructors (hence, will initialize all static variables).

I don't know when static constructors are invoked in ProjectN (native compilation of C#)

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.

gariig posted:

InitClass will be called at startup because the runtime wants to create the variable initialized. It sounds like you want Lazy<T>. Without a better sample it's hard to say if this is good or bad. I'd lean toward not doing it because it's hard to mock out or hide static anything during a unit test.

Lazy<T> would be the way to go except that the project is 3.5. I've run this code though, and it didn't run at startup - the class itself isn't static, so that's probably the difference.

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy

ljw1004 posted:

Wait, what? That's not what the link says. It says:

In practice, the JIT compiles a method only at the first time the method is invoked. At that moment it first chases down every type that's touched by the method, and ensures they're all loaded. The type-load process will invoke all static constructors (hence, will initialize all static variables).

I don't know when static constructors are invoked in ProjectN (native compilation of C#)

I don't think that's completely true. See this other Jon Skeet link about what happens without an explicit static constructor:

http://codeblog.jonskeet.uk/2010/01/26/type-initialization-changes-in-net-4-0/

EDIT: Though you are correct that it won't necessarily be called at startup.

gariig
Dec 31, 2004
Beaten into submission by my fiance
Pillbug

ljw1004 posted:

In practice, the JIT compiles a method only at the first time the method is invoked. At that moment it first chases down every type that's touched by the method, and ensures they're all loaded. The type-load process will invoke all static constructors (hence, will initialize all static variables).

You are correct. I was dumb. I create a console application and put the static items in the class Program so InitClass is called before application startup because the .NET runtime create the Program class. Creating another non-static class and putting in the static member and method has the creation wait until you touch the class.

EDIT: Was the initialization changed since Skeet's blog post? I tried the "Eager initialization: .NET 3.5" example and it printed out "Type initialized" when the class was touched. Changing the targeted .NET version didn't help. I don't have VS2008 installed and I'm too lazy to grab it

gariig fucked around with this message at 18:36 on Aug 8, 2014

kingcrimbud
Mar 1, 2007
Oh, Great. Now what?
I'm in the middle of creating a service that consumes something like 100 other services. My service will have its own model. Let's say my model has a Pet entity. And 15 of these other services have their own representations of what a pet is.

If I search these other systems and then try to represent these pets in my system, how can I model that correctly when each system has their own representation of a pet?

We've explored inheritance and creating a type per system. This gets really ugly fast and will be awful to maintain.
We've also explored decorating and compositing but again, this gets really complicated very quickly. In some cases, a Pet entity may have to have 20 new properties tacked on.

I'm currently looking at using the DynamicObject class and having my Pet inherit from it. I'm losing out on some safety and probably performance, but I can just set whatever properties I want on my Pet whenever I want.

Anyone experience a situation like this and come up with a good answer?

Mr Shiny Pants
Nov 12, 2012

kingcrimbud posted:

I'm in the middle of creating a service that consumes something like 100 other services. My service will have its own model. Let's say my model has a Pet entity. And 15 of these other services have their own representations of what a pet is.

If I search these other systems and then try to represent these pets in my system, how can I model that correctly when each system has their own representation of a pet?

We've explored inheritance and creating a type per system. This gets really ugly fast and will be awful to maintain.
We've also explored decorating and compositing but again, this gets really complicated very quickly. In some cases, a Pet entity may have to have 20 new properties tacked on.

I'm currently looking at using the DynamicObject class and having my Pet inherit from it. I'm losing out on some safety and probably performance, but I can just set whatever properties I want on my Pet whenever I want.

Anyone experience a situation like this and come up with a good answer?

The easiest is probably the dynamic object. Otherwise you'll have to do something like writing connectors for each service that will transform the incoming pet to your representation.

How will you query the properties? I mean some pet could have the property "Name" others the property "name" etc. etc. You'll never have an exact representation of your entity.

This is something XSDs were invented for.

Mr Shiny Pants fucked around with this message at 20:22 on Aug 8, 2014

Sedro
Dec 31, 2008
Have your interface to those services only deal with your own Pet model which has the properties you care about. If there is some agreed-upon Pet ID, use that (obviously pets don't have unique IDs but your domain might). Basically, don't pollute your system with other systems' representations--convert all Pets to your own representation ASAP.

NihilCredo
Jun 6, 2011

iram omni possibili modo preme:
plus una illa te diffamabit, quam multæ virtutes commendabunt

At some point in the next few months, we might have to convert a large solution from VB.Net to C#. Is there a general consensus on what is the most reliable translation tool available on the market?

Dirk Pitt
Sep 14, 2007

haha yes, this feels good

Toilet Rascal
I am doing a lot of work with xamarin lately and saw they are offering a subscription model for their indie package. $25 per month per platform instead of shelling out $600 at once. I think it is good if you want to build am app but aren't ready to buy a license up front once the thirty day trial expires.

Xamarin studio is not visual studio, but it has a lot of good things like nuget and a nice component store. Also, they recently added vertical tabs, which is a god send.

Essential
Aug 14, 2003
I have a data upload process I need to run at a certain point and I need to check every 30 seconds if it's time to upload. Then when I am uploading data I don't want to check again until the process is complete. Once complete I need to start checking every 30 seconds again.

EDIT: This DOES appear to be working as intended, I had some bad test code firing it off more than once.
code:
uploadTimer = new System.Threading.Timer(t => CheckDataUpload(), null, 30000, System.Threading.Timeout.Infinite);
What do you guys typically use in this situation?

Essential fucked around with this message at 18:09 on Aug 9, 2014

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

Essential posted:

I have a data upload process I need to run at a certain point and I need to check every 30 seconds if it's time to upload. Then when I am uploading data I don't want to check again until the process is complete. Once complete I need to start checking every 30 seconds again.

I was under the impression I could use the System.Threading.Timer with a callback method and pass in a Timeout.Infinite parameter and that would stop the timer when it fired, then restart the timer after the upload method, like this:

However, that keeps calling the CheckDataUpload method.

What do you guys typically use in this situation?

This sounds like a case for a separate data-uploading service. You put a message in a queue saying "i need to upload some data". The uploader takes care of business, and when it's done puts a message in a different queue saying "task is done" that your source application will read from.

New Yorp New Yorp fucked around with this message at 17:50 on Aug 9, 2014

Essential
Aug 14, 2003

Ithaqua posted:

This sounds like a case for a separate data-uploading service. You put a message in a queue saying "i need to upload some data". The uploader takes care of business, and when it's done puts a message in a different queue saying "task is done" that your source application will read from.

This may be a perfect solution, I'm looking into it now. Thanks for the suggestion!

ljw1004
Jan 18, 2005

rum

Essential posted:

I have a data upload process I need to run at a certain point and I need to check every 30 seconds if it's time to upload. Then when I am uploading data I don't want to check again until the process is complete. Once complete I need to start checking every 30 seconds again.
What do you guys typically use in this situation?

I hate callbacks. What you're describing is a "process" or "workflow". I do all of these with async, because that I way I can code my workflow algorithm using familiar constructs like "while":

code:
// launch the async worker at application startup:
StartUploadWorkerAsync();


async void StartUploadWorkerAsync()
{
   while (true)
   {
      await Task.Delay(30000);
      if (!timeToUpload) continue;
      await DoUploadAsync(...);
   }
}

Essential
Aug 14, 2003

ljw1004 posted:

I hate callbacks. What you're describing is a "process" or "workflow". I do all of these with async, because that I way I can code my workflow algorithm using familiar constructs like "while":

code:
// launch the async worker at application startup:
StartUploadWorkerAsync();


async void StartUploadWorkerAsync()
{
   while (true)
   {
      await Task.Delay(30000);
      if (!timeToUpload) continue;
      await DoUploadAsync(...);
   }
}

Thank you for the suggestion Lucian! Is there a similar async thing I can do with the 4.0 framework? We have to support Win XP machines so I cannot get above 4.0 framework :(

Malcolm XML
Aug 8, 2009

I always knew it would end like this.

Essential posted:

Thank you for the suggestion Lucian! Is there a similar async thing I can do with the 4.0 framework? We have to support Win XP machines so I cannot get above 4.0 framework :(

Microsoft.bcl.async

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

Essential posted:

Thank you for the suggestion Lucian! Is there a similar async thing I can do with the 4.0 framework? We have to support Win XP machines so I cannot get above 4.0 framework :(

Async BCL on NuGet should work assuming you're developing on VS2012 or later.

Adbot
ADBOT LOVES YOU

Essential
Aug 14, 2003

Malcolm XML posted:

Microsoft.bcl.async

Ithaqua posted:

Async BCL on NuGet should work assuming you're developing on VS2012 or later.

Yep, I'm on vs2013. Thanks you guys!

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply