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.
 
  • Locked thread
Night Shade
Jan 13, 2013

Old School

PhonyMcRingRing posted:

Personally, in this situation, I wrap my constructor body in a try-catch and have it dispose itself if necessary. Especially if there's a public constructor anyway, never know who's gonna call it!

I do the same thing, except that I also rethrow the exception. The constructor's job is to return a usable object, and if it can't do that (things to consider: various IOExceptions, OutOfMemoryException, ThreadAbortException, StackOverflowException) you're already in an exceptional state. The difference between throwing and self-disposing is that if the constructor doesn't throw, at some point whatever instantiated your object is going to try and use it despite it being in an invalid state so all you're really doing is delaying the inevitable.

Adbot
ADBOT LOVES YOU

Night Shade
Jan 13, 2013

Old School

ninjeff posted:

This solves the immediate problem, but also introduces a new one: your Dispose method now can't assume it's being called on a fully initialised and consistent object.

You could do all the disposal of dependencies in the constructor instead of calling Dispose, but then you make your constructor even harder to verify.

For most managed dependencies, you can just let the GC take care of it next Gen0 sweep. Realistically I'd only try to clean up unmanaged resources and any event subscriptions created in a constructor's catch block.

Night Shade
Jan 13, 2013

Old School
Maybe C# 5 In a Nutshell? It's written by the guy who made LinqPad, which is an awesome little .net snippet runtime. I've had a flick through the copy we have at work, and imo it does a pretty good job of covering C# and the .NET framework without getting bogged down in beginner level intro-to-programming tutorials.

Night Shade fucked around with this message at 08:47 on Apr 17, 2013

Night Shade
Jan 13, 2013

Old School
^^ :argh:

Paul MaudDib posted:

I know LINQ has lots of special-cased operations to take advantage of HashSets
It really doesn't. HashSet does if you use two HashSet to perform set operations, and that's only if they share a common EqualityComparer. ToLookup() and ToDictionary() will recompute the hash across the entire collection (O(N)) just so you can then perform an O(1) lookup.

Zhentar's right, dump the HashSet entirely and jam them in a dictionary with record_id as the key. You could also look at SortedDictionary<> since you mentioned you wanted to use a sorted array of record_id, which will give you O(log N) insert and retrieve but keep your records sorted.

Paul MaudDib posted:

But I don't want to pass around the whole record list repeatedly

Why not? It's like 8 bytes to pass a reference, and that's only if you're on x64.

Night Shade
Jan 13, 2013

Old School

Zhentar posted:

If you actually need to different objects with the same record ID to have the same hash (e.g. you've overridden Equals), then yeah, returning the recordId's hash would be good. If you haven't overridden Equals, don't touch the hash.

To expand on this: the default implementations of Equals, IEqualityComparer etc. basically go "are these two things the same instance?". If for whatever reason you need to change this behaviour you're better served by changing it in a custom IEqualityComparer instead of doing so in a .Equals() override, partly because everyone fucks up using .Equals() and uses == or != instead and partly because all of the built in collections that care about equality will let you provide an instance of IEqualityComparer to customise their comparison behaviour anyway.

If you do ever override Equals, your implementation of GetHashCode must return the same value for two instances where a.Equals(b) is true or you will break collections that use it. This is also true for any IEqualityComparers you create. Have a look at this blog post by Eric Lippert for further discussion on the topic of how to GetHashCode.

In your specific case, I really don't think you should be touching Equals unless there's a really good reason that any given Record object should consider itself to be the same as any other Record object with the same record ID (hint: this is probably not what you want).

As for decent hashing functions, bearing in mind that you will almost never avoid collisions completely due to things like internal bucket count choices, based on this and related questions on stack overflow something like this should do fine:
code:
unchecked {
    int hashCode = _field1.GetHashCode();
    hashCode = hashCode * 31 + _field2.GetHashCode();
    hashCode = hashCode * 31 + _field3.GetHashCode();
//  ...
    return hashCode;
}
Using 31 as the constant has a couple of desirable properties: as a prime it tends to generate better distributions when modulo arithmetic is applied to choose a bucket, and being so close to 32 it can be implemented on CPU as shift-and-subtract instead of multiply, which is usually faster.

Night Shade
Jan 13, 2013

Old School

ShaunO posted:

How do I generate a MS Authenticode .pfx certificate to sign a ClickOnce manifest using a local CA (Server 2008 DC)?

certmgr.msc - Request new certificate, then export.
http://stackoverflow.com/questions/1118612/how-can-i-get-a-domain-controller-to-give-me-a-clickonce-certificate

e: There is a certificate template in the wizard specifically for code signing.

e2: vvvv You're welcome, that looks like an enormous pain in the arse. At least now your CA server is set up for any other ones you need.

Why must Microsoft make it so fiddly to do anything slightly unusual...

Night Shade fucked around with this message at 04:41 on Apr 22, 2013

Night Shade
Jan 13, 2013

Old School
The GC does not call dispose. Certain classes with unmanaged resources (eg System.Drawing.Image) have a finalizer method that delegates to Dispose. The GC does call finalizers unless told not to by GC.SuppressFinalize().

If *you* don't call Dispose you run the risk of leaving things like SQL connections, files or handles open until the GC gets around to cleaning them up. Depending on what generation you've managed to get your object into, this may not be for some time.

Night Shade
Jan 13, 2013

Old School

Manslaughter posted:

Is there a way to make Visual Studio automatically make any new files in one of your project's folders get included in the project?

I believe you can do some fuckery with the project file to make it include *.* (or *.cs, *.vb) but I haven't done so myself.

Night Shade
Jan 13, 2013

Old School

Orzo posted:

I have to explicitly call Test.TestMethod<string>? If I don't, the compiler says it can't infer the generic usage. Why?

It works for Func<T> because the compiler can figure out what T is from your lambda's return value. With Action<T>, you're passing something into your lambda and doing some stuff to/with it. Yes, you're assigning it to a (closed over) string variable, but the compiler doesn't know if v should be of type String or MySubclassOfString or something else entirely.

Night Shade
Jan 13, 2013

Old School
Which version of .NET are you targeting? If it's 4.5 or even 4.0 you have access to a whole bunch of things that will make your life much simpler. See: ConcurrentQueue<>, all the nice *Async methods on sockets etc. Also dedicated threads per socket doesn't scale particularly well, you're much better off doing Begin*(callback) / End*(IAsyncResult) or in 4.5 *Async because the thread pool does nice things under the hood to not poo poo up the scheduler.

Also this statement is raising alarm bells:

quote:

sends any updates it has directly to the clients using its own set of sockets

Sockets are two-way, and any server-client communications should go over the same socket the client connected to the server with.

Off the top of my head: honestly if you've got access to .NET 4.0 or 4.5 I'd drop in TPL DataFlow (a Microsoft nuget package) and set up agent objects for your clients, gamestates (assuming your server handles more than one) and a server agent responsible for accepting connections, wrapping them in client agents, sending client agents a list of available gamestates and registering client agents to the appropriate gamestate agent in response to some registration message from the client. The agent objects don't have to be anything fancy, just a message queue (TPL DataFlow makes this easy), methods to handle messages and for the client agent methods to handle transforming messages from whatever your wire protocol is to message objects. Google's Protobuf is a decent way to get a binary wire format going without having to dick around with Microsoft's lovely ones or xml serialisation and there's a pretty decent .NET package for it again available through nuget.

Night Shade
Jan 13, 2013

Old School

Alien Arcana posted:

Okay, revised description. Two main threads. One's got a TcpListener in a loop, waiting for incoming connections. When it gets one, it assigns it a socket, puts the socket into some kind of thread-safe collection, and then calls BeginReceive on the socket (with an appropriately-chosen callback method to grab the incoming packets and stuff them in a BlockingCollection). The other thread is watching the BlockingCollection, grabs whatever comes out of it, does its game-state-adjustment magic, and then uses the same sockets to Send the updates out.

Is there anything in there that blatantly Won't Work? Because I think I can manage that implementation.

I can't think of anything off the top of my head, the only thing I would suggest is that you might be better off using traditional locking (=mutexes under the hood) around a regular List<Socket> instead of a thread-safe list of clients, primarily to avoid weird race conditions between clients connecting and the gamestate thread trying to push updates out. You're not really going to win much performance with a thread safe collection in that scenario because you're iterating over the whole set on gamestate updates anyway.

I still think that you're going to be better served creating a client agent class to handle each socket rather than having your gamestate thread access them directly. For one, it'll mean socket error handling doesn't wind up making GBS threads up your game logic.

Night Shade
Jan 13, 2013

Old School

PhonyMcRingRing posted:

Technically, WebAPI is a WCF service wrapped up in a little package.

Wait, what? Have you actually looked at the code? It's much more like MVC than anything else, I don't even think it references System.ServiceModel :colbert:

Fake edit: OK so self hosted mode runs on top of WCF's http stuff, but really WebAPI is designed to be hosted in IIS.

Real edit: And self hosted mode is in its own DLL, so technically WebAPI itself doesn't reference System.ServiceModel :smugbert:

Night Shade fucked around with this message at 01:51 on May 30, 2013

Night Shade
Jan 13, 2013

Old School

Zhentar posted:

I said "anything else" because MSTest does support that.

code:
[TestMethod]
[DataSource("System.Data.Odbc", @"Dsn=Excel Files;dbq=|DataDirectory|\TestCases.xlsx" , "Cases$", DataAccessMethod.Sequential)]
public void MyTest() { ... }
Bam, a list of 450 test cases gets run through my test (eight of them, actually), and my QA person can add more without editing code. It's awesome.

You might be able to do something with this and an ODBC connection/command. Something along the lines of:
code:
public static IEnumerable TestCases { get {

var connection = new OdbcConnection(@"Dsn=Excel Files;dbq=|DataDirectory|\TestCases.xlsx");
connection.Open();
var command = connection.CreateCommand();
command.CommandText = "Cases$";
var reader = command.ExecuteReader();
while( reader.Read() )
{
    object[] row = new object[reader.FieldCount];
    reader.GetValues(row);
    yield return row;
}
// replace these with using blocks because i'm lazy
reader.Dispose();
command.Dispose();
connection.Dispose();
} }
Note: Coded from MSDN online straight into SA's edit box, errors & omissions excepted

Night Shade
Jan 13, 2013

Old School

Ithaqua posted:

This just screams "abstract me!".
:words:

https://github.com/Mikkeren/FizzBuzzEnterpriseEdition

Yes, this is Java. No, I don't care. :colbert:

Night Shade
Jan 13, 2013

Old School

JawnV6 posted:

I fell in love with lock(this){} and never looked back.

Don't do this. Lock on a private new object() field, they're basically free. Otherwise you'll wind up competing with some joker that decides to lock on a reference to your object on another thread.

Night Shade
Jan 13, 2013

Old School

Dietrich posted:

I agree that locking on this is a bad call, but what about locking on a private static dictionary object when reading or writing to it from various threads?

Yeah that's fine. As a general rule, don't lock on anything you aren't certain anybody else will be able to lock on without doing stupid reflection tricks, so anything private is a prime candidate. e:
does a much better job of explaining the reasons.

For dictionaries you may also want to consider refactoring to use a ReaderWriterLockSlim so you can get parallel reads.

Night Shade fucked around with this message at 03:26 on Jun 13, 2013

Night Shade
Jan 13, 2013

Old School

Alien Arcana posted:

Specifically, if I call one of the Begin methods (e.g. TcpListener.BeginAcceptSocket), how do I tell it to stop listening so that I can shut down the server? There does not appear to be a designated method for this, and I can't call EndAcceptSocket without an IAsynchState to pass it. I tried just calling TcpListener.Stop, but that just seems to trigger my "accept socket" delegate getting called anyway, and promptly throwing an exception because the listener has been disposed!
This is correct behaviour.

quote:

Can anyone tell me what I'm doing wrong?
Not handling exceptions - that's how the IAsyncResult pattern works. Your callback is guaranteed to be called, and the End... call will throw whatever exception you need to deal with.
In the case of listener socket shutdown which is what .Stop() does, it throws an ObjectDisposedException as documented on MSDN: http://msdn.microsoft.com/en-us/library/system.net.sockets.tcplistener.endacceptsocket.aspx

All you need to do is:
code:
private void AcceptNewClient(IAsyncResult ar)
{
  Socket inputSocket;
  try
  {
    inputSocket = Listener.EndAcceptSocket(ar);
  }
  catch( ObjectDisposedException )
  {
    return;
  }

  // do stuff with the socket

  BeginListening();
}
You may also want to process SocketExceptions in a few cases.

Night Shade
Jan 13, 2013

Old School

GoodCleanFun posted:

Check out the practical use at the bottom of the following link:
http://digitaltapestry.wordpress.com/2009/03/20/reflecting-on-code/

Caliburn Micro uses this in its PropertyChangedBase, along with some thread marshalling stuff. The ability to refactor and not have to worry about breaking all of the property changed magic strings is totally worth the tiny overhead and the slightly obscure PropertyChanged(()=>Property) instead of PropertyChanged("Property").

Another related trick: never null-check an event again. Declare them as:
code:
public event EventHandler<EventArgs> SomethingHappened = delegate{};
The empty delegate invocation is basically free, and since nothing outside your class can remove it SomethingHappened will never be null so you can omit the check.

Night Shade
Jan 13, 2013

Old School

uXs posted:

Too much typing, use this instead: public event EventHandler<EventArgs> SomethingHappened = () => { };

Also it may be basically free, but it's not.

It isn't totally free, but I ran some timing loops in linqpad on an i7-2600:

quote:

null check unsubscribed - 100,000,000 iterations: 00:00:00.3041283 (3.041283 ns/iteration)
null check subscribed - 100,000,000 iterations: 00:00:00.4259502 (4.259502 ns/iteration)
null check double subscribed - 100,000,000 iterations: 00:00:01.4567414 (14.567414 ns/iteration)

default implementation - 100,000,000 iterations: 00:00:00.3956589 (3.956589 ns/iteration)
default implementation subscribed - 100,000,000 iterations: 00:00:01.4991489 (14.991489 ns/iteration)
where "default implementation" is doing that trick, and subscribed is where an external handler is registered.

To be honest if you're trying to nickel and dime over less than ten nanoseconds, .NET is probably not an appropriate environment for whatever you're doing.

Edit: and the added memory pressure is best measured in individual bytes.

Night Shade
Jan 13, 2013

Old School

comedyblissoption posted:

Is there a way in .net to write generic, re-usable linq queries with an ORM?

As a simple example, how could I create linq expressions/execute linq queries that will find all of the records in the database where a specified field is >= today. I don't want to have to copy paste this code for every query for a class that uses similar logic.

If all of the classes inherit from an interface and the property I am querying on has the same name in all of the classes, entity framework's linq provider is able to understand and generate the query. However, this sucks because it won't work with scenarios where the property name is not the same across all the classes for which I want to use a generic query.
Bolded part makes this harder.
This is 100% untested, but it should be along the right track. I'd test it myself but I'm about to go see Enders Game.

code:
public class Extensions {
	public static IQueryable<T> GetFutureRecords<T>(this IQueryable<T> queryable, Expression<Func<T,TField>> dateField, DateTime since = DateTime.Today)
	{
		MemberExpression property = dateField.Body as MemberExpression;
		if( property == null ) {
			throw new InvalidOperationException("Please specify a public property to test.");
		}
		Expression parameter = Expression.Parameter(typeof(T));
		Expression lambda = Expression.Lambda<Func<T,bool>>( Expression.GreaterThanOrEqual(property.Update(parameter), Expression.Constant(since)));
		return queryable.Provider.CreateQuery( 
			Expression.Call( typeof(Queryable).GetMethod("Where", new[] { typeof(IQueryable<T>), typeof(Expression<Func<T, bool>>) } ),
			queryable.Expression, lambda) );
	}
}
Use: ormQueryable.GetFutureRecords(record => record.DateTimeField)

Night Shade
Jan 13, 2013

Old School

Tha Chodesweller posted:

Is there a way to basically check if all tasks fired off from the task factory/original task chain are complete? That'd be ideal, but with my admittedly limited knowledge in how the factory works and my Googling, it doesn't seem like it exists.

Specifying TaskCreationOptions.AttachedToParent in the nested Task.Factory.CreateNew() call will link the task contexts together, causing the parent to wait for the child to complete before completing itself. It also has the neat effect of propagating exceptions up through the parent task.

code:
[Test]
public void TestDetachedTask() {
  int complete = 0;
  var outer = Task.Factory.StartNew( () => {
    var inner = Task.Factory.StartNew( () => {
      Thread.Sleep(1000);
      Interlocked.Exchange(ref complete, 1);
    });
  }
  outer.Wait(); // does not wait for inner to complete
  Assert.That(complete, Is.EqualTo(1)); //fails
}

[Test]
public void TestAttachedTask() {
  int complete = 0;
  var outer = Task.Factory.StartNew( () => {
    var inner = Task.Factory.StartNew( () => {
      Thread.Sleep(1000);
      Interlocked.Exchange(ref complete, 1);
    }, TaskCreationOptions.AttachedToParent);
  }
  outer.Wait(); // waits for inner to complete
  Assert.That(complete, Is.EqualTo(1)); //passes
}
disclaimer: typed directly into edit box, may not compile

Night Shade
Jan 13, 2013

Old School
Are any of you guys using Service Bus for Windows Server? Any ideas how to get a service running as SYSTEM to authenticate against it?

Night Shade
Jan 13, 2013

Old School

Mr Shiny Pants posted:

If it is over the network it won't work, system is for the local machine. Configure your app to talk with the servicebus using a domain account.

configure the service to run as a user instead of localsystem.

Yeah I was having trouble getting it to work locally. I was hoping to avoid needing AD service accounts, some of our customers are a bit ...special... when it comes to their AD.

wwb posted:

^^^ if you don't have a domain handy then you can also use 2 similarly named / passworded windows accounts.

This is probably what we'll wind up doing if I can't get machine accounts working. Thanks!

Night Shade
Jan 13, 2013

Old School

wwb posted:

One thing to note -- every machine has an AD service account. Use DOMAIN\MACHINENAME$ ; maps to network service locally.

It does, but service bus won't let you grant roles to a machine account because reasons. It will let you grant roles to accounts in NT AUTHORITY, which I was hoping would give me a way to get local machine auth working.

Night Shade
Jan 13, 2013

Old School

GrumpyDoctor posted:

Has anyone used QuickGraph? I want to run A* on an undirected graph, but I can't figure out how to do it because the library's implementation of A* requires an IVertexListGraph but the only undirected graph I can figure out how to make doesn't implement that interface.

I threw together an undirected implementation based on the directed version: http://pastebin.com/fs3v7fk8
Totally untested, I'd check its output against a bidirectional copy of the source graph before using it in earnest.

Adbot
ADBOT LOVES YOU

Night Shade
Jan 13, 2013

Old School

GrumpyDoctor posted:

Has anyone gotten Git Extensions to work with VS 2013? I want more features than the built-in git provider has, but my problem is that the Git Extensions installer puts its plugin onto a network drive (because that's where my user profile lives), which breaks Git Extensions. The workaround is to make a local copy of the plug-in, but I don't know how to get VS to see it. It can see the add-in fine, but there's no entry in the source control provider drop-down.

Git Extensions isn't a source control provider, it just extends the solution explorer with file status badges and adds a bunch of shortcuts.

  • Locked thread