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
kitten emergency
Jan 13, 2008

get meow this wack-ass crystal prison
it's called a 'code smell'

Adbot
ADBOT LOVES YOU

KoRMaK
Jul 31, 2012



uncurable mlady posted:

it's called a 'code smell'

nah code smell is used for things that are a lot more fuzzy to describe. thats most def a lambda, it has a firm definition

EssOEss
Oct 23, 2006
128-bit approved
I shall name it "the mysterious case of the missing whitespace characters"

Cuntpunch
Oct 3, 2003

A monkey in a long line of kings
The "premature minification" sounds good to me.

LOOK I AM A TURTLE
May 22, 2003

"I'm actually a tortoise."
Grimey Drawer
If it's wrong to make operators look like other things by strategically omitting whitespace for anything else than comedic effect then I don't want to be wrong, because gently caress that poo poo.

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



The Prostate Operator

Mr. Crow
May 22, 2008

Snap City mayor for life

The Wizard of Poz posted:

It's not "just an assignment".

= is the assignment operator.
() => is the beginning of a Lambda expression.

Oh okay​, I thought you could assign expressions to variables, looks like I was mistaken, thanks for the clarification.

:cheers:

Also

uncurable mlady posted:

it's called a 'code smell'

Mr. Crow fucked around with this message at 21:54 on Mar 14, 2017

dougdrums
Feb 25, 2005
CLIENT REQUESTED ELECTRONIC FUNDING RECEIPT (FUNDS NOW)
After doing some more reading, it seems to be used in a few Linq-to-GPU schemes for writing functional kernels.

http://www.aleagpu.com/release/3_0_2/doc/gpu_programming_csharp.html#lambdas for example.

I take 'code smell' to mean that thing I do in other languages where I'm not quite sure how something is supposed to work, but I shoehorn in whatever does the job.

Also I think they should be called delegate expressions instead of lambda expressions ... obviously actions are not lambda terms, and things like
code:
from i in Enumerable.Range(0, 10)
let a = new Func<object, object>(o => { Console.Out.WriteLine(o); return o; })
select a(i)
is all sorts of hosed lol

EssOEss
Oct 23, 2006
128-bit approved
Just so we are clear, the only thing that smells about the example you started the discussion with is the weird-rear end formatting. The concept itself is a perfectly fine usage of C# if you format it correctly so it does not look like some weirdass "arrow through a portal":

code:
{
	var x = 2;
	Func<int> a = () => 10 * x;
}
Pressing enter between statements is also greatly recommended. I assume this is a contrived example and not real code (given that the variables are not used inside the block), so presumably you just shortened it for the post.

dougdrums
Feb 25, 2005
CLIENT REQUESTED ELECTRONIC FUNDING RECEIPT (FUNDS NOW)
Yeah, it's a small bit of context, so to speak.

I take it that some of y'all work with people who might actually take this to be a good idea…

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy

Mr. Crow posted:

Oh okay​, I thought you could assign expressions to variables, looks like I was mistaken, thanks for the clarification.

:cheers:

Also

I think this probably isn't what you meant, but you can assign capital-E Expressions to variables, using the same syntax:

code:
Expression<Func<int, int>> expr = a => a + 1;

Warbird
May 23, 2012

America's Favorite Dumbass

Let's talk Json.NET for a second. I'm pulling JSON from WeatherUnderground and hoping to insert it into a class I've generated from json2csharp, but I'm not exactly sure how to do so. J2C# returns multiple classes and I'm not really sure how to approach this.

code:
public class Features
{
    public int conditions { get; set; }
}

public class Response
{
    public string version { get; set; }
    public string termsofService { get; set; }
    public Features features { get; set; }
}

public class Image
{
    public string url { get; set; }
    public string title { get; set; }
    public string link { get; set; }
}
and so forth.

Do I make classes for each of these and have the JSON deserialize into each? All the examples I've come across are dealing with a single class. Am I missing something and you can just slap it inside one class and it just works?

chippy
Aug 16, 2006

OK I DON'T GET IT

Warbird posted:

Let's talk Json.NET for a second. I'm pulling JSON from WeatherUnderground and hoping to insert it into a class I've generated from json2csharp, but I'm not exactly sure how to do so. J2C# returns multiple classes and I'm not really sure how to approach this.

code:
public class Features
{
    public int conditions { get; set; }
}

public class Response
{
    public string version { get; set; }
    public string termsofService { get; set; }
    public Features features { get; set; }
}

public class Image
{
    public string url { get; set; }
    public string title { get; set; }
    public string link { get; set; }
}
and so forth.

Do I make classes for each of these and have the JSON deserialize into each? All the examples I've come across are dealing with a single class. Am I missing something and you can just slap it inside one class and it just works?

Do you have an example response from the API you can post? If you've got nested objects in your Json, the easiest way is to create a class structure that matches that, i.e. a top level class which holds instances of other classes for the nested stuff.

Drastic Actions
Apr 7, 2009

FUCK YOU!
GET PUMPED!
Nap Ghost

Warbird posted:

Do I make classes for each of these and have the JSON deserialize into each? All the examples I've come across are dealing with a single class. Am I missing something and you can just slap it inside one class and it just works?

it should have given you a root object, like this

code:
public class RootObject
{
    public Response response { get; set; }
    public Location location { get; set; }
    public CurrentObservation current_observation { get; set; }
    public Forecast forecast { get; set; }
}
Which you should be able to deserialize with

code:
JsonConvert.DeserializeObject<RootObject>(jsonString);
Looking at the output json2csharp gave though, you should really clean up what it outputs. For example, it gave multiple `Forecastday` objects (Forecastday, Forecastday2) which are not needed. Also, it does the minimum of creating objects, just using the lower case for object names. You can give `JsonProperty` fields with the name of the field, then rename the actual thing whatever you want. For example.

code:
[JsonProperty("date")]
public Date ForcastDate { get; set; }

Warbird
May 23, 2012

America's Favorite Dumbass

One day I'm going to be able to say "I want to try to do X" and not end up grinding my teeth down to nubs. Can you do a pseudocode example or something of how to go from a given JSON object to a C# class or the like? I'm about to throw this computer through the first readily available window.

NihilCredo
Jun 6, 2011

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

Out of curiosity, do you have a reason for using json2csharp instead of Visual Studio's built-in "Paste JSON as classes" command?

Horn
Jun 18, 2004

Penetration is the key to success
College Slice
You probably want to use Newtonsoft Json. Their front page (http://www.newtonsoft.com/json) gives basic examples and I'm sure you can find 1000s more on stackoverflow.

chippy
Aug 16, 2006

OK I DON'T GET IT

Horn posted:

You probably want to use Newtonsoft Json. Their front page (http://www.newtonsoft.com/json) gives basic examples and I'm sure you can find 1000s more on stackoverflow.

He is, I think. He said he was using Json.NET which is what the Newtonsoft library is called.

Warbird posted:

One day I'm going to be able to say "I want to try to do X" and not end up grinding my teeth down to nubs. Can you do a pseudocode example or something of how to go from a given JSON object to a C# class or the like? I'm about to throw this computer through the first readily available window.

It's a one-liner to do the actual deserialization if you have your classes structured the same as your json, and any non-matching property names decorated with the JsonPropery attribute as Drastic Actions said:

code:
RootObject response = JsonConvert.DeserializeObject<RootObject>(jsonString);
RootObject is the type you're deserializing too, and jsonString is the json response.

What errors are you actually getting? If you give us your code and and example response, it should be fairly obvious what's going wrong.

chippy fucked around with this message at 17:29 on Mar 16, 2017

Calidus
Oct 31, 2011

Stand back I'm going to try science!

Horn posted:

You probably want to use Newtonsoft Json. Their front page (http://www.newtonsoft.com/json) gives basic examples and I'm sure you can find 1000s more on stackoverflow.

Isn't newtonsoft the default json package installed with MVC?

Warbird
May 23, 2012

America's Favorite Dumbass

NihilCredo posted:

Out of curiosity, do you have a reason for using json2csharp instead of Visual Studio's built-in "Paste JSON as classes" command?

None whatsoever. "I've been meaning to try working with APIs. It would be neat if I could make a desktop application to show the temp outside." was the entire planning process here. Strictly to see how it worked. The only reason I'm using whatever it is I am is because that's whatever guide I walked into recommended it. I really hope the VS command you're talking about is a joke or obtusely hard to use. If that's something built in and easy to use then in going to be sick.

Several hours a billion chrome tabs later all I have to show is a headache. Assume I know absolutely nothing but the basics of programming.

(ie- I once spent two weeks wondering why the html files on my webserver weren't rendering before I figured out that I needed to install Apache)

Warbird fucked around with this message at 17:42 on Mar 16, 2017

Mr. Crow
May 22, 2008

Snap City mayor for life
I find serialization is effortless until it isn't and then it's a huge pain in the rear end, so have some solace there.

Usually if you're having problems try and make it simpler and get the basic value types into a class then start building from there.

Lists and complex types are always hit and miss depending on which serialization library you're using.

chippy
Aug 16, 2006

OK I DON'T GET IT

Mr. Crow posted:

I find serialization is effortless until it isn't and then it's a huge pain in the rear end, so have some solace there..

Preach. In fact, I think you can extend this comment to working with 3rd party web based APIs, generally. I've had to do a lot of work with the Salesforce and Workplace (Facebook at work) APIs recently, and it's all either been beautiful or excruciating.

Warbird
May 23, 2012

America's Favorite Dumbass

NihilCredo posted:

Out of curiosity, do you have a reason for using json2csharp instead of Visual Studio's built-in "Paste JSON as classes" command?

God drat it, why did this have to work? Thank you all for the help!

One more, hopefully easier, best practices question. Right now I've got the generated classes sitting below my main loop/program
code:
MainWindow()
{
    foo();
    ApiStuff();
}

ApiStuff()
{
     //angst;
}

#region HellaClasses


In my (business) coding classes we were beaten with sticks if classes weren't shunted off into Classname.cs for what I assume were modularity reasons. It appears I can toss them in such a file and reference them via FizzBuzz.Rootobject, but I'm not sure I see a point in doing so. Is it advised to have this sort of setup?

Drastic Actions
Apr 7, 2009

FUCK YOU!
GET PUMPED!
Nap Ghost

Warbird posted:

One day I'm going to be able to say "I want to try to do X" and not end up grinding my teeth down to nubs. Can you do a pseudocode example or something of how to go from a given JSON object to a C# class or the like? I'm about to throw this computer through the first readily available window.

I wrote an Xamarin Workbooks Example of JSON.NET Serialization and Deserialization. You can download Workbooks here. It's free.

I would also say that I tend to not use types when using JSON.NET, and just deserialize it to `dynamic`.

Warbird
May 23, 2012

America's Favorite Dumbass

I had it working via a bit back, but you lose intellisense. I need all the help I can get, so not having it is not ideal.

Destroyenator
Dec 27, 2004

Don't ask me lady, I live in beer
Most C# coding standards mandate one class per file, it's usually a good rule until it isn't. For code like that I'd put all your generated classes in a separate file because they are "different" sort of code that should be separate from your logic, but not move them out to individual files per class because they are so closely interlinked and if you want to regenerate them it's all in one place.

Really it's a per-taste thing, the compiler doesn't care.

riichiee
Jul 5, 2007
I'm looking at creating an Excel VSTO Addin that does the following:

- Pulls data from SQL Server to an Excel Workbook.
- User then makes changes to data (offline)
- User then makes a request to "push" the data back into the database.
- A list of differences is shown.
- User then signs off on differences, adds comments, etc.. and the data is saved into SQL Server.

My understanding is that this is basically a "disconnected entities" problem, and that EF6 could handle stuff such as the list of differences, via change tracking?

Obviously there will be some massaging of the data between SQL Server & Excel, but is this the correct path to be researching?

raminasi
Jan 25, 2005

a last drink with no ice

riichiee posted:

I'm looking at creating an Excel VSTO Addin that does the following:

- Pulls data from SQL Server to an Excel Workbook.
- User then makes changes to data (offline)
- User then makes a request to "push" the data back into the database.
- A list of differences is shown.
- User then signs off on differences, adds comments, etc.. and the data is saved into SQL Server.

My understanding is that this is basically a "disconnected entities" problem, and that EF6 could handle stuff such as the list of differences, via change tracking?

Obviously there will be some massaging of the data between SQL Server & Excel, but is this the correct path to be researching?

I don't know anything about the EF6 stuff, but for Excel addins in general, Excel-DNA is slick as hell and may be worth looking into.

MisterZimbu
Mar 13, 2006

MisterZimbu posted:

Ugh, there's a longstanding bug in Visual Studio/.NET (?) that's been the bane of my existence for about a year.

  • Project is an ASP WebForms application (I've seen it in Web Site projects as well, believe I've seen it in MVC but can't remember if that's actually true)
  • Project has references to Newtonsoft.Json >= v6 and WebApi (which has a dependency on Newtonsoft.Json >= 4.5.1)
  • When you build the project, Newtonsoft.Json is not pulled from the packages folder but rather some random folder in Program Files (Blend in this case, though I've seen it come from others). The version pulled from the Program Files folder is v4.5.1, instead of the version referenced.

Usually I can bumble around for awhile and come up with a resolution, but it's something that's occurred in multiple different projects on different machines.

Today it seems that the bug has evolved to something more insane and nonsensical:

  • The project is one that has run into this sort of issue before
  • Project consists of two WebForms applications that talk to each other through some SOAP endpoints. They are not actual dependencies of each other in the build process, however.
  • In this case, when I build a single site (and that project alone), it builds correctly. However, the other one magically gets a wrong Newtonsoft.Json DLL in it's bin folder. (ie, build Website A, Website B gets a bad DLL, build Website B, Site A gets a bad DLL).
  • The projects are not dependencies of each other - in fact if I look at verbose build logs of Site A, site B is not even mentioned in the log (and vice versa when I build site B).

This is driving me insane.

This was more of a frustrated rant than a call for support, but I ended up finding the cause of this - both of the projects had a common dependency that included an older WebApi from Program Files instead of from NuGet. Both projects also included Newtonsoft.Json, so when you build the whole solution, the correct DLL gets included. However, when you built a single project, it would rebuild the dependency, and copy WebApi - and its older Json.net DLL - into the output of the other project.

Warbird
May 23, 2012

America's Favorite Dumbass

Doing Regex stuff now because that's less frustrating than JSON/APIs. Right? Right?

I've actually had a decent amount of success, but I'm tripping at the finish line. I've got a large .XPS document that I've used a scientific process to extract the data out of (zoomed all the way out and just copied pasted the text out to a .txt) and I've gotten it down to one big ol' flat CSV. Now I just want to toss some newlines in on every third comma so Excel can make it into the semi structured table it was in when it was a .XPS.
code:
string csvStructured = Regex.Replace(csvFlat, @"^([^,]+(?:,[^,]+){2}),", "$1" + Environment.NewLine);
Does what I need, but only to the first instance of the match. I've been playing with the Regex for a bit now, but haven't been able to work out why it's not cooperating. Any suggestions?

Nth Doctor
Sep 7, 2010

Darkrai used Dream Eater!
It's super effective!


Warbird posted:

Doing Regex stuff now because that's less frustrating than JSON/APIs. Right? Right?

I've actually had a decent amount of success, but I'm tripping at the finish line. I've got a large .XPS document that I've used a scientific process to extract the data out of (zoomed all the way out and just copied pasted the text out to a .txt) and I've gotten it down to one big ol' flat CSV. Now I just want to toss some newlines in on every third comma so Excel can make it into the semi structured table it was in when it was a .XPS.
code:
string csvStructured = Regex.Replace(csvFlat, @"^([^,]+(?:,[^,]+){2}),", "$1" + Environment.NewLine);
Does what I need, but only to the first instance of the match. I've been playing with the Regex for a bit now, but haven't been able to work out why it's not cooperating. Any suggestions?

I'm guessing that the leading ^ is anchoring just at the start of your string. Since you're starting with what I assume is a single line of text anyway, setting the multiline option won't work.
What you probably want is a regex more like:
code:
Regex.Replace(csvFlat, "([^,]+(?:,[^,]+){2}),", "$1" + Environment.NewLine);
It checks out in RegexBuddy.

Warbird
May 23, 2012

America's Favorite Dumbass

Beautiful, thank you! The output is still a bit off, but I'm 99% sure that due to some inconsistent formatting somewhere in the source doc. Hooray for unstructured text inputs!

Edit: Yep, some dumbass double spaced where they weren't supposed to and it threw things off mid file. Hopefully tweaking regex to break on a large whitespace amount will sort it out.

Warbird fucked around with this message at 17:06 on Mar 17, 2017

Mr Shiny Pants
Nov 12, 2012

Warbird posted:

Beautiful, thank you! The output is still a bit off, but I'm 99% sure that due to some inconsistent formatting somewhere in the source doc. Hooray for unstructured text inputs!

Edit: Yep, some dumbass double spaced where they weren't supposed to and it threw things off mid file. Hopefully tweaking regex to break on a large whitespace amount will sort it out.

Wow, you really have a way of picking "awkward" stuff. RegEx compared to JSON makes serializing seem so simple.

Nth Doctor
Sep 7, 2010

Darkrai used Dream Eater!
It's super effective!


Mr Shiny Pants posted:

Wow, you really have a way of picking "awkward" stuff. RegEx compared to JSON makes serializing seem so simple.

I'm just happy I could finally contribute. RegEx is something that weirdly clicked with me back in college, and I love using them to solve text processing problems.

Warbird
May 23, 2012

America's Favorite Dumbass

Mr Shiny Pants posted:

Wow, you really have a way of picking "awkward" stuff. RegEx compared to JSON makes serializing seem so simple.

JSON was "I don't want to work, but do something that I could leverage as being useful to work to justify not working", RegEx is "I need to parse a huge amount to text for work and I don't want to wish I was dead doing it". On that note, anyone know if VS has functionality for me to load in a .edmx and see all the entity relationships and so forth?

ModeSix
Mar 14, 2009

I'm using ASP.NET Core and EntityFramework Core.

I'm trying to add an item to a list from a database query doing the following:

code:
IEnumerable<Enrollment> enrollments = _context.Enrollments.Where(se => se.StudentEnrolled == id).ToList();

            List<GroupListViewModel> groups = new List<GroupListViewModel>();

            foreach (var group in enrollments)
            {
                
                var groupadd = _context.Groups.Where(g => g.GroupID == group.GroupId)
                .Select(gl => new GroupListViewModel
                {
                    GroupID = gl.GroupID,
                    BookID = gl.BookID,
                    Level = gl.Level,
                    NumberOfEnrollments = _context.Enrollments.Where(gi => gi.GroupId == gl.GroupID).Count(),
                    TeacherName = _context.ApplicationUser.Where(ti => ti.Id == gl.ApplicationUserID)
						.Select(tn => tn.LastName + ", " + tn.FirstName).FirstOrDefault()
                });

                groups.Add(groupadd);
	  }
On the groups.Add(groupadd); segment, it is giving me an error that says:

quote:

Argument 1: Cannot convert from 'System.Linq.IQueryable<GroupListViewModel>' to 'GroupListViewModel'

So my question is, what did I do wrong? Why won't it let me add an item to the List<GroupListViewModel> ?

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

ModeSix posted:

I'm using ASP.NET Core and EntityFramework Core.

I'm trying to add an item to a list from a database query doing the following:

code:
IEnumerable<Enrollment> enrollments = _context.Enrollments.Where(se => se.StudentEnrolled == id).ToList();

            List<GroupListViewModel> groups = new List<GroupListViewModel>();

            foreach (var group in enrollments)
            {
                
                var groupadd = _context.Groups.Where(g => g.GroupID == group.GroupId)
                .Select(gl => new GroupListViewModel
                {
                    GroupID = gl.GroupID,
                    BookID = gl.BookID,
                    Level = gl.Level,
                    NumberOfEnrollments = _context.Enrollments.Where(gi => gi.GroupId == gl.GroupID).Count(),
                    TeacherName = _context.ApplicationUser.Where(ti => ti.Id == gl.ApplicationUserID)
						.Select(tn => tn.LastName + ", " + tn.FirstName).FirstOrDefault()
                });

                groups.Add(groupadd);
	  }
On the groups.Add(groupadd); segment, it is giving me an error that says:


So my question is, what did I do wrong? Why won't it let me add an item to the List<GroupListViewModel> ?

Without more context, it looks like your .Select is going to return an IQueryable result which could potentially contain multiple objects. Then you are trying to add it as a single object to your list. You can either use SingleOrDefault or FirstOrDefault to make it to a single object. If you WANT the possibility of a collection being returned by your .Select then you can pass the results to .AddRange on your list instead of .Add.

ModeSix
Mar 14, 2009

Dr. Poz posted:

Without more context, it looks like your .Select is going to return an IQueryable result which could potentially contain multiple objects. Then you are trying to add it as a single object to your list. You can either use SingleOrDefault or FirstOrDefault to make it to a single object. If you WANT the possibility of a collection being returned by your .Select then you can pass the results to .AddRange on your list instead of .Add.

Perfect!

Thank you, AddRange was exactly what fixed it and it's doing exactly what I want it to do now.

I did in fact want all of the returned objects added to the List, because I need to iterate over them in the View to fill out a table with multiple columns.

Appreciate the help.

ModeSix fucked around with this message at 00:40 on Mar 19, 2017

Baloogan
Dec 5, 2004
Fun Shoe
IS NUGET DOWN!?!?!?!?!?

Adbot
ADBOT LOVES YOU

GameCube
Nov 21, 2006

Where the hell do I find an official copy of the Microsoft Limited Public License? I'm doing one of those awful licensing scans on our code and need to prove that we're allowed to use code from MSDN examples, which according to this page is allowed under the "Microsoft Limited Public License."

quote:

Software accessible on the Documentation Portals is made available by the designated publisher under the associated license terms. If Software is accessible on the Documentation Portals without license terms, then subject subsection (c) below you may use it to design, develop, and test your programs. If any such Software without license terms is marked as “sample” or “example,” then you may use it under the terms of the Microsoft Limited Public License.

Searching for "Microsoft Limited Public License" gets me a bunch of Stack Overflow questions and some other sites' copies of different versions of the license, but nothing official. I need the latest, official version of the license, especially considering that some sites' versions specify that the license only applies to code running on Windows, while the apparent newer version is slightly more flexible (enough that we should be okay with Xamarin).

e: Eh, nevermind, our scanner thing has the license in its own database. Good enough for me.

GameCube fucked around with this message at 20:36 on Mar 22, 2017

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