EzDevInfo.com

.net-3.5 interview questions

Top .net-3.5 frequently asked interview questions

LINQ's Distinct() on a particular property

I am playing with LINQ to learn about it, but I can't figure out how to use Distinct when I do not have a simple list (a simple list of integers is pretty easy to do, this is not the question). What I if want to use Distinct on a list of an Object on one or more properties of the object?

Example: If an object is Person, with Property Id. How can I get all Person and use Distinct on them with the property Id of the object?

Person1: Id=1, Name="Test1"
Person2: Id=1, Name="Test1"
Person3: Id=2, Name="Test2"

How can I get just Person1 and Person3? Is that possible?

If it's not possible with LINQ, what would be the best way to have a list of Person depending on some of its properties in .NET 3.5?


Source: (StackOverflow)

Which method performs better: .Any() vs .Count() > 0?

in the System.Linq namespace, we can now extend our IEnumerable's to have theAny() and Count() extension methods.

I was told recently that if i want to check that a collection contains 1 or more items inside it, I should use the .Any() extension method instead of the .Count() > 0 extension method because the .Count() extension method has to iterate through all the items.

Secondly, some collections have a property (not an extension method) that is Count or Length. Would it be better to use those, instead of .Any() or .Count() ?

yea / nae ?


Source: (StackOverflow)

Advertisements

Could not find default endpoint element

I've added a proxy to a webservice to a VS2008/.NET 3.5 solution. When constructing the client .NET throws this error:

Could not find default endpoint element that references contract 'IMySOAPWebService' in the service model client configuaration section. This might be because no configuaration file was found for your application or because no end point element matching this contract could be found in the client element

Searching for this error tells me to use the full namespace in the contract. Here's my app.config with full namespace:

<client>
  <endpoint address="http://192.168.100.87:7001/soap/IMySOAPWebService"
            binding="basicHttpBinding" bindingConfiguration="IMySOAPWebServicebinding"
            contract="Fusion.DataExchange.Workflows.IMySOAPWebService" name="IMySOAPWebServicePort" />
</client>

I'm running XP local (I mention this because a number of Google hits mention win2k3) The app.config is copied to app.exe.config, so that is also not the problem.

Any clues?


Source: (StackOverflow)

How to bind inverse boolean properties in WPF?

What I have is an object that has an IsReadOnly property. If this property is true, I would like to set the IsEnabled property on a Button, ( for example ), to false.

I would like to believe that I can do it as easily as IsEnabled="{Binding Path=!IsReadOnly}" but that doesn't fly with WPF.

Am I relegated to having to go through all of the style settings? Just seems too wordy for something as simple as setting one bool to the inverse of another bool.

<Button.Style>
    <Style TargetType="{x:Type Button}">
        <Style.Triggers>
            <DataTrigger Binding="{Binding Path=IsReadOnly}" Value="True">
                <Setter Property="IsEnabled" Value="False" />
            </DataTrigger>
            <DataTrigger Binding="{Binding Path=IsReadOnly}" Value="False">
                <Setter Property="IsEnabled" Value="True" />
            </DataTrigger>
        </Style.Triggers>
    </Style>
</Button.Style>

Source: (StackOverflow)

How to parse a string into a nullable int

I'm wanting to parse a string into a nullable int in C#. ie. I want to get back either the int value of the string or null if it can't be parsed.

I was kind of hoping that this would work

int? val = stringVal as int?;

But that won't work, so the way I'm doing it now is I've written this extension method

public static int? ParseNullableInt(this string value)
{
	if (value == null || value.Trim() == string.Empty)
	{
		return null;
	}
	else
	{
		try
		{
			return int.Parse(value);
		}
		catch
		{
			return null;
		}
	}
}

Is there a better way of doing this?

EDIT: Thanks for the TryParse suggestions, I did know about that, but it worked out about the same. I'm more interested in knowing if there is a built-in framework method that will parse directly into a nullable int?


Source: (StackOverflow)

Why Response.Redirect causes System.Threading.ThreadAbortException?

When I use Response.Redirect(...) to redirect my form to a new page I get the error:

A first chance exception of type 'System.Threading.ThreadAbortException' occurred in mscorlib.dll
An exception of type 'System.Threading.ThreadAbortException' occurred in mscorlib.dll but was not handled in user code

My understanding of this is that the error is being caused by the webserver aborting the remainder of the page the response.redirect was called on.

I know I can add a second parameter to Response.Redirect that is called endResponse. If I set endResponse to True I still get the error but if I set it to False then I do not. I am pretty sure though that that means the webserver is running the rest of the page I redirected away from. Which would seem to be inefficient to say the least. Is there a better way to do this? Something other than Response.Redirect or is there a way to force the old page to stop loading where I will not get a ThreadAbortException?


Source: (StackOverflow)

Use LINQ to get items in one List<>, that are not in another List<>

I would assume there's a simple LINQ query to do this, I'm just not exactly sure how. Please see code snippet below, the comment explains what I'd like to do:

class Program
{
    static void Main(string[] args)
    {
        List<Person> peopleList1 = new List<Person>();
        peopleList1.Add(new Person() { ID = 1 });
        peopleList1.Add(new Person() { ID = 2 });
        peopleList1.Add(new Person() { ID = 3 });

        List<Person> peopleList2 = new List<Person>();
        peopleList2.Add(new Person() { ID = 1 });
        peopleList2.Add(new Person() { ID = 2 });
        peopleList2.Add(new Person() { ID = 3 });
        peopleList2.Add(new Person() { ID = 4 });
        peopleList2.Add(new Person() { ID = 5 });

        //I would like to perform a LINQ query to give me all
        //of the people in 'peopleList2' that are not in 'peopleList1'
        //this example should give me two people (ID = 4 & ID = 5)
    }
}

class Person
{
    public int ID { get; set; }
}

Source: (StackOverflow)

Named string formatting in C#

Is there any way to format a string by name rather than position in C#?

In python, I can do something like this example (shamelessly stolen from here):

>>> print '%(language)s has %(#)03d quote types.' % \
      {'language': "Python", "#": 2}
Python has 002 quote types.

Is there any way to do this in C#? Say for instance:

String.Format("{some_variable}: {some_other_variable}", ...);

Being able to do this using a variable name would be nice, but a dictionary is acceptable too.

UPDATE: I ended up doing something like this post, but it's definitely not pretty. I'll try out John Sheehan's approach, but if anybody has any other suggestions in the meantime, feel free to add them. :)

UPDATE 2: John Sheehan's approach works pretty well. Accepting it.


Source: (StackOverflow)

How can I take more control in ASP.NET?

I'm trying to build a very, very simple "micro-webapp" which I suspect will be of interest to a few Stack Overflow'rs if I ever get it done. I'm hosting it on my C# in Depth site, which is vanilla ASP.NET 3.5 (i.e. not MVC).

The flow is very simple:

  • If a user enters the app with a URL which doesn't specify all the parameters (or if any of them are invalid) I want to just display the user input controls. (There are only two.)
  • If a user enters the app with a URL which does have all the required parameters, I want to display the results and the input controls (so they can change the parameters)

Here are my self-imposed requirements (mixture of design and implementation):

  • I want the submission to use GET rather than POST, mostly so users can bookmark the page easily.
  • I don't want the URL to end up looking silly after submission, with extraneous bits and pieces on it. Just the main URL and the real parameters please.
  • Ideally I'd like to avoid requiring JavaScript at all. There's no good reason for it in this app.
  • I want to be able to access the controls during render time and set values etc. In particular, I want to be able to set the default values of the controls to the parameter values passed in, if ASP.NET can't do this automatically for me (within the other restrictions).
  • I'm happy to do all the parameter validation myself, and I don't need much in the way of server side events. It's really simple to set everything on page load instead of attaching events to buttons etc.

Most of this is okay, but I haven't found any way of completely removing the viewstate and keeping the rest of the useful functionality. Using the post from this blog post I've managed to avoid getting any actual value for the viewstate - but it still ends up as a parameter on the URL, which looks really ugly.

If I make it a plain HTML form instead of an ASP.NET form (i.e. take out runat="server") then I don't get any magic viewstate - but then I can't access the controls programmatically.

I could do all of this by ignoring most of ASP.NET and building up an XML document with LINQ to XML, and implementing IHttpHandler. That feels a bit low level though.

I realise that my problems could be solved by either relaxing my constraints (e.g. using POST and not caring about the surplus parameter) or by using ASP.NET MVC, but are my requirements really unreasonable?

Maybe ASP.NET just doesn't scale down to this sort of app? There's a very likely alternative though: I'm just being stupid, and there's a perfectly simple way of doing it that I just haven't found.

Any thoughts, anyone? (Cue comments of how the mighty are fallen, etc. That's fine - I hope I've never claimed to be an ASP.NET expert, as the truth is quite the opposite...)


Source: (StackOverflow)

Entity Framework and SQL Server View

For several reasons that I don't have the liberty to talk about, we are defining a view on our Sql Server 2005 database like so:

CREATE VIEW [dbo].[MeterProvingStatisticsPoint]
AS
SELECT
    CAST(0 AS BIGINT) AS 'RowNumber',
    CAST(0 AS BIGINT) AS 'ProverTicketId',
    CAST(0 AS INT) AS 'ReportNumber',
    GETDATE() AS 'CompletedDateTime',
    CAST(1.1 AS float) AS 'MeterFactor',
    CAST(1.1 AS float) AS 'Density',
    CAST(1.1 AS float) AS 'FlowRate',
    CAST(1.1 AS float) AS 'Average',
    CAST(1.1 AS float) AS 'StandardDeviation',
    CAST(1.1 AS float) AS 'MeanPlus2XStandardDeviation',
    CAST(1.1 AS float) AS 'MeanMinus2XStandardDeviation'
WHERE 0 = 1

The idea is that the Entity Framework will create an entity based on this query, which it does, but it generates it with an error that states the following:

Warning 6002: The table/view 'Keystone_Local.dbo.MeterProvingStatisticsPoint' does not have a primary key defined. The key has been inferred and the definition was created as a read-only table/view.

And it decides that the CompletedDateTime field will be this entity primary key.

We are using EdmGen to generate the model. Is there a way not to have the entity framework include any field of this view as a primary key?


Source: (StackOverflow)

Conditional Compilation and Framework Targets

There are a few minor places where code for my project may be able to be drastically improved if the target framework were a newer version. I'd like to be able to better leverage conditional compilation in C# to switch these as needed.

Something like:

#if NET40
using FooXX = Foo40;
#elif NET35
using FooXX = Foo35;
#else NET20
using FooXX = Foo20;
#endif

Do any of these symbols come for free? Do I need to inject these symbols as part of the project configuration? Seems easy enough to do since I'll know which framework is being targeted from MSBuild.

/p:DefineConstants="NET40"

Update: My question is how are people handling this situation? Are you creating different configurations? Are you passing in the constants via the command line?


Source: (StackOverflow)

How do I tell if .NET 3.5 SP1 is installed?

How can I find out if SP1 has been installed on a server which has .NET 3.5?


Source: (StackOverflow)

Converting a generic list to a CSV string

I have a list of integer values (List) and would like to generate a string of comma delimited values. That is all items in the list output to a single comma delimted list.

My thoughts... 1. pass the list to a method. 2. Use stringbuilder to iterate the list and append commas 3. Test the last character and if it's a comma, delete it.

What are your thoughts? Is this the best way?

How would my code change if I wanted to handle not only integers (my current plan) but strings, longs, doubles, bools, etc, etc. in the future? I guess make it accept a list of any type.


Source: (StackOverflow)

Memcached with Windows and .NET

Is there anyone already implement memcached for production use in Windows environment? Because many blogs that I've read, it's not recommended to run memcached in Windows especially for production use, for example running memcached on windows.

And one more thing, which memcached client that is good to use with c# and .net 3.5 ? I've found many alternate such as Memcached Providers @ Codeplex, Beitmemcached, and memcached provider @ Sourceforge


Source: (StackOverflow)

Why can't an anonymous method be assigned to var?

I have the following code:

Func<string, bool> comparer = delegate(string value) {
    return value != "0";
};

However, the following does not compile:

var comparer = delegate(string value) {
    return value != "0";
};

Why can't the compiler figure out it is a Func<string, bool>? It takes one string parameter, and returns a boolean. Instead, it gives me the error:

Cannot assign anonymous method to an implicitly-typed local variable.

I have one guess and that is if the var version compiled, it would lack consistency if I had the following:

var comparer = delegate(string arg1, string arg2, string arg3, string arg4, string arg5) {
    return false;
};

The above wouldn't make sense since Func<> allows only up to 4 arguments (in .NET 3.5, which is what I am using). Perhaps someone could clarify the problem. Thanks.


Source: (StackOverflow)