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
Crazy Mike
Sep 16, 2005

Now with 25% more kimchee.
Here's my headache for today. I have a DataGridView where I want certain columns centered, but changing the Alignment property seems to have no effect. After the DataGridView is populated I can alter the alignment of the column headers, but not the subsequent rows.
code:
DataGridViewCellStyle centered = new DataGridViewCellStyle();
centered.Alignment = DataGridViewContentAlignment.MiddleCenter;
centered.ForeColor = Color.Red;
            
DataGridViewCellStyle columnHeaders = new DataGridViewCellStyle();
columnHeaders.WrapMode = DataGridViewTriState.True;
columnHeaders.BackColor = Color.LightGray;
columnHeaders.Alignment = DataGridViewContentAlignment.MiddleCenter;

dgr.ColumnHeadersDefaultCellStyle = columnHeaders; //Column Headers are centered 
//Format Columns

DataGridViewColumn columnToCenter = dgr.Columns[0];
columnToCenter.Width = 50;
columnToCenter.DefaultCellStyle = centered; //Subsequent rows in this column are red but not centered 
Stack overflow suggested that the style may be overridden but I don't see where that could be happening in this program besides in the form design. Is there anything else that I may not be thinking of?

edit: I needed a fresh mind to figure this out...
code:
for (int i = 0; i < dgr.RowCount; i++)
            {
                
                dgr.Rows[i].Cells[0].Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
                dgr.Rows[i].Cells[1].Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
                dgr.Rows[i].Cells[2].Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
                dgr.Rows[i].Cells[12].Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
            }

Crazy Mike fucked around with this message at 17:47 on Jul 1, 2013

Adbot
ADBOT LOVES YOU

diadem
Sep 20, 2003
eet bugz
Aside from AppHarbor, where can I get some Jenkins style build machines and unit tests in the cloud without having to throw my IT staff at it?

I'm using .NET 4.5 and NUnit

ninjeff
Jan 19, 2004

Mr.Hotkeys posted:

What's the best way to indicate when writing a virtual method that overriding is fine but that you need to call the base version of the method as well? Or is there a better pattern for this? I know Dispose's pattern uses two methods but even there unless the extending class defines a third to mimick the second for anything that might extend from there, you'll still run into the problem somewhere down the line if your inheritance goes that far.
How about inverting that dependency? Something like this:
C# code:
abstract class BaseClass
{
	public void Foo(string arg)
	{
		this.OnFoo(arg);
		// put the base class's foo implementation here
	}

	protected abstract void OnFoo(string arg);
}

sealed class Subclass : BaseClass
{
	protected override void OnFoo(string arg)
	{
		// put the subclass's foo implementation here
	}
}
Subclasses have to implement OnFoo, giving their implementors a clear idea of where to put their fooing logic. They don't have to know if (and when [and how many times]) they need to call base.Foo, because the base class is in charge of orchestrating the fooing. If you need the base class's foo to happen first, or you need a BeforeFoo and an AfterFoo, then you can do that too, and implementors never have to wrap their heads around the internals of the base class.

Mr.Hotkeys
Dec 27, 2008

you're just thinking too much
That would work, but only for sealed classes; it just means I'd have to keep repeating that pattern in each extending class just in case anything wants to extend it and do the same thing.

code:
abstract class BaseClass
{
    public void Foo(string arg)
    {
        this.OnFoo(arg);
        // put the base class's foo implementation here
    }

    protected abstract void OnFoo(string arg);
}

class Subclass : BaseClass
{
    protected sealed override void OnFoo(string arg)
    {
	OnOnFoo(arg);
        // put the subclass's foo implementation here
    }

    protected abstract void OnOnFoo(string arg);
}

sealed class SubSubclass : Subclass
{
    protected override void OnOnFoo(string arg)
    {
        // put the subclass's foo implementation here
    }
}
And so on, how ever often unsealed classes extend it. I ended up settling half and half, the base class does what you suggested and from there on out hopefully extending classes will read the comments and call the base methods, but still wondering if there's a better way to do it/document it.

Gul Banana
Nov 28, 2003

this problem you've encountered is pretty normal - the fact is that if you want a class to be safely extensible by inheritance, you're going to have to design it that way. that means explicitly making-inheritable your intermediate subclasses, and so on. or giving up some safety.

if you want things to be more composable, why not create an IFooer interface instead- your current base class could be a BasicFooer, then what are currently intermediate subclasses could *contain* a BaseFooer, having a Foo() implementation of their own which uses myIFooer.Foo(). no stage of this would have to care how deep in the hierarchy it was.

Gul Banana fucked around with this message at 06:01 on Jun 29, 2013

Mr.Hotkeys
Dec 27, 2008

you're just thinking too much

Gul Banana posted:

the fact is that if you want a class to be safely extensible by inheritance, you're going to have to design it that way.

Well I mean yeah that's the goal

Gul Banana posted:

if you want things to be more composable, why not create an IFooer interface instead- your current base class could be a BasicFooer, then what are currently intermediate subclasses could *contain* a BaseFooer, having a Foo() implementation of their own which uses myIFooer.Foo(). no stage of this would have to care how deep in the hierarchy it was.

So basically sub encapsulation for inheritance? That would work, it'd be gross conceptually (for what I'm doing specifically and what the classes represent) and code (a lot of repeated methods or methods that just call other methods) but it would definitely work, and I might fall back on it depending on whether or not this looks like it's going to be a problem.

Jabor
Jul 16, 2010

#1 Loser at SpaceChem
Honestly I think trying to enforce this is rather unnecessary, if you write "When overriding this make sure to chain to the base class implementation" in your docs and then someone doesn't do that, it's not like they have anyone to blame but themselves.

Alternatively if you're writing a components library or something you could do something like:

code:
public class BaseClass {
  public sealed void Foo() {
    this.FooInternal();
    this.OnFoo();
  }

  internal void FooInternal() {}

  protected void OnFoo() {}
}
Then inside your library, you override FooInternal (chain to the base implementation each time, or not, whatever, you're writing all the code so all you need to do here is not gently caress it up), while anyone consuming your library uses OnFoo (and it's their own drat fault if they override one of their own OnFoo implementations with a different one and don't chain to the superclass version, it's not like there's anything you can do about that).

ljw1004
Jan 18, 2005

rum

Mr.Hotkeys posted:

What's the best way to indicate when writing a virtual method that overriding is fine but that you need to call the base version of the method as well?

I think that in the early days of object oriented programming, it was axiomatic that "call the base method" was the first thing you do when overriding. But it was never enforced, and thus fragile, and I reckon this fragility was one of the (many) nails in the "full-on OOD coffin".

I still shudder when I see a library that forces you to call the base method LAST.


Anyway, I'm not aware of how to force this, and I don't think there exists a standard annotation, and I think you should refactor your library to avoid this fragility.

Sedro
Dec 31, 2008
Overrides make more sense when your APIs are pure/less focused on side effects.
C# code:
override void Initialize() {
    // do I put my code here?
    base.Initialize();
    // or here?
}

override T Calculate() {
    if (cachedResult == null) {
        // it's obvious if and when I need to call the base method
        cachedResult = base.Calculate();
    }
    return cachedResult;
}

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug
When it looks like calling a base implementation of a method is always a prerequisite, I prefer to refactor so that I have something like

code:
public class Foo
{
	public void DoImplementationIndependentStuff() 
	{
		// important stuff
		DoFooSpecificThings();
	}
	
	protected virtual void DoFooSpecificThings()
	{
		// foo specific things!
	}
}

public class DerivedFoo : Foo
{
	protected override void DoFooSpecificThings()
	{
		// derived foo specific things
	}
}

Orzo
Sep 3, 2004

IT! IT is confusing! Say your goddamn pronouns!

zokie posted:

namespace provider property

Ithaqua posted:

:monocle:
I never noticed that before. That's the problem epalm is having, then.
I just wanted to point out that this also blew my mind.

Uziel
Jun 28, 2004

Ask me about losing 200lbs, and becoming the Viking God of W&W.
I'm not sure if this would do better in the jQuery thread but I'm running into a problem with Microsoft's MVC4 and Unobtrusive validation, and jquery blockUI.

I have a form with two jquery datepickers that validate remotely through an attribute on the model. This works fine as is, but I want to add a modal loading window while the processing for the submission is happening on the back end but obviously only when the form is valid.

The issue I'm running into is that on initial submit of the form, the form is valid until the remote validation finishes, so something like this makes the modal loading window never go away, as the initial submit's valid is always true:

code:
$("#seasonalSubmissionForm").submit(function () {
        $("#seasonalSubmissionForm").validate();
        if ($("#seasonalSubmissionForm").valid()) {
            $.blockUI();
        } else {
            $.unblockUI();
        }
    });

Sab669
Sep 24, 2009

I'm using a timer object to perform some code 2 seconds after the windows form loads, but then after that it only needs to be done once every 2 minutes or so. Right now, in the Elapsed event I'm just re-setting its Interval property, which seems pretty lovely. Is there a more proper way to do this?

Dietrich
Sep 11, 2001

Sab669 posted:

I'm using a timer object to perform some code 2 seconds after the windows form loads, but then after that it only needs to be done once every 2 minutes or so. Right now, in the Elapsed event I'm just re-setting its Interval property, which seems pretty lovely. Is there a more proper way to do this?

You can use tasks to do this sort of thing. Timers are pretty lovely in general.

epswing
Nov 4, 2003

Soiled Meat
Is anyone here using InstallShield 2012 LE with Visual Studio 2012? I just updated from InstallShield 2011 LE and Visual Studio 2010 (where everything was working fine, of course), and now the IS installer projects are not building. The errors are sitting in a StackOverflow question I posted earlier today.

Basically it says things like "Could not find file" and "Verify that the file exists in the specified location". The files IS is complaining about DO exist in the specified location, so I'm at a loss here.

How exactly am I supposed to generate my precious Setup.exe file? By selecting the SingleImage configuration and running Build Solution (this is how I always did it in VS 2010)? Or some other way? I get the feeling that it's building my projects out of order, and at the time IS tries to run, the assemblies it wants don't exist yet.

epswing fucked around with this message at 18:16 on Jul 2, 2013

crashdome
Jun 28, 2011

Dietrich posted:

You can use tasks to do this sort of thing. Timers are pretty lovely in general.

Is there a task-based way to have a callback guaranteed to run on the UI thread? Because I'm using a timer right now only because the callback method runs on the UI and it's consistent timing. It is an IO intensive method. Basically, I read some (roughly 48) digital outputs off a card and turn some indicator lights on/off in the UI based on their value. At peek idleness with the rest of my code it runs every 200ms and in some cases every 60ms when only monitoring a single value during a procedure. It's ok if it's blocked for a second or two during certain times because it is mostly visual cues and not time-critical operations but, it needs to be able to accelerate back to normal operating speed pretty quickly after something cpu-intensive. If a task can guarantee me that in some way, I'll gladly switch.

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

crashdome posted:

Is there a task-based way to have a callback guaranteed to run on the UI thread? Because I'm using a timer right now only because the callback method runs on the UI and it's consistent timing. It is an IO intensive method. Basically, I read some (roughly 48) digital outputs off a card and turn some indicator lights on/off in the UI based on their value. At peek idleness with the rest of my code it runs every 200ms and in some cases every 60ms when only monitoring a single value during a procedure. It's ok if it's blocked for a second or two during certain times because it is mostly visual cues and not time-critical operations but, it needs to be able to accelerate back to normal operating speed pretty quickly after something cpu-intensive. If a task can guarantee me that in some way, I'll gladly switch.

async methods. If you call the method from the UI thread, it will run on the UI thread. I've used a DispatcherTimer in conjunction with async methods in WPF before for periodically polling a web service and it worked great.

crashdome
Jun 28, 2011
Uh...

It is a DispatcherTimer. The read operation is in the tick event. I guess I am not seeing why or where the async comes in?

edit: Let me elaborate a bit so you can tell me if there is a different way.

The read operation is a single method call on a device object.

timer_Tick -> object.PerformRead(); this.UpdateThoseFourPeskyControls();

This method loops through 24 properties in blocks of 8 (the card can read a single value or values in blocks of a byte for Boolean outputs). Each read is roughly 5-6ms on a good day. So I loop 3 times and read 3 bytes worth of data in less than 60ms. I then also read 3 analog (basically a byte) values. Then, I update bound properties on the object doing the usual "if (prop == value) return;" so I don't fire off my OnNotifyProperty unless absolutely needed.

After calling this method, way back in the tick method, I have to update some UI controls manually which are not data-bound to the object directly. Not many. Maybe 4.

If I didn't use a DispatcherTimer, and I tried a few other options, I would always get the 'accessing UI on separate thread' warnings.

crashdome fucked around with this message at 19:14 on Jul 2, 2013

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

crashdome posted:

Uh...

It is a DispatcherTimer. The read operation is in the tick event. I guess I am not seeing why or where the async comes in?

So you don't block the UI thread during your IO intensive operation.

crashdome
Jun 28, 2011
You replied just as I edited in some details.

I see your point. Should I just make the object.PerformRead() do the asyncing so my UI(WinForm) doesn't have to?

edit: wait, but I can't update my UI until that method is done. I have to do the async/await in the tick event no matter what. Correct?


VVVV OK, that's what I thought. I'll probably even throw in something to prevent the 'ticks' from stacking in the event something horrible goes wrong and it takes 5 years to do a read operation.

crashdome fucked around with this message at 19:38 on Jul 2, 2013

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

crashdome posted:

You replied just as I edited in some details.

I see your point. Should I just make the object.PerformRead() do the asyncing so my UI(WinForm) doesn't have to?

edit: wait, but I can't update my UI until that method is done. I have to do the async/await in the tick event no matter what. Correct?

Yes. Your event handler will be async, and then you make your PerformRead method async and await it.

I'd expect it to look something like this:

code:
public async void Timer_Tick(object sender, RoutedEventArgs e) 
{
	var results = await object.PerformReadAsync();
	UpdateUI(results);
}

raminasi
Jan 25, 2005

a last drink with no ice
Can anyone think of a reason that this function inside a mixed DLL:
C++ code:
void some_class::func() {
    try {
        throw std::exception("butts");
    }
    catch (std::exception & e) {
        log(e.what());
    }
}
isn't catching its own exception? It's being called from a native DLL and is compiled without /clr. I've tried all the exception modes, and in every case the exception appears at the DLL boundary rather than inside the catch block. Googling for this is really hard because most people are curious about throwing exceptions across a native/managed boundary, which is specifically what I'm failing to avoid here.

e: The problem doesn't happen if the function is free, rather than a member function.

edit2: Okay, my repro case isn't staying consistent so I have no idea what the gently caress is going on.

raminasi fucked around with this message at 21:03 on Jul 2, 2013

Che Delilas
Nov 23, 2009
FREE TIBET WEED

GrumpyDoctor posted:

Can anyone think of a reason that this function inside a mixed DLL:
C++ code:
void some_class::func() {
    try {
        throw std::exception("butts");
    }
    catch (std::exception & e) {
        log(e.what());
    }
}
isn't catching its own exception? It's being called from a native DLL and is compiled without /clr. I've tried all the exception modes, and in every case the exception appears at the DLL boundary rather than inside the catch block. Googling for this is really hard because most people are curious about throwing exceptions across a native/managed boundary, which is specifically what I'm failing to avoid here.

e: The problem doesn't happen if the function is free, rather than a member function.

edit2: Okay, my repro case isn't staying consistent so I have no idea what the gently caress is going on.

I've seen exceptions swallowed like that before, though admittedly in a straight C# application, not mixed. Are you calling this function from a form's "Load" event handler function?

http://stackoverflow.com/questions/1583351/silent-failures-in-c-seemingly-unhandled-exceptions-that-does-not-crash-the-pr

raminasi
Jan 25, 2005

a last drink with no ice
No, it's not called from there. I've already identified no fewer than three unrelated subproblems contributing to this weird behavior, and I still haven't solved the underlying bit. So far:
  • I've learned that VS2010 isn't great about knowing which parts of a C++/CLI project it needs to recompile, so sometimes you'll have to force a rebuild of the whole project in order to see a change you've made,
  • The mixed-mode debugger likes to jump around your source code, so sometimes I'd think an exception was getting ignored only to have the debugger jump right back into the appropriate catch block on the next "Step over," and
  • A completely unrelated component had set a custom SEH handler which was hijacking the original throw (which was inside some third-party library code) and making me think I was losing my call stack.
Hopefully at some point I'll figure out how to fix my actual problem.

Fuck them
Jan 21, 2011

and their bullshit
:yotj:
So the project I'm in now WAS using Entity, now it's not, and I'm basically navigating my first ever big project with abstraction layers and hundreds of files, etc.

It was 555 the first time I checked VS's count. Hah.

Since I don't have the VS edition where I can just go "make me a call graph" :colbert: I'm doing it myself, and I can't find very cleanly where the bubbling up from the controller for "make a drat record and put it in the goddamn db dammit" actually reaches the methods that actually touch the database oh so intimately.

If it matters, the project is VB.net (The state that gave us the contract said so, not us!). Are there any free tools out there or do I just get to play "memorize key combos for definitions and references" and click methods all day and let it just coalesce?

I know how each part works, but I can't find where the hell the business object is passed to the function that takes the properties of it and sticks them into command.Paramaters to send to the stored proc. It's like there's the business object generation track, and then just sitting elsewhere there's something waiting for it, but I can't find where it's actually passed :psypop:

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

NDepend. There's a 14 day trial.

However, in my experience, a "big ball of mud" application that wasn't properly designed (which may very well be what you're working on) will generate a hideous dependency graph, and you'll be just as confused after as you were before.

New Yorp New Yorp fucked around with this message at 17:03 on Jul 3, 2013

Dietrich
Sep 11, 2001


You sure there isn't some sort of dependency injection going on?

No Safe Word
Feb 26, 2005

Yeah frankly if F12 (Go to definition) and Shift+F12 (Find all references) don't cut it, the easiest way to actually dig through the execution path is to attach the debugger and step through it all, which will cover you in the cases of dependency injection and any other sort of indirection.

Fuck them
Jan 21, 2011

and their bullshit
:yotj:

Dietrich posted:

You sure there isn't some sort of dependency injection going on?

I'm pretty sure there is a good object model behind there, since my team lead was big on making sure I knew that before making big changes, and would be mentoring if he didn't get sick-as-a-dog.

I also say this because there's some pretty clear this->that->the_next_thing going on, it's just that I see two chains which don't 'talk'.

No Safe Word posted:

Yeah frankly if F12 (Go to definition) and Shift+F12 (Find all references) don't cut it, the easiest way to actually dig through the execution path is to attach the debugger and step through it all, which will cover you in the cases of dependency injection and any other sort of indirection.

Gonna do that! Thanks!

Ithaqua posted:

NDepend. There's a 14 day trial.

However, in my experience, a "big ball of mud" application that wasn't properly designed (which may very well be what you're working on) will generate a hideous dependency graph, and you'll be just as confused after as you were before.

Gonna do that after I try it the step-thru way, thanks for the find!

Dirk Pitt
Sep 14, 2007

haha yes, this feels good

Toilet Rascal

Ithaqua posted:

NDepend. There's a 14 day trial.

However, in my experience, a "big ball of mud" application that wasn't properly designed (which may very well be what you're working on) will generate a hideous dependency graph, and you'll be just as confused after as you were before.

I have some terrible dependency graphs in an application I wrote last year before I wizened up to DI and the factory pattern.

I'd like to think every developer has those projects that have a pretty UI and a disastrous backend. Especially with a bastardized mvvm implementation.

Fortunately for you 2banks, . Net makes it easy to navigate a cluster gently caress.

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

2banks1swap.avi posted:

I'm pretty sure there is a good object model behind there, since my team lead was big on making sure I knew that before making big changes, and would be mentoring if he didn't get sick-as-a-dog.

Do you know what dependency injection is? It's a way of implementing inversion of control, which is vital for creating loosely-coupled, testable architectures.

When you write code like this:
code:
public class Frobbler
{
	public void Frobble() 
	{
		var db = new FrobbleDb();
		var frobbleItems = db.GetThingsToFrobble();
	}
}
In that case, you have what's known as a hard dependency. Your Frobbler class creates a FrobbleDb, and you have no way of controlling that. What if you wanted to test the logic in Frobble with a specific dataset that doesn't come from a database? You can't, and life is harder.

One method (and there are others) to avoid this is to use dependency injection. In DI, your Frobbler doesn't instantiate FrobbleDb. Instead, it's provided an implementation of the IFrobbleDb interface, which can be a real database object, or a mock object that returns only a specific set of data for testing. It would look like this:

code:
public class Frobbler
{
	private readonly IFrobbleDb db;
	public Frobbler(IFrobbleDb db) 
	{
		this.db = db;
	}
	public void Frobble() 
	{
		var frobbleItems = db.GetThingsToFrobble();
	}
}
If you have code that uses DI in your codebase and you're not familiar with the pattern, it can be confusing and look like dependencies are never being instantiated.

Fuck them
Jan 21, 2011

and their bullshit
:yotj:

Dirk Pitt posted:

I have some terrible dependency graphs in an application I wrote last year before I wizened up to DI and the factory pattern.

I'd like to think every developer has those projects that have a pretty UI and a disastrous backend. Especially with a bastardized mvvm implementation.

Fortunately for you 2banks, . Net makes it easy to navigate a cluster gently caress.

It has a feel for my newbie self to be more than decent.

The only thing that makes me go "WTF?" is two files named (A_Thing_I_dunno_if_I_can_talk_about)Repository.vb, though one is a business object, and the other is a service, and in totally different parts of a BIG project.

wwb
Aug 17, 2004

That is probably a good sign on some levels -- they have at least made an attempt to separate concerns.

Fuck them
Jan 21, 2011

and their bullshit
:yotj:
Even with NDepend I can't manage to get a graph from the controller going "HEY, MAKE THIS AND PUT IT IN THE DB :downs:" and a chain of calls to where a method goes "OKAY! LOADING PARAMETERS AND CALLING THAT STORED PROC! :downsrim:"

Now, on the other hand, I CAN do this with step-in debugging. Maybe I'll just do it by hand?

Ugh.

JawnV6
Jul 4, 2004

So hot ...
Just wait until you hit some multithreaded code that behaves differently when you're gumming up one thread with step-through debugging :)

Fuck them
Jan 21, 2011

and their bullshit
:yotj:
It's kind of shocking that only by running the drat program that I can see the bubbling up of calls until it actually puts the drat data into the db for "create a goddamn note."

Truly it is the future. I'm just going to take notes and then MSPaint this so I can get out by four without having an aneurysm.

Fuck them
Jan 21, 2011

and their bullshit
:yotj:

JawnV6 posted:

Just wait until you hit some multithreaded code that behaves differently when you're gumming up one thread with step-through debugging :)

Would multi-thread-debugging allow you to manually trigger the likes of spinlocks or mutexes or whatever?

Or would you have separate "step throughs" for each thread? :psypop:

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug
Are they using an IOC container like Ninject, Unity, Castle Windsor, StructureMap, or Autofac?

Fuck them
Jan 21, 2011

and their bullshit
:yotj:
I ran the step-thru (more like step in :getin:) debugger and employed my copy and paste skills to show what is involved for the controller to put stuff in the DB.

Tell me if this is just the results of using an ORM or some generator, or a good attempt at separating concerns, or bad separation, or a horror, please.

Please note I replaced certain things with $PROJECT and $TASK, since while I'm not under an NDA, given that this is being done for a state government, I don't want it to be too easy for some goon to figure out what I'm working on.

code:
Namespace $PROJECTII
    Public Class $TASKsController
        Inherits $PROJECTBaseController

 <HttpPost()>
        Function Create(ByVal viewModel As $TASKsCreateViewModel) As ActionResult

            Try
                _$TASKsRepository.Create$TASK(viewModel) // calls...
                If ValidationContext.IsValid Then
                    viewModel.IsValid = True
                Else
                    viewModel.IsValid = False
                End If

                Return Json(viewModel)
            Catch ex As Exception
                Throw New Exception(ex.Message, ex.InnerException)
            End Try
        End Function
    End Class
End Namespace

Namespace BusinessRepositories
    Public Class $TASKsRepository
        Inherits BaseRepository
        Implements I$TASKsRepository


	//below is called
        Public Sub Create$TASK(viewModel As $PROJECT_ViewModels.Adult$TASKs.$TASKsCreateViewModel) Implements I$TASKsRepository.Create$TASK
            ValidateRequired(Function() viewModel.Notes)
            ValidateRequired(Function() viewModel.DateCreated)
            ValidateRequired(Function() viewModel.ContactDate)
            ValidateRequired(Function() viewModel.NextReportDate) //validating stuff 

            If ValidationContext.IsValid Then
                _$TASKsDataService.Create$TASK(viewModel) //calls...
            End If
        End Sub

    End Class
End Namespace

Namespace DataServices
    Public Class $TASKsDataService
        Private ReadOnly _service$TASKs As New $TASKsServiceClient

	//below is called 
        Public Function Create$TASK(viewModel As $TASKsCreateViewModel) As $TASKsCreateViewModel
            Try
                Dim $TASKs = MapViewModelToBusinessObject(viewModel) //hooray another method in the same class!

                viewModel.CasePIN = _service$TASKs.Create$TASK($TASKs) //oh now we're going elsewhere
                viewModel.IsValid = True
            Catch ex As Exception
                viewModel.IsValid = False
            End Try

            Return viewModel
        End Function //back from writing to the DB, now we're done. 

	//Now we're in the only time a second method in the same class is called yo!
        Private Function MapViewModelToBusinessObject(viewModel As $TASKsCreateViewModel) As Adult.$TASKs
            Dim adult$TASKs As New Adult.$TASKs

            adult$TASKs.ClientPIN = viewModel.ClientPIN
            adult$TASKs.CasePIN = viewModel.CasePIN
            adult$TASKs.$TASK = viewModel.Notes
            adult$TASKs.DateCreated = DateTime.Now.ToString
            adult$TASKs.CreateUser = viewModel.CreatedBy
            adult$TASKs.ContactDate = viewModel.ContactDate
            adult$TASKs.NextReportDate = viewModel.NextReportDate
            adult$TASKs.$TASKAuthorPIN = viewModel.CreatedBy
            adult$TASKs.$TASKAuthorFocusGroup = "Bail"
            adult$TASKs.ActivityType = "ACTTP"   'viewModel.ActivityType
            adult$TASKs.Contact1 = 0    'viewModel.Contact1
            adult$TASKs.Category2CD = 0    'viewModel.Category2CD
            adult$TASKs.Category3CD = 0    'viewModel.Category3CD
            adult$TASKs.ActivityActionCd = 0 'viewModel.ActivityActionCd
            adult$TASKs.CategoryOtherCd = 0 'viewModel.CategoryOtherCd

            adult$TASKs.ModifyUser = viewModel.CreatedBy
            adult$TASKs.ModifyTSP = DateTime.Now.ToString
            adult$TASKs.ActiveFlg = 0    'viewModel.ActiveFlg
            adult$TASKs.ArchivedFlg = 0  'viewModel.ArchivedFlg
            adult$TASKs.DeletedFlg = 0   'viewModel.DeletedFlg
            adult$TASKs.ExpungedFlg = 0   'viewModel.ExpungedFlg
            adult$TASKs.HiddenFlg = 0   'viewModel.HiddenFlg
            adult$TASKs.InactiveFlg = 0   'viewModel.InactiveFlg


            Return adult$TASKs
        End Function // back up to the Create$TASK() method

    End Class
End Namespace

Public Class $TASKsService
    Implements I$TASKsService
    
    //here we go again 
    Function Create$TASK($TASKs As Jud.Itd.$PROJECT.BusinessObjects.Adult.$TASKs) As Integer Implements I$TASKsService.Create$TASK
        Try
            Return _$TASKsRepository.Create$TASKs($TASKs) //One more jump!
        Catch ex As Exception
            Throw New Exception(ex.Message, ex.InnerException)
        End Try
    End Function
End Class

Namespace Repositories
    Public Class $TASKsRepository
        
	//And now we finally write to the database!!!! :toot:
	Function Create$TASKs(ByVal model As $TASKs) As Integer
            Dim pin As Integer
            Dim connectionString As String = ConfigurationManager.ConnectionStrings("$PROJECTDB").ToString()

            Using connection As New SqlConnection(connectionString)
                Using command As New SqlCommand()

                    command.Connection = connection
                    command.CommandType = CommandType.StoredProcedure
                    command.CommandText = "spr_ADLT_CMN_$TASKsCreate"

                    command.Parameters.Add(New SqlParameter("ClientPIN", model.ClientPIN))
                    command.Parameters.Add(New SqlParameter("ClientNote ", model.$TASK))
                    command.Parameters.Add(New SqlParameter("CasePIN ", model.CasePIN))
                    command.Parameters.Add(New SqlParameter("CreateUser ", model.CreateUser))
                    command.Parameters.Add(New SqlParameter("CreateTSP ", model.DateCreated))
                    command.Parameters.Add(New SqlParameter("ContactDate ", model.ContactDate))
                    command.Parameters.Add(New SqlParameter("NextReportDate ", model.NextReportDate))
                    command.Parameters.Add(New SqlParameter("Category1NoteCodePIN ", model.Contact1))
                    'command.Parameters.Add(New SqlParameter("ActivityCD ", model.ActivityType))
                    command.Parameters.Add(New SqlParameter("ClientNoteAuthorPIN ", model.$TASKAuthorPIN))
                    command.Parameters.Add(New SqlParameter("ClientNoteAuthorFocusGroup ", model.$TASKAuthorFocusGroup))
                    command.Parameters.Add(New SqlParameter("ModifyUser ", model.ModifyUser))
                    command.Parameters.Add(New SqlParameter("ModifyTSP ", model.ModifyTSP))
                    command.Parameters.Add(New SqlParameter("ActivityNoteCodePIN ", model.ActivityActionCd))
                    command.Parameters.Add(New SqlParameter("Category2NoteCodePIN ", model.Category2CD))
                    command.Parameters.Add(New SqlParameter("Category3NoteCodePIN", model.Category3CD))
                    command.Parameters.Add(New SqlParameter("CategoryNoteOther ", model.CategoryOtherCd))
                    command.Parameters.Add(New SqlParameter("ActiveFlg ", model.ActiveFlg))
                    command.Parameters.Add(New SqlParameter("ArchivedFlg ", model.ArchivedFlg))
                    command.Parameters.Add(New SqlParameter("DeletedFlg ", model.DeletedFlg))
                    command.Parameters.Add(New SqlParameter("ExpungedFlg ", model.ExpungedFlg))
                    command.Parameters.Add(New SqlParameter("HiddenFlg ", model.HiddenFlg))
                    command.Parameters.Add(New SqlParameter("InactiveFlg ", model.InactiveFlg))


                    connection.Open()

                    pin = command.ExecuteScalar()
                End Using

                connection.Close()
            End Using

            Return pin
        End Function //now we go back to $TASKsService.Create$TASK()!

    End Class
End Namespace

IS THIS NORMAL? :stonk:

I literally had to go for a walk around the entire office building to get calmed down after doing this whole thing. Is this normal or is something really wrong?


Ithaqua posted:

Are they using an IOC container like Ninject, Unity, Castle Windsor, StructureMap, or Autofac?

None of the devs know; the lead is sick as hell and at home. I'll ask him next week.

Fuck them fucked around with this message at 21:43 on Jul 3, 2013

Adbot
ADBOT LOVES YOU

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

That all looks like good, well-factored code. I think what you're missing is the implementation in the base classes.

[edit]
I take that back, there's definitely weird/bad stuff.

code:
       Try
            Return _$TASKsRepository.Create$TASKs($TASKs) //One more jump!
        Catch ex As Exception
            Throw New Exception(ex.Message, ex.InnerException)
        End Try
Please tell whoever wrote that code to not catch exceptions if you're not handling them.

[edit2]
Also, based on some of variable names I can still tell what the software is intended for, so you might want to redact it further.

New Yorp New Yorp fucked around with this message at 20:37 on Jul 3, 2013

  • Locked thread