Get the Nth Minimum or Nth Maximum number from a collection C#

For a collection of integers/decimals, we can use the .Max() and .Min() to get the maximum and minimum value of the collection respectively.
However, there are two more case scenarios, that I have faced, which I am going to discuss next. Following is the definition of a class Item that I am going to use here:

class Item: IComparable<Item>
{
    public string itemName { get; set; }
    public int itemPrice { get; set; }

    int IComparable<Item>.CompareTo(Item other)
    {
        if (other.itemPrice > this.itemPrice)
            return -1;
        else if (other.itemPrice == this.itemPrice)
            return 0;
        else 
            return 1;
    }

 
	//Operator overloading 

	public static bool operator >(Item X, Item Y)
	{
		if (X == null && Y == null)
		{
			return false;
		}
		if (X == null)
		{
			return false; //true?
		}
		if (Y == null)
		{
			return true; //false? 

		}

		return X.itemPrice > Y.itemPrice;
	}

	public static bool operator <(Item X, Item Y)
	{
		if (X == null && Y == null)
		{
			return false;
		}
		if (X == null)
		{
			return true; //false?
		}
		if (Y == null)
		{
			return false; //true? 

		}

		return X.itemPrice < Y.itemPrice;
	} 
}

 

Populate some value to the collection


Item[] items = { new Item { itemName="Item1", itemPrice=10 },
                 new Item { itemName="Item2", itemPrice=20 },
                 new Item { itemName="Item3", itemPrice=30 }, 
                 new Item { itemName="Item4", itemPrice=40 } };

Get the Minimum number greater than a certain value OR Maximum number lesser than a certain value


//get the minimum valued item = Item1
int min = items.Min().itemPrice;//get the min valued item greater than the 2nd item = Item3
int min = items.Where(p => p > items[1]).DefaultIfEmpty().Min().itemPrice);
//get the maximum valued item = Item4
int min = items.Max().itemPrice;

//get the max valued item less than the 3rd item = Item2
int min = items.Where(p => p < items[2]).DefaultIfEmpty().Max().itemPrice);

 

Similarly, we can also get the element at each index


Item secondLowest = numbers.OrderBy(num => num).ElementAt(1);
Item secondHighest = numbers.OrderBy(num => num).Reverse().ElementAt(1);

Advertisements

Validate a String to be in Guid Format in .net C#

Initially, I was using a wrong mechanism to validate a string to be in GUID format. I was doing the following:

string wrongString = String.Empty;
bool IsCorrectGuid = false;
try
{
    Guid guid = new Guid(wrongString);
    IsCorrectGuid = true;
}
catch(FormatException){}

However, try-catch is an expensive process so, if you have huge no. strings to validate and most of them will not be a Guid then, this is a very bad way of validation.

The correct way is to use Regex, and if you are working on .Net 4.0 or higher then, you can also use the Guid.TryParse method to achieve the same goal. Following I have demonstrated to validate the string in both ways.

Guid.TryParse

string correctString = Guid.NewGuid().ToString();
Guid guid;
bool guidResTrue = Guid.TryParse(correctString, out guid);

Regex

string correctString = Guid.NewGuid().ToString();

//returns true for correct format, case in-sensitive
Regex isGuid = new Regex(@"^(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}$", RegexOptions.Compiled);
bool guidResTrue = isGuid.IsMatch(correctString.ToUpper());

Of course, Guid.TryParse should be the preferred way of doing it if, you’re using .Net 4.0 or higher.

Split a String to Array of Strings and Include the Delimiters using .NET C#

To also get the delimiter of the string after the split we’ll have to use Regex.Split. Look at the following code:
string input = "SomeText,SomeText,SomeText,SomeText,SomeText,SomeText"; 
string pattern = "(,)";
string[] substrings = Regex.Split(input, pattern);

OUTPUT
SomeText
,
SomeText
,
SomeText
,
SomeText
,
SomeText
,
SomeText

NOTE: If you remove the parentheses from the pattern, using just “,”, the delimiters will not be preserved.

You can get more info about Regex.Split here

Associate Tooltip with WinForm Controls C#

There’s no direct property like ToolTip is available in WinForm, so you have to create an instance of the ToolTip class and assign captions to the various controls of the form using the same object.

private void Form1_Load(object sender, EventArgs e)
{
         // Create the ToolTip and associate with the Form container.
         ToolTip toolTip = new ToolTip();

         // Set up the delays for the ToolTip.
         toolTip.AutoPopDelay = 5000;
         toolTip.InitialDelay = 1000;
         toolTip.ReshowDelay = 500;
         // Force the ToolTip text to be displayed whether or not the form is active.
         toolTip.ShowAlways = true;

         // Set up the ToolTip text for the Button and Checkbox.
         toolTip.SetToolTip(this.button1, "My button1");
         toolTip.SetToolTip(this.checkBox1, "My checkBox1");
}

Get the Current Screen Size for WinForms C#

We’re gonna use the .net Screen class here. There are two aspects here.

Full Screen Size

int screenWidth = Screen.PrimaryScreen.Bounds.Width;
int screenHeight = Screen.PrimaryScreen.Bounds.Height;

Available Screen Size

int screenWidth = Screen.PrimaryScreen.WorkingArea.Width;
int screenHeight = Screen.PrimaryScreen.WorkingArea.Height; 

Stop/Prevent Browser from Caching the current Page

protected void StopPageCaching()
{
    HttpContext.Current.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
    HttpContext.Current.Response.Cache.SetValidUntilExpires(false);
    HttpContext.Current.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
    HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
    HttpContext.Current.Response.Cache.SetNoStore();
}

Unrecognized attribute ‘targetFramework’ error is encountered for Asp.Net 4.0 site while Deploying it to the IIS or GoDaddy

This error is usually thrown when you try to deploy a Asp.Net 4.0 to IIS whose App Pool is targeting the .Net 2.0. You can confirm that by checking the last line of your error page. This is where running the .net version is displayed.

To resolve it, just do the following

For IIS

Make sure .Net 4.0 is registered in IIS. To do that run the aspnet_regiis.exe tool from the command prompt having administrative rights.
The tool is located at C:\Windows\Microsoft.NET\Framework64\v4.0.30319.

Now in the command prompt run the command aspnet_regiis.exe -iru.

We’re using iru because it Installs this version of ASP.NET. If there are any existing applications that uses ASP.NET, it will not change IIS configuration to use this version. More Info

Next open IIS Manager. Go to your sites app pool. Select Basic Settings and change the framework from 2.0 to 4.0.

For GoDaddy

For GoDaddy, you have to select from the menu bar, More => IIS Management. There at the top you’ll see your sites current .net version with an option to modify.

Select it and change the .Net version from 2.0 to 4.0.

Now here’s an issue. Even if you see your version as 4.0/4.5 still, I recommend you to change the version first to 2.0 and then again back to 4.0. This issue has arisen in the past that the GoDaddy IIS is showing the .Net Framework as 4.0 but somehow internally, it’s still pointing to 2.0. You can confirm the version of the .net environment by looking at the last line of the error page [highlighted above] Just remember to manually recycle the app pool after each version change.

That’s it. The IIS is now targeting the framework .net 4.0.

Difference between Covariance and Contravariance delegates in .NET

When you assign a method to a delegate, the method signature does not have to match the delegate exactly. This is called covariance and contravariance.

Covariance

Covariance makes it possible that a method has a return type that is more derived than that defined in the delegate.

public delegate TextWriter CovarianceDel();
public StreamWriter MethodStream() { return null; }
public StringWriter MethodString() { return null; }
CovarianceDel del;
del = MethodStream;
del = MethodString;

Because both StreamWriter and StringWriter inherit from TextWriter, you can use the CovarianceDel with both methods. However, the other way round is not possible.

Contravariance

Contravariance permits a method that has parameter types that are less derived than those in the delegate type.

void DoSomething(TextWriter tw) { }
public delegate void ContravarianceDel(StreamWriter tw);
ContravarianceDel del = DoSomething;

The method DoSomething takes TextWriter as its parameter. Since, StreamWriter is derived from TextWriter, we can also pass the object of StreamWriter to the method DoSomething through this delegate instead of TextWriter.

More Info:- http://blogs.msdn.com/b/ericlippert/archive/tags/covariance+and+contravariance/

Could not load file or assembly or one of its dependencies. Operation is not supported. (Exception from HRESULT: 0x80131515)

You may have encounter this error while installing a Windows Service or loading a project in Visual Studio. If the file that you’re installing or loading has been downloaded from the internet in the zip format then there’s an easy fix.

Just go back to the ZIP file you downloaded, select properties, then “unblock” the content.


Then extract the contents and rerun it.  Everything should work fine.