- Sedro
- Dec 31, 2008
-
|
If I'm inheriting from an abstract class, is there really no way to make one of the overridden properties more accessible without essentially duplicating it?
Explicit interface implementation might work for you. Just cast or implicitly convert to IButt when you need to access the property.
C# code:public interface IButt
{
int Size { get; }
}
public abstract class AbstractButt
{
protected abstract int Size { get; }
}
public class ConcreteButt : AbstractButt, IButt
{
protected override int Size { get { return 10; } }
int IButt.Size { get { return Size; } }
}
|
#
¿
Jul 16, 2014 20:54
|
|
- Adbot
-
ADBOT LOVES YOU
|
|
#
¿
May 4, 2024 18:14
|
|
- Sedro
- Dec 31, 2008
-
|
Bueller? Anyone? I still haven't figured this out.
This seems to work
Service:
C# code:public class Request { public string Body { get; set; } }
public class Response { public string Body { get; set; } }
public interface IMyService
{
Task<Response> DoSomethingAsync(Request request);
}
public class MyService : IMyService
{
int i = 0;
public async Task<Response> DoSomethingAsync(Request request)
{
await Task.Delay(TimeSpan.FromSeconds(1));
// simulate transient failure
if (i < 3)
{
++i;
Console.WriteLine("Failure " + i);
throw new Exception("Failure " + i);
}
// eventual success
return new Response { Body = request.Body };
}
}
Behavior:
C# code:public class RetryBehavior : IInterceptionBehavior
{
static MethodBase DoSomethingAsync = typeof(IMyService).GetMethod("DoSomethingAsync");
readonly RetryPolicy policy = RetryPolicy.DefaultFixed;
public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
{
if (input.MethodBase == DoSomethingAsync)
{
// inject retry policy
var task = policy.ExecuteAsync(() =>
{
var result = getNext()(input, getNext);
return result.ReturnValue as Task<Response>;
});
return input.CreateMethodReturn(task);
}
return getNext()(input, getNext);
}
public IEnumerable<Type> GetRequiredInterfaces()
{
yield return typeof(IMyService);
}
public bool WillExecute
{
get { return true; }
}
}
Usage:
C# code:var container = new UnityContainer();
container.AddNewExtension<Interception>();
container.RegisterType<IMyService, MyService>(
new Interceptor<InterfaceInterceptor>(),
new InterceptionBehavior<RetryBehavior>());
var service = container.Resolve<IMyService>();
var future = service.DoSomethingAsync(new Request { Body = "butts" });
var response = future.GetAwaiter().GetResult(); // can't await in a console app
Console.WriteLine(response.Body);
Output:
code:Failure 1
Failure 2
Failure 3
butts
|
#
¿
Jul 17, 2014 17:19
|
|
- Sedro
- Dec 31, 2008
-
|
I'd like to know what gets spit out by Path.GetInvalidFileNameChars(). Is there a more reasonable thing for me to do than boot up a new console app and print them to screen? I feel like Visual Studio should have some sort of console that I can type commands like this into.
If you already have something running in a debugger you can use the "Immediate" window. You can't use lambda expressions though which makes it useless 90% of the time.
|
#
¿
Jul 25, 2014 16:45
|
|
- Sedro
- Dec 31, 2008
-
|
I would swear there was an easy way to do this. Isn't there a way to go from a lambda to the full, written out expression (in other words, creating expressions by explicitly calling Expression.whatever)? Sometimes I feel like it would be helpful when trying to do things with expressions if I could just write out simple examples and look at the results.
It's an implicit conversion provided by the language. The compiler will generate the expression tree.
C# code:Expression<Func<string, int>> expr = s => s.Length;
|
#
¿
Jul 26, 2014 00:44
|
|
- Sedro
- Dec 31, 2008
-
|
So I'm using ReactiveUI to build a WPF application and I'm stumped. I'm trying to link the selected value of a listview to an observable property and then trigger a ReactiveCommand.
How do I do this? Reactive's docs are lacking, to say the least.
Here's an example
C# code:using System.Reactive.Linq;
// an interface for the main view-model
public interface IViewModel
{
IList<ItemViewModel> Items { get; }
ItemViewModel SelectedItem { get; set; }
ICommand Command { get; }
}
// main application view-model with a list of things
public class ViewModel : ReactiveObject, IViewModel
{
public ViewModel()
{
items = new ReactiveList<ItemViewModel>
{
new ItemViewModel { Value = "foo" },
new ItemViewModel { Value = "bar" },
};
// Require that something is selected
var canExecute = this.ObservableForProperty(x => x.SelectedItem).Select(x => x != null);
command = ReactiveCommand.CreateAsyncTask(canExecute, async o =>
{
// simulate delay
await Task.Delay(TimeSpan.FromSeconds(2));
MessageBox.Show("Done!");
return Unit.Default;
});
}
readonly ReactiveList<ItemViewModel> items;
public IList<ItemViewModel> Items
{
get { return items; }
}
ItemViewModel selectedItem;
public ItemViewModel SelectedItem
{
get { return selectedItem; }
set { this.RaiseAndSetIfChanged(ref selectedItem, value); }
}
readonly ReactiveCommand<Unit> command;
public ICommand Command
{
get { return command; }
}
}
// view-model representing an item in the list
public class ItemViewModel
{
public string Value { get; set; }
}
XAML
XML code:<Window
x:Class="ReactiveUITest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:myapp="clr-namespace:ReactiveUITest"
Title="MainWindow" Height="350" Width="525"
>
<Window.DataContext>
<!-- Instantiating the view model in XAML, because I can -->
<myapp:ViewModel/>
</Window.DataContext>
<StackPanel>
<ListBox
ItemsSource="{Binding Path=Items, Mode=OneTime}"
SelectedItem="{Binding Path=SelectedItem, Mode=TwoWay}"
DisplayMemberPath="Value"
/>
<TextBlock>
<Run Text="Selected:"/>
<Run Text="{Binding SelectedItem.Value}"/>
</TextBlock>
<Button Content="Clicky" Command="{Binding Path=Command}"/>
</StackPanel>
</Window>
|
#
¿
Jul 29, 2014 20:00
|
|
- Sedro
- Dec 31, 2008
-
|
You have to use ClassB (with initialization in the ctor) or ClassC.
They do plan to add this to the language [source].
|
#
¿
Aug 1, 2014 17:32
|
|
- Sedro
- Dec 31, 2008
-
|
Agreed. Immutable POCOs are still second-class.
C# code:// Mutable
public class A
{
public int X { get; set; }
public string Y { get; set; }
}
new A { X = 123, Y = "foobar" };
// Immutable
public class A
{
readonly int x;
readonly string y;
public A(int x, string y)
{
this.x = x;
this.y = y;
}
public int X { get { return x; } }
public string Y { get { return y; } }
}
new A(x: 123, y: "foobar");
Ideally we could use the initializer syntax with immutable objects too
C# code:class A
{
int X { get; readonly set; }
string Y { get; readonly set; }
}
var a = new A { X = 123, Y = "foobar" };
a.X = 456; // error
|
#
¿
Aug 1, 2014 21:13
|
|
- Sedro
- Dec 31, 2008
-
|
Have your interface to those services only deal with your own Pet model which has the properties you care about. If there is some agreed-upon Pet ID, use that (obviously pets don't have unique IDs but your domain might). Basically, don't pollute your system with other systems' representations--convert all Pets to your own representation ASAP.
|
#
¿
Aug 8, 2014 20:22
|
|
- Sedro
- Dec 31, 2008
-
|
Can't you just have a dependency property representing the stringified value?
|
#
¿
Aug 11, 2014 18:55
|
|
- Sedro
- Dec 31, 2008
-
|
Windbg can tell you what exactly is keeping the object around. I posted an example in the last thread but I can't search posts...
|
#
¿
Aug 18, 2014 04:30
|
|
- Sedro
- Dec 31, 2008
-
|
You should already have the fields generated, so the code would reduce to this
C# code:public class Foo(IButts butts, IDongs dongs)
{
public Foo() : this(new RegularButts(), new RegularDongs()) {}
}
|
#
¿
Aug 20, 2014 19:02
|
|
- Sedro
- Dec 31, 2008
-
|
I thought so at first, but I did some reading that indicated that the primary constructor parameters are only available during class initialization, so you have to assign them into a field or something.
So primary constructors will save exactly 1 line of code (excluding braces)? I hope that's not the case.
Edit: I guess it also removes the need for field assignments e.g. this.foo = foo. But still not in the same league as scala's case classes.
Sedro fucked around with this message at 19:29 on Aug 20, 2014
|
#
¿
Aug 20, 2014 19:26
|
|
- Sedro
- Dec 31, 2008
-
|
ObservableCollection has lots of warts. In case you wanted a real answer, you can just convert the ObservableCollection into an INotifyPropertyChanged.
|
#
¿
Aug 28, 2014 04:05
|
|
- Sedro
- Dec 31, 2008
-
|
Right. LINQ to Objects methods execute lazily. In the example above, it doesn't start executing the Where or the OrderBy until you start accessing the values in result.
OrderBy is a little special because you need to materialize the entire collection in order to produce the first item. It might as well return a list.
|
#
¿
Aug 29, 2014 18:27
|
|
- Sedro
- Dec 31, 2008
-
|
JSON in the URL is not just marginally less readable, it's incomprehensible
Before encoding, hmm doesn't look so bad
code:/Search?term=pumas&filters={"productType":["Clothing","Bags"],"color":["Black","Red"]}
After encoding
code:/Search?term=pumas&filters=%7B%22productType%22%3A%5B%22Clothing%22%2C%22Bags%22%5D%2C%22color%22%3A%5B%22Black%22%2C%22Red%22%5D%7D
it
|
#
¿
Sep 4, 2014 23:43
|
|
- Sedro
- Dec 31, 2008
-
|
If you do think assembly loading is the problem, there's fusion logs.
I'm looking into this now since I have to do this with another image source that already has images of the right size. However, that leads to:
Pull the filename out of the response header, examples here.
|
#
¿
Sep 12, 2014 01:28
|
|
- Sedro
- Dec 31, 2008
-
|
Does the type have a .cctor or any static fields?
|
#
¿
Sep 12, 2014 02:02
|
|
- Sedro
- Dec 31, 2008
-
|
The only thing I'm not sure is how to peel off the file from the webclient OpenRead without making another DownloadFile/request operation, something to do with StreamReader maybe.
C# code:using (var contents = webClient.OpenRead(...))
using (var fs = File.Create(@"\path\to\file"))
{
contents.CopyTo(fs);
}
|
#
¿
Sep 12, 2014 03:03
|
|
- Sedro
- Dec 31, 2008
-
|
Obvious question, does it throw an exception?
|
#
¿
Sep 12, 2014 04:38
|
|
- Sedro
- Dec 31, 2008
-
|
I'm having a weird issue with a double value drifting in a for loop. I wrote a C# program to control another program and the details don't really matter but after some amount of time my double drifts by ~0.00000000000001 and it is messing with my measurements a little bit.
Floating point addition and multiplication aren't associative because every computation may result in a loss of precision.
Your loop compounds the precision errors from previous loop iterations. You need to rewrite your loop so that size does not depend on the previous iteration.
Wrong:
C# code:double size = 1.95;
for (int i = 1; i <= 80; ++i) {
size += .05;
// use size
}
Right:
C# code:double initial = 1.95;
for (int i = 1; i <= 80; ++i) {
double size = initial + i * .05;
// use size
}
Increasing the size of the number from double (64-bit) to decimal (128-bit) does not fix the problem.
|
#
¿
Sep 14, 2014 22:13
|
|
- Sedro
- Dec 31, 2008
-
|
Where clauses are normally cumulative, so why would Linq-to-Entities/Linq-to-SQL be any different?
C# code:Enumerable.Range(1, 5).Where(x => x != 2).Where(x => x != 4); // 1, 3, 5
|
#
¿
Sep 16, 2014 17:09
|
|
- Sedro
- Dec 31, 2008
-
|
I'd honestly never considered it before. I always assumed that multiple Wheres in LINQ to Objects wasn't cumulative, so doing that would iterate the list once, and give you 1,3,4,5. Then it would iterate the second list and give you 1,3,5. Of course, now that I think about it, it makes sense that it would be able to be optimized so the list is only iterated a single time.
The more you know.
It's usually safe to think of Linq iterating the list and producing a new list each time. Though with infinite lists, the laziness is no longer an optimization and actually necessary for correctness. For example you could create a random number generator, then transform it to get random numbers which are even.
C# code:static IEnumerable<int> Randoms() {
var random = new Random();
while (true) yield return random.Next();
}
// if Where wasn't lazy this would never terminate
Randoms().Where(x => x % 2 == 0);
I like to think of IQueryable as transforming an SQL query instead of a sequence of values.
C# code:SQL.Range(1, 5).Where(x => x != 2).Where(x => x != 4);
SQL("select i from ( values (1), (2), (3), (4), (5) ) as t(i)").Where(x => x != 2).Where(x => x != 4);
SQL("select i from ( select i from ( values (1), (2), (3), (4), (5) ) as t(i) ) t where i <> 2").Where(x => x != 4);
SQL("select i from ( select i from ( select i from ( values (1), (2), (3), (4), (5) ) as t(i) ) t where i <> 2 ) where i <> 4");
|
#
¿
Sep 16, 2014 21:24
|
|
- Sedro
- Dec 31, 2008
-
|
C# code:foreach(System.Configuration.SettingsProperty setting in Settings.Default.Properties)
{
// setting is a SettingsProperty
}
...
Isn't the whole point of strong static typed languages to avoid this sort of problem? Is this an edge case wart that was a side effect of the introduction of generics which we're happy enough to suffer? (Or an edge case that appeared after the introduction of both generics and the var keyword?)
The loop unsafely casts each item from object to System.Configuration.SettingsProperty. It dates back to C# before generics. Compare to looping in Java 1.4 which existed around the same time.
Java code:while (iter.hasNext()) {
SettingsProperty = (SettingsProperty)iter.next();
}
They couldn't exactly remove the feature from the language once generics were introduced.
|
#
¿
Sep 18, 2014 16:47
|
|
- Sedro
- Dec 31, 2008
-
|
Is it possible to write a generic wrapper that lets you do something like .Where(Not(string.IsNullOrEmpty))? The closest I can get is this:
code:Func<T, bool> Not<T>(Func<T, bool> action)
{
return (T parameter) => !action(parameter);
}
But the only way to use it is .Where(Not<string>(string.IsNullOrEmpty))); and I don't like how it won't infer the template, but I don't know how to fix that
It's not possible in C# because string.IsNullOrEmpty is typeless. In the case of Enumerable.Where<T>, the type parameter T is inferred from the IEnumerable<T> rather than the Func<T, bool>.
|
#
¿
Oct 20, 2014 18:52
|
|
- Sedro
- Dec 31, 2008
-
|
In the world of dumb micro-optimizations this is probably up there.
However the annoyance of null checking events everywhere can be circumvented (along with boilerplate event-raising logic) with a simple extension method. This also satisfies the 'performance' inclined as well, and in my opinion is just easier to use/read.
code:public static void Raise(this EventHandler handler, object sender, EventArgs e)
{
if (handler != null)
{
handler(sender, e);
}
}
code:Butts.Raise(this, new ButtsArg());
I think you end up making a total of like 6 overloads for the various event handler types that don't derive from EventHandler, for example NotifyCollectionChangedEventHandler.
But now you're constructing the EventArgs even if you don't fire the event! You could pass them as Func<EventArgs> but now you're constructing delegates, which was the "problem" we were originally trying to avoid.
|
#
¿
Nov 17, 2014 19:09
|
|
- Sedro
- Dec 31, 2008
-
|
I'm trying to union a couple of lists of objects on some subset of their properties and this is the thing I came up with:
C# code:public static IEnumerable<TSource> DelegateUnion<TSource>(
this IEnumerable<TSource> left,
IEnumerable<TSource> right,
Func<TSource, TSource, bool> comparator)
{
var sent = new List<TSource>();
Func<TSource, bool> partialComp = (thingy) => sent.Any(sentMember => comparator(sentMember, thingy));
foreach (var sourceThingy in left.Concat(right))
{
if (sent.Any(partialComp)) continue;
yield return sourceThingy;
sent.Add(sourceThingy);
}
}
//usage:
listA.DelegateUnion(listB, (l, r) => l.A == r.A && l.B == r.B)
Ex: http://dotnetpad.net/ViewPaste/Y9oTeaonakydgugrAofGoA
The actual properties are ints so the comparison function in the example is actually very close to what mine actually is.
Am I missing something less slow and convoluted? Should I just go ahead and post this in the coding horrors thread?
How about this
C# code:public static IEnumerable<T> UnionBy<T>(this IEnumerable<T> left, IEnumerable<T> right, Func<T, IStructuralEquatable> selector)
{
return left.Concat(right).ToLookup(selector).Select(x => x.First());
}
class MyClass
{
public int A { get; set; }
public int B { get; set; }
public int C { get; set; }
}
var listA = new List<MyClass> { new MyClass { A = 1, B = 2, C = 3 } };
var listB = new List<MyClass> { new MyClass { A = 1, B = 2, C = 5 } };
listA.UnionBy(listB, x => Tuple.Create(x.A, x.B)).Count(); // 1
listA.UnionBy(listB, x => Tuple.Create(x.A, x.B, x.C)).Count(); // 2
As a tangent, tuples have some odd equality properties. They don't implement operator== so it falls back to the default behavior of comparing object references.
C# code:var a = Tuple.Create(1,2);
var b = Tuple.Create(1,2);
a == b // false
a.Equals(b) // true
Knowing this, we can systematically reduce this logic
C# code:c.DelegateUnion(d, (l, r) => l.Item1 == r.Item1 && l.Item2 == r.Item2).Count()
// the expression above implements the default Tuple equality
c.DelegateUnion(d, (l, r) => l.Equals(r)).Count()
// the method group is a bit cleaner
c.DelegateUnion(d, Object.Equals).Count()
// and the above expression is the same as the default Union
c.Union(d).Count()
Sedro fucked around with this message at 17:10 on Nov 19, 2014
|
#
¿
Nov 19, 2014 17:07
|
|
- Sedro
- Dec 31, 2008
-
|
This all is interesting because previously the only advice I've ever read about rolling my own GetHashCode or extending the existing one is "don't" but that SO answer looks like it'll work* so thanks.
E: was messing with dotnetpad too long and missed Sedro's reply which is also a neat idea - thanks! I didn't realize IStructuralEquatable would make it so simple.
*though that example may be me getting too clever for my own good
There's nothing special about IStructuralEquatable, I was just using it as a marker for tuples of any arity. You could also use ITuple (more specific) or simply object (less specific) since everything has an Equals method.
You can compare UnionBy to the built-in Linq functions:
C# code:listA.OrderBy(x => Tuple.Create(x.B, x.C));
listA.GroupBy(x => Tuple.Create(x.B, x.C));
|
#
¿
Nov 19, 2014 18:58
|
|
- Sedro
- Dec 31, 2008
-
|
Java also provides "thread safe" versions of their collections
|
#
¿
Dec 2, 2014 16:43
|
|
- Sedro
- Dec 31, 2008
-
|
I can't think of a scenario where creation time would be a real factor when it comes to AppDomain versus a separate process. If you were doing a bunch of small things frequently you would use pooling and job queuing like with threads, no? Communication speed between processes would be the bigger concern I think. I've rarely ever used IPC so I don't know how well that would work.
Maybe if you are doing a bunch of things frequently which involve running untrusted/fenced code, like a plugin system. Intra-process communication between AppDomains would presumably be faster than standard IPC. Also it's the only way to unload code.
|
#
¿
Dec 7, 2014 07:13
|
|
- Sedro
- Dec 31, 2008
-
|
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.
You can, but the List in .NET doesn't implement equality/hash in terms of its items. So you should use a custom EqualityComparer when you construct the dictionary.
|
#
¿
Dec 22, 2014 18:33
|
|
- Sedro
- Dec 31, 2008
-
|
It's reasonable to use a list because query results are ordered.
The mismatch is when you try to pretend that foreign key relationships are object references. I've found that treating a database as sets of tuples leads to cleaner code and better performance on the order of magnitudes.
|
#
¿
Jan 6, 2015 19:56
|
|
- Sedro
- Dec 31, 2008
-
|
Why does it seem like everyone is making web apps as opposed to local apps? In my shop we have no need for any special internet applications outside of the browser and with HIPAA we have little to no reason to unnecessarily expose our data to the internet more than required.
Web apps don't have to be exposed to the internet
|
#
¿
Jan 12, 2015 03:27
|
|
- Sedro
- Dec 31, 2008
-
|
Pull the QueryParser construction out of the loop? Also you can probably use MultiFieldQueryParser. Also consider whether you even need category IDs to be analyzed
|
#
¿
Jan 13, 2015 23:29
|
|
- Sedro
- Dec 31, 2008
-
|
As far as whether you should, APIs like this are pretty common
pre:GET /posts fetch all posts
GET /posts/16 fetch specific post #16
GET /posts/16/comments fetch all comments for post #16
GET /posts/16/comments/7 fetch specific comment #7 for post #16
|
#
¿
Jan 20, 2015 21:18
|
|
- Sedro
- Dec 31, 2008
-
|
You should use FromResult if you already know the result
C# code:() => Task.FromResult(myList.Count)
|
#
¿
Mar 5, 2015 19:48
|
|
- Sedro
- Dec 31, 2008
-
|
Why would the Response class have a close method?
|
#
¿
Mar 12, 2015 04:59
|
|
- Sedro
- Dec 31, 2008
-
|
I'm wondering if it's better to keep ViewModels coupled more towards frameworks (WPF, etc..) building a new set of VMs for each different 'View' framework and not worry about it? OR should I have a single ViewModel which can work in Wpf/WinForms/ASP.NET whatever???
Generally speaking, the purpose of the view-model/controller is to translate your (e.g. pre-existing, domain-specific) model into a form which is easily consumable from a given UI technology. So yes, it would be normal to have different view-models.
|
#
¿
Mar 13, 2015 21:47
|
|
- Sedro
- Dec 31, 2008
-
|
Yeah, the generated "MainWindow" in a default WPF project inherits from Window, so I wouldn't call that bad practice.
|
#
¿
Mar 19, 2015 01:45
|
|
- Sedro
- Dec 31, 2008
-
|
Is there any option for C# desktop apps that isn't totally painful?
no
|
#
¿
Apr 8, 2015 01:40
|
|
- Adbot
-
ADBOT LOVES YOU
|
|
#
¿
May 4, 2024 18:14
|
|
- Sedro
- Dec 31, 2008
-
|
Unfortunately dotCoverage is a Visual Studio plugin which I can't use at the moment. I need something that works outside of Visual Studio. Preferably something that can be implemented into a build pipeline inside of Jenkins or some other CI server.
TeamCity has a dropdown for dotCover, NCover and PartCover, so use one of those? I don't use code coverage so can't recommend one.
|
#
¿
Apr 9, 2015 17:33
|
|