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
roflsaurus
Jun 5, 2004

GAOooooooh!! RAOR!!!

Bognar posted:

I'm assuming the existing web app uses a session cookie to maintain authorization state? If so, you can just use cookies with HttpClient. It lets you set a CookieContainer, which will handle cookies like a browser would.

Existing web app just uses the standard iis forms authentication and standard asp.net webforms controls.

I'm also using restsharp client side - not sure if that would make a difference?

Adbot
ADBOT LOVES YOU

Drastic Actions
Apr 7, 2009

FUCK YOU!
GET PUMPED!
Nap Ghost

aBagorn posted:

Go on... :allears:

Well, the good news is that you can watch it here! Here's some fun facts about the demo. A little inside info:

  • The client development did start two weeks ago. I got started three weeks ago for the server stuff.

  • The app was always going to be a messaging app, but the original theme was... let's say a bit larger. We had to change it to "Kinder Chat" because someone (either Microsoft or us) got cold feet. That change came about last week. But we never changed our namespaces, so if you look at the VS project on screen, you can see what we were going for :).

  • The actual original idea was something Miguel thought of before I got to the company. It was a joke he's been kicking around. Seeing that he had everything well thought out, I asked if he went the extra step of actually making a spec for it. And sure enough, he did. We started talking about the fesability of it and were planning on actually doing this outside of Xamarin, but then it was decided to bring it in house and use our resources. That's how I got involved.

  • The Azure crash they talked about was real. Originally the messaging server was on my own Azure account, and I totally forgot about it when we moved it to a Xamarin project. I was not there when they decided to send a blast email to everyone in the company to get it tested, so when we had all those people on it, it blew through the credits. I moved it to our own accounts, scaled it, and all was well.

  • The encrypted messaging stuff they talked about is real. Basically, here's how it works. The user creates a new account and after they enter in their confirm token, the device they are on gets added to their user as a new device, with a public and private key. Technically, this device is actually a hacked together ASP.NET Identity, because I didn't have time nor energy to roll my own solution, nor did I really want to (seriously, three weeks). I generate a username and password on the server, which the client then sends back to get an Auth token. They then use this auth token to make requests, so now I know they are, in fact, a verified user. The client generates a public/private key. The private key is stored on the device and never leaves it. The public key gets saved with the device on the server. When you send a message, it gets encrypted with the other users public key, so that when they receive it, it gets decrypted. That is live and (magically) worked great on stage.

  • The achievement system as shown was fake. There is a real system on the server that's handling them, but we didn't have time to add it into the app.

  • The link to parent feature is fake, but the original app didn't call for it being there at all. Originally, when you made a new user, a "hidden device" was added so every message you made would be sent to another entity without your knowledge. That's actually still there, so all the messages they were sending on stage were being sent to my account in Boston. And of course, it all worked :).

  • As is somewhat typical of Miguel, he had way way way more ideas for the app. On top of ideas I flat out said I wouldn't do (He wanted encrypted video. Three days before BUILD. Ha ha ha no.), we had to scale down the more ambitious elements of the app.

  • For avatars, there is a static default animal set that is pulled from the server on initial load, and have a "AvatarType" enum so if we want to add more static avatars that we can sort by type, we can. User uploaded avatars are added to the same table with a "User" value.

  • The Xamarin Inspector is legit cool and does work. There is network support in it, and originally there were going to show it off, but didn't have time. The big issue though is that it does not work over HTTPS very well. So for the demo, it's all being run over the wire with no encryption. So the "Encrypted" messaging app is not being run with SSL. The messages are encrypted on the client though, so even if you did see it, you could not read it.

  • They mentioned that we used Twillo for SMS and SendGrid for emails. We never implemented Twillo, but we did talk to them and get credits for it. Just not enough time to demo it. SendGrid was implemented, but the only reason I used it was because I didn't want this demo to touch our actual production mail client. So I figured implementing SendGrid was a good compromise.

  • They didn't show the "ServerClient" project in VS, but I wrote that. I kept documenting the API for the server, but no one had time to integrate it into the clients, so I did it for them, since I already knew what the server needed (since I wrote it :v:). So if they DID open it, you would see similar patterns to what my apps usually have, except the code is a poo poo load better, with much more and better error handling and interfaces actually being implemented. It's also integrated with Insights.

There are plans to open source the client portion of the app at some point. I don't really want to open up the server part, because the code is pretty jank (Again, three weeks, and I don't know of a net benefit anyone would have using it since it has nothing to do with Xamarin) but the client portion is really well done.. But if anyone is interested I can talk about it.

Drastic Actions fucked around with this message at 15:09 on May 2, 2015

Inverness
Feb 4, 2009

Fully configurable personal assistant.
Thank God parameterless constructors for structs are not in the RC.

That was a can of worms that didn't need to be opened.

Edit: Finally found an up-to-date bit on what got in the RC for C# 6:
  • Nameof provides a refactoring-safe way of getting the name of e.g. a parameter, member or type as a string.
  • Using null-conditional operators, you can get a built-in null check while accessing and invoking members and indexers.
  • String interpolation: String interpolation provides a concise way of describing string templates that insert expressions into format strings (C# only at Preview, both VB and C# at RTM).
  • Methods, getter-only properties, etc., can now have a single expression as their body, just like lambdas.
  • Auto-properties can have initializers and no longer require setters.
  • Index initializers: Inside an object initializer, you can now initialize a specific index of the new object. C# only.
  • Exception filters let you look at an exception and decide whether to catch it with a given catch block.
  • Using clauses for static classes bring their static members directly into scope, so you can call for example WriteLine() or Sqrt() without prefixing with the class name.
  • Await now works in catch and finally blocks, obviating some very tricky workarounds.

For primary constructors they really just need to add a new, context-sensitive keyword "primary" for constructors, because sticking it in the part with the class name is the worst thing for formatting. Either that or make "default" have a different meaning in that context:
C# code:
public class AddUserCommand : Command
{
    public default AddUserCommand(User newUser, User creator);

    public AddUserCommand(User newUser)
        : this(newUser, creator: newUser)
    {
    }
 
    public User NewUser { get; protected set; } = newUser;
    public User Creator { get; protected set; } = Verify.NotNull("creator", creator);
    Guid _creatorId = creator.Id;
}

Inverness fucked around with this message at 03:01 on May 3, 2015

Cryolite
Oct 2, 2006
sodium aluminum fluoride
I found a bug in our app due to comparisons between DateTimeOffset and DateTime. I want to audit the rest of the codebase for the same type of problem and have fishy comparisons fail a unit test or something.

Using Roslyn I can find all the BinaryExpressionSyntax I think I want to inspect, but doing it for the whole solution instead of a single file seems tough. We're still using 2013 with no immediate plans to go to 2015, so I didn't really want to write a VS code analyzer for this. Is there a story for analyzing problems across a whole solution but not by using a code analyzer? What are my options?

Pentecoastal Elites
Feb 27, 2007

Is the Windows 10 registry different than previous versions of windows?

It seems like 10 will save registry values as typed, but 7/8 saves objects that need to be parsed. Specifically I'm doing this:
code:
bool hotkeyCtrl = Convert.ToBoolean(key.GetValue("hotkeyCTRL", false));
Which works on 7/8 but fails on 10. However:
code:
bool hotkeyCtrl = (bool) key.GetValue("hotkeyCTRL", false);
Works on 10 but fails on 7/8.

Is there a better way to go about this? Is there a right way to add a shim for Win10? Just check Environment.OSVersion?

NihilCredo
Jun 6, 2011

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

Onion Knight posted:

Is the Windows 10 registry different than previous versions of windows?

It seems like 10 will save registry values as typed, but 7/8 saves objects that need to be parsed. Specifically I'm doing this:
code:
bool hotkeyCtrl = Convert.ToBoolean(key.GetValue("hotkeyCTRL", false));
Which works on 7/8 but fails on 10. However:
code:
bool hotkeyCtrl = (bool) key.GetValue("hotkeyCTRL", false);
Works on 10 but fails on 7/8.

Is there a better way to go about this? Is there a right way to add a shim for Win10? Just check Environment.OSVersion?

This ought to do the trick:

code:
Convert.ToBoolean( (object) key.GetValue("hotkeyCTRL", false))
Won't do anything on 7/8, on 10 it will box the boolean and then immediately unbox it back.

EDIT: Although I'm not sure why you're getting that exception in the first place, since Convert.ToBoolean should accept boolean inputs quite fine. This works in dotnetfiddle, for example:

code:
using System;

var rand = new Random();

for (int i = 1; i <= 100; i++)
{

var SchrödingersRegistry = rand.Next(2) >= 1 ? true : (object) "FALSE";

Console.WriteLine(Convert.ToBoolean(SchrödingersRegistry));
}

NihilCredo fucked around with this message at 11:01 on May 3, 2015

Drastic Actions
Apr 7, 2009

FUCK YOU!
GET PUMPED!
Nap Ghost

NihilCredo posted:

This ought to do the trick:

code:
Convert.ToBoolean( (object) key.GetValue("hotkeyCTRL", false))
Won't do anything on 7/8, on 10 it will box the boolean and then immediately unbox it back.

EDIT: Although I'm not sure why you're getting that exception in the first place, since Convert.ToBoolean should accept boolean inputs quite fine. This works in dotnetfiddle, for example:

code:
using System;

var rand = new Random();

for (int i = 1; i <= 100; i++)
{

var SchrödingersRegistry = rand.Next(2) >= 1 ? true : (object) "FALSE";

Console.WriteLine(Convert.ToBoolean(SchrödingersRegistry));
}

Because before he was doing this

code:
TweetThisCB.Checked = bool.Parse((string) key.GetValue("autoTweet", false));
Which would fail, since it's being cast as string even though it's a bool. Basically when I ran the app he made it would just flat out crash on 10 because of it. Casting as object should be a decent enough hack around it, but uggg, registry functions.

Inverness
Feb 4, 2009

Fully configurable personal assistant.

Drastic Actions posted:

Because before he was doing this

code:
TweetThisCB.Checked = bool.Parse((string) key.GetValue("autoTweet", false));
Which would fail, since it's being cast as string even though it's a bool. Basically when I ran the app he made it would just flat out crash on 10 because of it. Casting as object should be a decent enough hack around it, but uggg, registry functions.
Uggg, the registry in general. It seems like a great example of something that should be a virtual file system instead of what it is.

Pentecoastal Elites
Feb 27, 2007

Drastic Actions posted:

Because before he was doing this

code:
TweetThisCB.Checked = bool.Parse((string) key.GetValue("autoTweet", false));
Which would fail, since it's being cast as string even though it's a bool. Basically when I ran the app he made it would just flat out crash on 10 because of it. Casting as object should be a decent enough hack around it, but uggg, registry functions.

I interpreted your latest reply on the repo as it still failing after my changes, because what you posted caused it to fail on my machine. If you haven't tried it after yesterday, then I misinterpreted your response and I asked a dumb question here.

My original attempt at just casting the registry value to bool failed too, with the same exception, which is why I added the weird bool->string->bool conversion. Honestly I'm still not sure why that worked. I'm also not sure why it couldn't interpret the registry data as the correct type. It seems to be okay now, but that's not very helpful from a learning standpoint. I might work on it a little more and clean it up, but today I found out that ShareX is a thing, which does what I want my app to do, but better and with more features, so there's probably not much more use in the project except as a portfolio piece.
Once I get Windows 10 on my laptop I'll test it again with NihilCredo's solution, just in case.

Also I'm way new to this stuff and Drastic Action's was the first pull request I ever got and I was super pumped. Sorry if my etiquette about this stuff is way off base, haha

Cryolite
Oct 2, 2006
sodium aluminum fluoride
How safe is it to install VS2015 RC alongside VS2013? I vaguely remember reading something that said you should only install VS2015 in a VM or something that can be reformatted. Was this only for the CTPs or something like that? When it's actually released, will I be able to completely uninstall the RC and install the actual release, without messing up my system?

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

Cryolite posted:

How safe is it to install VS2015 RC alongside VS2013? I vaguely remember reading something that said you should only install VS2015 in a VM or something that can be reformatted. Was this only for the CTPs or something like that? When it's actually released, will I be able to completely uninstall the RC and install the actual release, without messing up my system?

RC is a "go live" release, meaning it is supported. I've been using it for a few weeks alongside 2013, it's fine.

NihilCredo
Jun 6, 2011

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

Onion Knight posted:

Once I get Windows 10 on my laptop I'll test it again with NihilCredo's solution, just in case.
As I edited in later, there shouldn't be any need to cast to Object, because Convert.ToBoolean() has an overload that takes a boolean argument; the first snippet you posted should work just fine. The cast wouldn't do any harm, but it would also be pointless and confusing.

Cryolite posted:

How safe is it to install VS2015 RC alongside VS2013? I vaguely remember reading something that said you should only install VS2015 in a VM or something that can be reformatted. Was this only for the CTPs or something like that? When it's actually released, will I be able to completely uninstall the RC and install the actual release, without messing up my system?

Have been running the CTP alongside VS13 for a few months now (for messing around with F#4 and with vNext, while I did production work on VS13), never had any problems.

If all my plugins work fine I'll probably switch over to VS15RC for production work too; side-by-side installations are a little expensive on a SSD.

ljw1004
Jan 18, 2005

rum

Onion Knight posted:

Is the Windows 10 registry different than previous versions of windows?

No!

quote:

Is there a better way to go about this? Is there a right way to add a shim for Win10? Just check Environment.OSVersion?

Don't check Environment.OSVersion because that's way too fragile! I'm 99.9% sure that there's something else going on. What key are you looking at? Is it a key created by your own app? I'd figure out the underlying problem before hacking around with weird casts.

Inverness
Feb 4, 2009

Fully configurable personal assistant.

Cryolite posted:

How safe is it to install VS2015 RC alongside VS2013? I vaguely remember reading something that said you should only install VS2015 in a VM or something that can be reformatted. Was this only for the CTPs or something like that? When it's actually released, will I be able to completely uninstall the RC and install the actual release, without messing up my system?
It's fine to install the 2015 RC alongside 2013. Also you won't need to uninstall the RC as it will be possible to upgrade it directly to the RTM version of the same edition.

Pentecoastal Elites
Feb 27, 2007

ljw1004 posted:

Don't check Environment.OSVersion because that's way too fragile! I'm 99.9% sure that there's something else going on. What key are you looking at? Is it a key created by your own app? I'd figure out the underlying problem before hacking around with weird casts.

That's fair.

Here's the code as it looks now. The program is a task tray app that listens for a hotkey press then uploads a user-defined screenshot crop to imgur. The source is here.
The configurations are being loaded when the app starts up, and saved only when the configuration menu is closed.

This, for me, works:
code:
        public Config()
        {
            InitializeComponent();
        }

        public void LoadConfigurations()
        {
            RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Imgruber\Config", true) ??
                              Registry.LocalMachine.CreateSubKey(@"SOFTWARE\Imgruber\Config");

            urlTB.Text = (string) key.GetValue("lastLink", ""); 
            useCtrlBOX.Checked = Convert.ToBoolean(key.GetValue("hotkeyCTRL", false));
            useAltBOX.Checked = Convert.ToBoolean(key.GetValue("hotkeyALT", false));
            HotkeyCOMBO.SelectedIndex = (int) key.GetValue("hotkeyIndex", 0);
            LinkCodeCOMBO.SelectedIndex = (int) key.GetValue("linkCodeIndex", 0);
            TweetThisCB.Checked = Convert.ToBoolean(key.GetValue("autoTweet", false));
            TweetPrependTB.Text = (string) key.GetValue("prependText", "");
        }

        private void SaveConfigurations()
        {
            RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Imgruber\Config", true);

            key.SetValue("lastLink", urlTB.Text);
            key.SetValue("hotkeyCTRL", useCtrlBOX.Checked);
            key.SetValue("hotkeyALT", useAltBOX.Checked);
            key.SetValue("hotkeyIndex", HotkeyCOMBO.SelectedIndex);
            key.SetValue("linkCodeIndex", LinkCodeCOMBO.SelectedIndex);
            key.SetValue("autoTweet", TweetThisCB.Checked);
            key.SetValue("prependText", TweetPrependTB.Text);
        }
now, if I change one of the bools like this:
code:
            useCtrlBOX.Checked = (bool) key.GetValue("hotkeyCTRL", false);
I get an InvalidCastException on that line.

Then, I went into regedit and cleared all of the keys my program generates. If the registry doesn't have an Imgruber key already, it runs and generates the default values. However, next time it runs, it'll break on the first bool again.
I've checked the registry in every case I could think of (bool cast, default values/bool cast, saved values/bool conversion, default values/bool conversion, saved values) and the registry entries look identical. They're all of type REG_SZ and their data is either True or False, without exception.
The string and int casts work totally fine, no problems with any of those.

I am stumped!

ljw1004
Jan 18, 2005

rum

Onion Knight posted:

Then, I went into regedit and cleared all of the keys my program generates. If the registry doesn't have an Imgruber key already, it runs and generates the default values. However, next time it runs, it'll break on the first bool again.
I've checked the registry in every case I could think of (bool cast, default values/bool cast, saved values/bool conversion, default values/bool conversion, saved values) and the registry entries look identical. They're all of type REG_SZ and their data is either True or False, without exception.
The string and int casts work totally fine, no problems with any of those.

I reckon in your mass of retesting you got into a mixed state.

key.SetValue("useCtrl", chkbox.Checked) will always write a REG_SZ into the registry with value "True" or "False". (This appears to be true regardless of current culture).

key.GetValue("useCtrl", false) will either return a string (if the regvalue was there), or a boolean (if the regkey was absent and it had to fall back to the default you provided which was a bool). It's up to you to handle both. Certainly the (bool) cast will fail with InvalidCastException in the first case and succeed in the second case, so it's not appropriate. Convert.ToBoolean() will succeed in both cases.

(Personally I think it's fishy to supply a default which has a different type from the thing you're actually reading from the registry... I think you should have written key.GetValue("useCtrl", "False") to simplify your code-paths).


I suspect that the difference you observed wasn't a 10 vs 7/8 issue, but was rather a "stuff was in the registry" vs "stuff wasn't yet in the registry" issue.

ljw1004 fucked around with this message at 18:47 on May 4, 2015

Literal Hamster
Mar 11, 2012

YOSPOS
I'm trying to deserialize a JSON string onto a C# class using Json.Net, but the process seems to be failing silently.

code:
public class Realm
{
	public class File
	{
		public string url { get; set; }
		public long lastModified { get; set; }
	}

	#region Realm properties

	public List<File> files { get; set; } // TODO: See if I can make this an object rather than a list
	
	...

	public async void GetAuctionDataSourceAsync( Uri uri )
	{
		using ( var client = new HttpClient() )
		{
			try
			{
				JsonConvert.PopulateObject( await client.GetStringAsync( uri ), this );
			}
			catch ( Newtonsoft.Json.JsonException e ) { Utility.Log( e ); }
			catch ( Exception e ) { Utility.Log( e ); }
		}
	}
}
I get no exceptions, I can manually download the string and write it to the console and everything seems to be in order, but files is still null. Is there someone who has worked with Json.Net that can tell me what I'm doing wrong?

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

Daysvala posted:

I'm trying to deserialize a JSON string onto a C# class using Json.Net, but the process seems to be failing silently.

code:

public class Realm
{
	public class File
	{
		public string url { get; set; }
		public long lastModified { get; set; }
	}

	#region Realm properties

	public List<File> files { get; set; } // TODO: See if I can make this an object rather than a list
	
	...

	public async void GetAuctionDataSourceAsync( Uri uri )
	{
		using ( var client = new HttpClient() )
		{
			try
			{
				JsonConvert.PopulateObject( await client.GetStringAsync( uri ), this );
			}
			catch ( Newtonsoft.Json.JsonException e ) { Utility.Log( e ); }
			catch ( Exception e ) { Utility.Log( e ); }
		}
	}
}

I get no exceptions, I can manually download the string and write it to the console and everything seems to be in order, but files is still null. Is there someone who has worked with Json.Net that can tell me what I'm doing wrong?

Don't use async void. You should be awaiting that method, so use async Task.

raminasi
Jan 25, 2005

a last drink with no ice

Daysvala posted:

I'm trying to deserialize a JSON string onto a C# class using Json.Net, but the process seems to be failing silently.

code:
public class Realm
{
	public class File
	{
		public string url { get; set; }
		public long lastModified { get; set; }
	}

	#region Realm properties

	public List<File> files { get; set; } // TODO: See if I can make this an object rather than a list
	
	...

	public async void GetAuctionDataSourceAsync( Uri uri )
	{
		using ( var client = new HttpClient() )
		{
			try
			{
				JsonConvert.PopulateObject( await client.GetStringAsync( uri ), this );
			}
			catch ( Newtonsoft.Json.JsonException e ) { Utility.Log( e ); }
			catch ( Exception e ) { Utility.Log( e ); }
		}
	}
}
I get no exceptions, I can manually download the string and write it to the console and everything seems to be in order, but files is still null. Is there someone who has worked with Json.Net that can tell me what I'm doing wrong?

Json.Net is by default pretty permissive; when it sees something it doesn't understand it just moves on instead of complaining. I don't know what the problem is, but if you pass your own JsonSerializerSettings to PopulateObject you can turn on a few "throw instead of skipping if this particular failure case is encountered" options and even wire up your own error handler.

TheReverend
Jun 21, 2005

Could someone recommend a good WCF book or a tutorial to get a REST webservice going for a SQL Server DB?

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy

TheReverend posted:

Could someone recommend a good WCF book or a tutorial to get a REST webservice going for a SQL Server DB?

Maybe I'm wrong, but I feel like the way this question is worded is exposing some misconceptions, so I'll start from the beginning.

WCF is a communication framework from Microsoft that you should probably avoid unless you are required to use it. REST is a software architecture style that literally means "representational state transfer", but effectively means something different to everyone - only Roy Fielding knows what it really means. Neither WCF nor REST has anything to do with SQL Server.

What you probably want in .NET is something like Web API which allows you to easily create HTTP endpoints to build your web service out of. There are probably some good books about it, but in my opinion the linked tutorials are good enough.

Those tutorials use Entity Framework to talk to their SQL database, but use literally whatever you want. Web API (and WCF) have no requirements on how you get your data or where you get it from.

Mr Shiny Pants
Nov 12, 2012

TheReverend posted:

Could someone recommend a good WCF book or a tutorial to get a REST webservice going for a SQL Server DB?

There are some good videos from Jim Webber on how to architect a REST service. Especially how to handle HTTP methods and the ideas behind it all.

TheReverend
Jun 21, 2005

Nice! Thanks a lot. I thought since I use .net a lot that WCF would be easiest.

I actually have a fake web service running that I made that's all socket based and non standardized so I'm trying to do it right since we decided that the concept was good.

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.
ASP.NET Web API is the current generation upgrade from WCF.

TheReverend
Jun 21, 2005

Follow up:
Would Azure make this really easy?

I'm having issues with the Azure management page right now but I've never used it and I think that's what Azure is for?

Inverness
Feb 4, 2009

Fully configurable personal assistant.
I wonder why the using statement in C# wasn't made to be more like that in C++

Sometimes it feels like a lot of boilerplate is added for using statements in C#. I don't like having my code indented too much.

I was thinking of something like this:
C# code:
private void CppStyle()
{
    using var methodScope = File.OpenRead(...);
    // stuff
    {
        using var innerScope = File.OpenRead(...);
        // inner stuff
    }
}

private void LessIndentation()
{
    using new ScopedLock(_instanceLock);
    using var stream = new FileStream(...);
    using var reader = new StreamReader(stream);
    // etc...
}
I guess because a using statement makes it more explicit as to when you're done with the resource? But then it's not like C# doesn't let you make scopes just like in C++.

raminasi
Jan 25, 2005

a last drink with no ice
fwiw, F# does that.

brap
Aug 23, 2004

Grimey Drawer
Are you sure about the scopes? I'm pretty sure I've seen people just open up a block in some C# code so they could redeclare a variable or something. It's kind of nasty when it happens.

EssOEss
Oct 23, 2006
128-bit approved

TheReverend posted:

Follow up:
Would Azure make this really easy?

I'm having issues with the Azure management page right now but I've never used it and I think that's what Azure is for?

Azure is a cloud platform that can be used for hosting web applications (and other types of server-side applications) and which provides various pre-existing services. It does not change the way you develop software unless you wish to integrate those pre-existing services it offers. If you need to make a REST web service then make a REST web service. Yes, you can easily host it in Azure. And you can easily host it elsewhere.

It may be possible to share further advice if you provide more details about what you need to accomplish.

Space Whale
Nov 6, 2014
WeirdAPI is weird, or, I'm learning a new way to do things.

To Update, not Add/Insert a new Foo to $ENDPOINT, I call hit the same url, same verb, but I just omit two properties from the JSON.

is there a clean way to programmatically ignore the serialization of these properties, or should I just make a class without them and serialize that instead?

Edit: http://www.newtonsoft.com/json/help/html/ConditionalProperties.htm

My googlefu is rusty.

Space Whale fucked around with this message at 20:59 on May 7, 2015

zokie
Feb 13, 2006

Out of many, Sweden

Inverness posted:

I wonder why the using statement in C# wasn't made to be more like that in C++

Sometimes it feels like a lot of boilerplate is added for using statements in C#. I don't like having my code indented too much.

I was thinking of something like this:
C# code:
private void CppStyle()
{
    using var methodScope = File.OpenRead(...);
    // stuff
    {
        using var innerScope = File.OpenRead(...);
        // inner stuff
    }
}

private void LessIndentation()
{
    using new ScopedLock(_instanceLock);
    using var stream = new FileStream(...);
    using var reader = new StreamReader(stream);
    // etc...
}
I guess because a using statement makes it more explicit as to when you're done with the resource? But then it's not like C# doesn't let you make scopes just like in C++.

I'm having trouble understanding what you are looking for. But using-blocks just expand to a try-finally.
C# code:
 
using(var stream = new MemoryStream)
{
    // do stuff
}
becomes
C# code:
MemoryStream stream = null;
try
{
    stream = new MemoryStream();
    // do stuff	
}
finally
{
    if(stream != null) stream.Dispose();
}
But maybe you already knew that, also. You can totally insert { } to create an extra scope, but your negations are confusing me here :)

chippy
Aug 16, 2006

OK I DON'T GET IT
loving help me goons before I kill someone.

All I want to do is copy the client area of one form, and set it as the background of another form. I've tried a million things today, mostly nicked from SO, and I either get no background or some sort of stupid "General GDI error' exception. When I write the capture BitMaps to files they are just plain black rectangles.

Here's what I have at the moment, as I say, mostly stolen

code:
Public Sub CopyFormToBackGround(formToCover As Form)
        Dim bmpScreenShot As Bitmap = New Bitmap(formToCover.Width, formToCover.Height, PixelFormat.Format32bppArgb)
        formToCover.DrawToBitmap(bmpScreenShot, New Rectangle(0, 0, Me.Width, Me.Height))
        'bmpScreenShot.Save("c:\first screenshot.bmp", ImageFormat.Bmp)

        Dim origin As Point = formToCover.PointToScreen(New Point(0, 0))
        Dim dx As Integer = origin.X - formToCover.Left
        Dim dy As Integer = origin.Y - formToCover.Right

        'Copy client area into new bitmap
        Dim width As Integer = formToCover.ClientSize.Width
        Dim height As Integer = formToCover.ClientSize.Height

        Dim clientAreaBmap As New Bitmap(width, height)

        Using graphics As Graphics = graphics.FromImage(clientAreaBmap)
            graphics.DrawImage(bmpScreenShot, 0, 0, New Rectangle(dx, dy, width, height), GraphicsUnit.Pixel)
            Dim rectangle = New Rectangle(0, 0, width, height)
            'graphics.FillRectangle(New SolidBrush(Color.FromArgb(50, Color.Black)), rectangle)
        End Using

        clientAreaBmap.Save("C:\Temp\test.bmp", ImageFormat.Bmp)
        BackgroundImage = clientAreaBmap
        Refresh()

    End Sub
This earns me a plain gray background, and a black rectangle saved to disk.

Someone save me?

p.s. Winforms

p.p.s Also tried this, similar results:

code:
        Dim bmpScreenshot = New Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb)
        Dim x = formToCover.Left
        Dim y = formToCover.Right
        Dim size = formToCover.Size

        Using g As Graphics = Graphics.FromImage(bmpScreenshot)
            g.CopyFromScreen(x, y, 0, 0, size, CopyPixelOperation.SourceCopy)
            Dim rect = New Rectangle(0, 0, size.Width, size.Height)
            'g.FillRectangle(New SolidBrush(Color.FromArgb(50, Color.Black)), rect)
        End Using

        bmpScreenshot.Save("C:\Temp\test.bmp", ImageFormat.Bmp)
        BackgroundImage = bmpScreenshot

chippy
Aug 16, 2006

OK I DON'T GET IT
Wait, no! The second bit is now getting *something*, but it's the wrong part of the screen.

I am going to shoot myself.

edit: OK, mostly there, except I'm getting the title and bar and minimize, restore, etc. controls.

final edit: Don't worry goons, you can take me off suicide watch. Next time I'll just ask for help immediately instead of just struggling for hours, as Sod's Law dictates that this will cause me to immediately get it working.

chippy fucked around with this message at 16:51 on May 7, 2015

raminasi
Jan 25, 2005

a last drink with no ice

zokie posted:

I'm having trouble understanding what you are looking for. But using-blocks just expand to a try-finally.

They just want a way to modify a declaration such that the declared variable gets Dispose called when it falls out of scope, but not requiring a new scope the way using does.

chippy
Aug 16, 2006

OK I DON'T GET IT
I loving give up.

OK, so, Plexiglasss is just a borderless form with a blurred, faded image of the form it's given in its constructor set as its background.

If I do this:

code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim glass As New Plexiglass(Me, True, True, "Test")
        glass.Show(Me)
End Sub
It works perfectly. My window is overlaid with a blurred version of itself.

But if I do this in another method of the form:

code:
 Dim glass As New Plexiglass(Me, True, True, "Storing records...")
 glass.Show(Me)
        
  ' Do some work

glass.Close()

It doesn't work. All that happens is a Rectangle object on the form goes white for a bit.
I even tried sleeping for 5 seconds in case the work was just happening too quickly. Nothing.

Someone help me before I actually do kill myself?

e: Got it. Needed to call Refresh on the glass. Anyone know why calling it in its Shown event handler wasn't enough?
ee: Putting it in the Activated handler worked. gently caress Winforms.

chippy fucked around with this message at 17:47 on May 7, 2015

Inverness
Feb 4, 2009

Fully configurable personal assistant.

zokie posted:

I'm having trouble understanding what you are looking for. But using-blocks just expand to a try-finally.

...

But maybe you already knew that, also. You can totally insert { } to create an extra scope, but your negations are confusing me here :)
What I'm saying is that rather than being forced to create a new scope, I want the using statement to apply to whatever scope its located in.

I could write something like:
C# code:
private void MyMethod()
{
    using new ScopedTimer(_fileTimer);

    _tryCount++;

    using var stream = File.OpenRead(_fileName);
    stream.DoSomething();

    _successCount++;
}
Which would be equivalent to:
C# code:
private void MyMethod()
{
    using (new ScopedTimer(_fileTimer))
    {
        _tryCount++;
        using (var stream = File.OpenRead(_fileName))
        {
            stream.DoSomething();
            _successCount++;
        }
    }
}

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

Inverness posted:

What I'm saying is that rather than being forced to create a new scope, I want the using statement to apply to whatever scope its located in.

I could write something like:
C# code:
private void MyMethod()
{
    using new ScopedTimer(_fileTimer);

    _tryCount++;

    using var stream = File.OpenRead(_fileName);
    stream.DoSomething();

    _successCount++;
}
Which would be equivalent to:
C# code:
private void MyMethod()
{
    using (new ScopedTimer(_fileTimer))
    {
        _tryCount++;
        using (var stream = File.OpenRead(_fileName))
        {
            stream.DoSomething();
            _successCount++;
        }
    }
}

That starts to fall apart when the using block doesn't coincide with the end of the method.

For example:

C# code:
private void MyMethod()
{
    using (new ScopedTimer(_fileTimer))
    {
        _tryCount++;
        using (var stream = File.OpenRead(_fileName))
        {
            stream.DoSomething();
            _successCount++;
        }
    }

    using (var anotherStream = File.OpenRead(_fileName))
    {
        anotherStream.DoSomething();
    }
}
You actually want the first stream to be disposed in this case, so it can open a new stream to the same file. It seems like it's saving you a few levels of indentation at the cost of explicitness and readability, which I generally don't like.

raminasi
Jan 25, 2005

a last drink with no ice

Ithaqua posted:

That starts to fall apart when the using block doesn't coincide with the end of the method.

For example:

C# code:
private void MyMethod()
{
    using (new ScopedTimer(_fileTimer))
    {
        _tryCount++;
        using (var stream = File.OpenRead(_fileName))
        {
            stream.DoSomething();
            _successCount++;
        }
    }

    using (var anotherStream = File.OpenRead(_fileName))
    {
        anotherStream.DoSomething();
    }
}
You actually want the first stream to be disposed in this case, so it can open a new stream to the same file. It seems like it's saving you a few levels of indentation at the cost of explicitness and readability, which I generally don't like.

This is a far less common case, though. Again, F# does this exact thing (along with "C#-style using" for when you need explicit control), and having worked with both, I much prefer the F# version, from both a readability and usability point of view.

F# also allows the neat trick of combining use bindings with object expressions:
code:
let myfunction arg1 arg2 =
    use scopeGuard = { new IDisposable with member this.Dispose() = (* do whatever cleanup *) }
    // As soon as scopeGuard falls out of scope, whatever cleanup code you specified will execute

Ciaphas
Nov 20, 2005

> BEWARE, COWARD :ovr:


Is there a "right" way to open new views in MVVM? In a possibly ill-advised attempt to avoid controlling views from a viewmodel directly, I cobbled together something like this. Is it kind of the right way to go about it?

XML code:
<!-- main window, datacontext is viewmodel -->
<Button Content="Open Sub-window" Command="{Binding OpenSubWindowCommand}"/>
C# code:
interface IWindowService // everything's an object because maybe a test harness view wouldn't use System.Windows.Window???
{
  object OpenWindow(object window);
  bool FocusWindow(object window);
  bool CloseWindow(object window);
}

class WindowService : IWindowService
{
  object OpenWindow(object window)
  {
    // type checks here
    if (window as string == "SubWindow")
    {
      System.Windows.Window w = new Window();
      w.Show();
      return w;
    }
  }
  bool FocusWindow(object window) { return (window as Window).Focus(); }
  bool CloseWindow(object window) { (window as Window).Close(); return true; }
}

class MainWindowViewModel : IDisposable
{
  private IWindowService _MyWindowService; // set in ctor
  public RelayCommand OpenSubWindowCommand = new RelayCommand(x=>OpenSubWindow());

  private object _SubWindow;
  private void OpenSubWindow()
  {
    _SubWindow = _MyWindowService.OpenWindow("SubWindow");
  } 
  
  private void FocusSubWindow() // pretend I had the command etc for this too
  {
    if (_SubWindow != null) _MyWindowService.FocusWindow(_SubWindow);
  }

  public void Dispose()
  {
    if (_SubWindow != null) MyWindowService.CloseWindow(_SubWindow);
  }
}

Ciaphas fucked around with this message at 20:59 on May 7, 2015

Adbot
ADBOT LOVES YOU

ljw1004
Jan 18, 2005

rum

Inverness posted:

What I'm saying is that rather than being forced to create a new scope, I want the using statement to apply to whatever scope its located in.

I think the difference is that in C++ doesn't have GC, so every single blasted resource has to be disposed of, which is why they made the idiom so easy to use -- at the cost of it being implicit+invisible.

C# does have GC, so you only use the "using" pattern for heavyweight resources where you want to manually be fully aware and in control of disposing of those resources. So an implicit+invisible way to call Dispose would defeat the point.

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