Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Sunday, May 12, 2013

Single vs SingleOrDefault

If no element is found Single throws an exception, but SingleOrDefault returns null.

Both methods throw an exception if there's more than one element in the sequence.

For example if there's more than one element SingleOrDefault() throws something like the following: System.InvalidOperationException: Sequence contains more than one element

NOTE: FirstOrDefault should be used when we have more than one element in the sequence and want only one element from it (in this case -as the name indicates- the first one) FirstOrDefault returns null when founds nothing (similar to SingleOrDefault).

public Transaction GetTransaction(Transaction transaction) {
    var transactions = GetTransactions(from: transaction.Date, to: transaction.Date);
    return transactions != null 
        ? transactions.Where(t => t.ID == transaction.ID).FirstOrDefault()
        : null;
}

Thursday, June 7, 2012

Create CLR Assembly SQL Function

Create a cs code file with the desired functionality. Example:
using System;
using System.Data;
using Microsoft.SqlServer.Server;
using System.Data.SqlTypes;

public class TimeZoneHelper
{
    [Microsoft.SqlServer.Server.SqlFunction]
    public static DateTime MountainToUtc(DateTime mountainDateTime)
    {
         TimeZoneInfo zone = TimeZoneInfo.FindSystemTimeZoneById("Mountain Standard Time"); // "Mountain Standard Time" it's the ID regardless of daylight saving time (i.e. no matters if right now is daylight saving time, the ID name remains the same)

         DateTime utcTime = TimeZoneInfo.ConvertTimeToUtc(mountainDateTime, zone); // it automatically takes care of daylight saving time

         return utcTime;
    }
      
    [Microsoft.SqlServer.Server.SqlFunction]
    public static DateTime PacificToUtc(DateTime pacificDateTime)
    {
         TimeZoneInfo zone = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time"); // "Pacific Standard Time" it's the ID regardless of daylight saving time (i.e. no matters if right now is daylight saving time, the ID name remains the same)

         DateTime utcTime = TimeZoneInfo.ConvertTimeToUtc(pacificDateTime, zone); // it automatically takes care of daylight saving time

         return utcTime;
    }
}
Save the file as TimeZoneHelper.cs
Open the Visual Studio 2008 Command Prompt (I also tried the 2010 version but it didnt work) and run the following:
csc /target:library C:\Users\jon.connor\Downloads\TimeZoneHelper.cs
This will create a TimeZoneHelper.dll in the same directory where the source file is in.
In SQL Server run the following to enable CLR code to run:
sp_configure 'clr enabled', 1
GO
RECONFIGURE
GO

ALTER DATABASE Northwind SET TRUSTWORTHY ON;
GO
You also have to grant permissions to a SQL Server login:
GRANT UNSAFE ASSEMBLY TO some_user;
GO
Now you can create the assembly in the Northwind database
CREATE ASSEMBLY TimeZoneHelperAssembly 
FROM 'C:\Users\jon.connor\Downloads\TimeZoneHelper.dll' 
WITH PERMISSION_SET = UNSAFE
GO
Finally create functions based on the assembly methods.
CREATE FUNCTION dbo.MountainToUTC(@mountainDateTime datetime) 
RETURNS datetime 
AS EXTERNAL NAME 
[TimeZoneHelperAssembly].[TimeZoneHelper].[MountainToUtc]
GO

CREATE FUNCTION dbo.PacificToUTC(@pacificDateTime datetime) 
RETURNS datetime 
AS EXTERNAL NAME 
[TimeZoneHelperAssembly].[TimeZoneHelper].[PacificToUtc]
GO

And now you can start using these functions as you would normally do:
select dbo.MountainToUTC('2012-04-13 16:00:00'), 
       dbo.PacificToUTC('2012-04-13 16:00:00')


Thanks to http://goo.gl/W4u42

Monday, April 16, 2012

WCF MSMQ Message Retries

Using this settings (maxRetryCycles="50", retryCycleDelay="00:01:30", receiveRetryCount="0") it will retry the message 50 times with a delay of 90 seconds between every retry.

< binding name="DasBinding"
exactlyOnce="true"
durable="true"
maxRetryCycles="50"
retryCycleDelay="00:01:30"
receiveRetryCount="0"
...

In this page (http://msdn.microsoft.com/en-us/library/ms731380.aspx) there's more information about the settings for the MSMQ binding in WCF. Here I list a few of them and their descriptions:

maxRetryCycles

An integer that indicates the number of retry cycles used by the poison-message detection feature. A message becomes a poison message when it fails all delivery attempts of all cycles. The default is 3. For more information, see MaxRetryCycles.

retryCycleDelay

A TimeSpan value that specifies the time delay between retry cycles when attempting to deliver a message that could not be delivered immediately. The value defines only the minimum wait time because actual wait time can be longer. The default value is 00:10:00. For more information, see RetryCycleDelay.

receiveRetryCount

An integer that specifies the maximum number of times the queue manager should attempt to send a message before transferring it to the retry queue. The maximum number of immediate delivery attempts. The default is 5.

Monday, February 27, 2012

Log4net Exclude messages from log

In the config file add a StringMatchFilter with the string to discard/filter.

Example:


...










...

Friday, January 20, 2012

Linq NOT IN clause

To emulate a SQL "NOT IN" clause like the following:

SELECT * FROM Clients WHERE ClientID NOT IN (select ClientID from AssignedClients)

We can do the following in Linq:

IEnumerable< Client > assignedClients = _repo.GetAssignedClients();
IEnumerable< Client > allClients = _repo.GetAllClients();
IEnumerable< Client > availableClients = from c in allClients
where !(assignedClients.Any(a => a.ClientID == c.ClientID))
select c;

Where Client has the following definition:

public class Client {
public int ClientID { get; set; }
public string ClientName { get; set; }
public bool IsActive { get; set; }
}


Another example:
var clientids = new int[] {1, 2, 3}; // IEnumerable of integers
var records = new Record[] { new Record{ClientId = 1}, new Record{ClientId = 9}, new Record{ClientId = 8}, new Record{ClientId = 2} };

var theRest = from r in records
              where !(clientids.Any(id => id == r.ClientId))
              select r;

And this is another way of obtaining the same
var theRest = records.Where(r => !clientids.Contains(r.ClientId));

They both will return the records whose ClientId is not in the list of clientids.

Wednesday, January 4, 2012

MapPath ASP.NET

MapPath sometimes refers to the directory the .NET solution is in and not the website and sometimes it does refers to the website itself. If we add the tilde character (~) it will return the website's path.

For example I have my solution at C:\Projects\src\MeinApp and inside that directory is the website (C:\Projects\src\MeinApp\WebService).
MapPath("/Schemas") will return 'C:\Projects\src\MeinApp\Schemas\' but
MapPath("~/Schemas") will return 'C:\Projects\src\MeinApp\WebService\Schemas'
which is what we finally want.

string dir = HostingEnvironment.MapPath("~/Schemas");

Tuesday, September 27, 2011

Convert IEnumerable of String to Int

Code


// ids is an IEnumerable of String

var integers = ids.Select(x => int.Parse(x));

// to convert and sort at the same time:

var sortedIds = ids.Select(x => int.Parse(x)).OrderBy(x => x));

Sunday, June 19, 2011

Get Url - Protocol/Schema, Domain and (if applicable) Port

From goo.gl/WfuVV and goo.gl/AYp9v


Request.Url.GetLeftPart(UriPartial.Authority)

It will return a string like the following

"http://localhost:51528"

Requesr.Url properties and sample values:

Request.Url
{http://localhost:51528/Account/SendForgotPasswordEmail?email=jon@connor.com}
AbsolutePath: "/Account/SendForgotPasswordEmail"
AbsoluteUri: "http://localhost:51528/Account/SendForgotPasswordEmail?email=jon@connor.com"
Authority: "localhost:51528"
DnsSafeHost: "localhost"
Fragment: ""
Host: "localhost"
HostNameType: Dns
IsAbsoluteUri: true
IsDefaultPort: false
IsFile: false
IsLoopback: true
IsUnc: false
LocalPath: "/Account/SendForgotPasswordEmail"
OriginalString: "http://localhost:51528/Account/SendForgotPasswordEmail?email=jon@connor.com"
PathAndQuery: "/Account/SendForgotPasswordEmail?email=jon@connor.com"
Port: 51528
Query: "?email=jon@connor.com"
Scheme: "http"
Segments: {string[3]}
UserEscaped: false
UserInfo: ""

Wednesday, April 13, 2011

Regex Email

This is the one that jquery.validate.js uses:

string emailRegex = @"^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$";

Thursday, March 17, 2011

ASPNET State Database

You will need to run the following commands using a db login that has Create Database permission.
(command prompt)

cd C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727

aspnet_regsql -S serverName -U myUser -P p4zz#w0rd -ssadd -sstype c -d MyASPState

where

-S server name
-U user (database server login)
-P user's password
-d database name

Sunday, February 20, 2011

Retry Logic (Recursively)

Uploading a file to a webserver.

private string UploadFile(string name, string token, bool retry = true)
{
string publicUrl = null;

try
{
bool success = _service.Save(name, token, out publicUrl);
}
catch (WebException ex)
{
// Server will return a 401 (Unauthorized) response when the authorization token has expired.
// So will create a new token and retry this operation.
if (ex.Response != null && (ex.Response as HttpWebResponse).StatusCode == HttpStatusCode.Unauthorized)
{
if (retry)
{
_logger.WarnFormat("Server returned 401 (Unauthorized), requesting new token and retrying operation...");

token = UpdateToken();

publicUrl = UploadFile(name, token retry: false); // try only one more time.
}
else
_logger.ErrorFormat("Server returned 401 (Unauthorized) again. File {0} could not be uploaded, please process it manually.", name);
}
else
throw ex;
}

return publicUrl;
}

Wednesday, February 9, 2011

Singleton C#

Non thread-safe

public class MyStorage
{
private static MyStorage instance;

public static MyStorage Instance
{
get {
if (instance == null)
instance = new MyStorage();

return instance;
}
}

private MyStorage()
{
// do stuff
InitStuff();

bool result;
_overwrite = bool.TryParse( ConfigurationManager.AppSettings["Overwrite"], out result) ? result : false;
}

...
}

Friday, February 4, 2011

FileInfo Get File Bytes

1. approach

FileStream fs = myfileInfo.OpenRead();
int bytesCount =(int)fs.Length;
byte[] bytes = new byte[bytesCount];
int bytesRead = fs.Read(bytes, 0, bytesCount);
fs.Close();

2. approach

byte[] bytes = System.IO.File.ReadAllBytes(myfileInfo.FullName);

Tuesday, January 25, 2011

Time Zones Pacific UTC

Convert from Pacific Time to UTC/GMT

private DateTime ToUtc(DateTime pacificDateTime)
{
TimeZoneInfo pacificZone = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
// "Pacific Standard Time" it's the ID regardless of daylight saving time (i.e. no matters if right now is daylight saving time, the ID name remains the same)

DateTime utcTime = TimeZoneInfo.ConvertTimeToUtc(pacificDateTime, pacificZone);
// it automatically takes care of daylight saving time

return utcTime;
}

Convert from UTC/GMT to Mountain Time

private DateTime ToMountain(DateTime utcDate)
{
TimeZoneInfo mountainZone = TimeZoneInfo.FindSystemTimeZoneById("Mountain Standard Time");
// "Mountain Standard Time" it's the ID regardless of daylight saving time (i.e. no matters if right now is daylight saving time, the ID name remains the same)

DateTime mountainTime = TimeZoneInfo.ConvertTimeFromUtc(utcDate, mountainZone);
// it automatically takes care of daylight saving time

return mountainTime;
}

Time zone converter

private DateTime ToMountain(DateTime datetime, string originalTimeZoneID)
{
// The strings requested by the method are the ID regardless of daylight saving time (i.e. no matter if right now is daylight saving time, the ID name remains the same)
return TimeZoneInfo.ConvertTimeBySystemTimeZoneId(datetime, originalTimeZoneID, "Mountain Standard Time");
}

Sunday, January 23, 2011

List< T> as XmlArray


[System.Xml.Serialization.XmlRoot(ElementName = "user")]
public class User
{
[System.Xml.Serialization.XmlElement(ElementName = "id")]
public string ID { get; set; }

[System.Xml.Serialization.XmlArray("logs")]
[System.Xml.Serialization.XmlArrayItem("log")]
public List< Log> Logs { get; set; }
}

public class Log
{
[System.Xml.Serialization.XmlElement(ElementName = "no")]
public int Number { get; set; }

[System.Xml.Serialization.XmlElement(ElementName = "level")]
public string LogLevel { get; set; }
}

We could then deserialize an xml like the following into a User object.


1344166


1
Info


2
Debug



Thursday, January 20, 2011

Regex


string number = "9813f";
string regexPattern = @"^\d{5}$";

if (!Regex.IsMatch(number, regexPattern))
{
errorMessage = "The number is invalid (not a 5-digit number).";
return false;
}

Monday, January 17, 2011

Cache Algorithm

For an integer value:

private int GetInteger(int uniqueID)
{
int integerv;

string key = String.Format("{0}_{1}", "SOMETHING", uniqueID);

object value = Cache.Get(key); // could be HttpContext.Current.Cache.Get

if (value != null) {
integerv = (int)value;
}
else {
integerv = _db.GetValueFromDb(uniqueID);
Cache.Add(key, integerv); // could be HttpContext.Current.Cache.Add
}

return integerv;
}

Thursday, January 6, 2011

MD5 Hash

To generate an MD5 like 9adff06850bedeace9d0c6ebfe7ce507

private byte[] GetData(string filePath, string fileName, out string md5)
{
string path = Path.Combine(filePath, fileName);

byte[] bytes = System.IO.File.ReadAllBytes(path);

md5 = GetHash(bytes);

return bytes;
}

private string GetHash(byte[] data)
{
byte[] bytes = System.Security.Cryptography.MD5.Create().ComputeHash(data);

return StringifyMD5(bytes); // This method will return something like 9adff06850bedeace9d0c6ebfe7ce507
}

private string StringifyMD5(IEnumerable< byte> bytes)
{
var result = new StringBuilder();

foreach (byte b in bytes)
{
result.AppendFormat("{0:x2}", b);
}

return result.ToString();
}

we can also use it to generate a hash based on a string, for example, a filename:

string fileName = "some_file_name.xml";
string hash = GetHash(System.Text.Encoding.UTF8.GetBytes(fileName));

Wednesday, January 5, 2011

Print HTTP Response Headers

Key code:

using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
foreach (string key in response.Headers.AllKeys)
{
Console.WriteLine(String.Format("{0}: {1}", key, response.Headers[key]));
}
}

Complete code:


HttpWebRequest request = WebRequest.Create(_url) as HttpWebRequest;

request.Method = "GET";
request.Headers.Add("AuthToken", _token);
request.ContentLength = 0;

using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
Console.WriteLine("{0} {1}", (int)response.StatusCode, response.StatusCode);

foreach (string key in response.Headers.AllKeys)
{
Console.WriteLine(String.Format("{0}: {1}", key, response.Headers[key]));
}
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
Console.WriteLine("\n{0} ", reader.ReadToEnd());
}
}

Friday, December 31, 2010

Linq queries vs Lambda queries


foreach (var id in _clientIds)
{
items.AddRange(
clients.Where(x => x.ClientID == id)
);
}

// rest of the clients
items.AddRange(
clients.Where(x => !_clientIds.Contains(x.ClientID))
);

VS


foreach (var id in _clientIds)
{
items.AddRange(from c in clients
where c.ClientID == id
select c);
}

// rest of the clients
items.AddRange(from c in clients
where !_clientIds.Contains(c.ClientID)
select c);