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);

Saturday, December 25, 2010

Start New Thread

From http://www.csharp-examples.net/create-new-thread/


Thread thread = new Thread(new ThreadStart(WorkThreadFunction));
thread.Start();

public void WorkThreadFunction()
{
// do stuff
}

Friday, December 24, 2010

Open Port Windows 7

As an Administrator:
Windows Firewall with Advanced Security -> Inbound Rules -> New Rules -> Port -> Complete Wizard

Wednesday, December 22, 2010

KeyValuePair vs Dictionary

KeyValuePair or Dictionary for a method that should return a collection of key and values?

Apparently KeyValuePair isn't really intended to be used on its own outside of a Dictionary.

If we look at the signature of both types we'll find that


public struct KeyValuePair <TKey, TValue>
{
}


and for Dictionary:


public class Dictionary<TKey, TValue> : ... IEnumerable<KeyValuePair<TKey, TValue>> ...
{
}


so it's not a matter of KeyValuePair vs Dictionary but really IEnumerable<KeyValuePair<TKey, TValue>> vs Dictionary<TKey, TValue> and
since a dictionary is an IEnumerable<KeyValuePair<TKey, TValue>> then the answer is easy: use a dictionary.

Sunday, December 19, 2010

Install .NET Windows Service - installutil

1. Open the visual studio 2008 command prompt (or the 2010 version) as an administrator
2. Change to the directory where the binaries are deployed
3. Execute the following: installutil MyService.exe

> cd C:\Projects\Builds\MyService
> installutil MyService.exe
> exit

2.- Second Approach

1. open a command prompt as administrator
2. change to the .NET Framwork 2.0 directory
3. execute installutil specifying the full service path

> cd C:\Windows\Microsoft.NET\Framework64\v2.0.50727
> installutil C:\Projects\Builds\MyService\MyService.exe
> exit

If everything was ok, the service is installed and available in the service manager (service.msc)



Monday, December 6, 2010

Rename column

Script:


IF EXISTS (select 1 from sys.objects where name = 'Users') begin -- maybe this IF is redundant.
if exists ( select 1 from sys.tables t
join sys.columns c on c.object_id = t.object_id
where t.name = 'Users' and c.name = 'UserName') begin
exec sp_RENAME 'Users.UserName', 'LoginName' , 'COLUMN'
end
end
GO

Sunday, December 5, 2010

New NOT NULL column on existing table

Script:


if not exists ( select 1 from sys.tables t
join sys.columns c on c.object_id = t.object_id
where t.name = 'PushInterfaceRESTLog' and c.name = 'UserType')
BEGIN
ALTER TABLE PushInterfaceRESTLog
ADD UserType varchar(100) NULL
END
GO

if exists ( select 1 from sys.tables t
join sys.columns c on c.object_id = t.object_id
where t.name = 'PushInterfaceRESTLog' and c.name = 'UserType')
BEGIN
UPDATE PushInterfaceRESTLog SET UserType = 'Vendor'

ALTER TABLE PushInterfaceRESTLog
ALTER COLUMN UserType varchar(100) NOT NULL
END
GO

Saturday, December 4, 2010

Extension Methods

Where records is an IEnumerable of CustomRecord

List<int> numbers = records.GetNumbers();

In a public static class:

public static class DataExtension
{
    public static List<int> GetNumbers(this IEnumerable<CustomRecord> records)
    {
        var numbers = new List<int>();

        foreach (var record in records) {
            numbers.Add(record.Number);
        }

        return numbers;
    }
}

Tuesday, November 30, 2010

TryParse

We want result to be set to the value of someObject.SomeProperty, and in any other case to default to 99.


int result = 0;
int max = int.TryParse(someObject.SomeProperty, out result) ? result : 99;

equivalent to

int result = 0;
int max = 99;

if(int.TryParse(someObject.SomeProperty, out result) == true)
{
max = result;
}
else // ok, maybe this 'else' is redundant
{
max = 99;
}

Friday, November 12, 2010

Throw exception

When using throw after catching and handling an exception:


private void SaveRecord(Record record)
{
try
{
var db = new NorthwindDB();
db.SaveRecordInfo(null, record.ClientID, DateTime.Now).Execute(); // let's say this is the line 45
}
catch (Exception ex)
{
_logger.Error("Failed saving db record", ex);
throw;
}
}


We will get something like the following:


System.Transactions.TransactionManagerCommunicationException: blah blah blah ...
at SampleApp.DataAccess.Repository.SaveRecord(Record record) in C:\Projects\SampleApp.DataAccess\Repository.cs:line 45


Which is what we want, in this example we want to log the exception and then re-throw it without losing the stack trace info (and the exact line of code where the exception occurred)

Friday, November 5, 2010

Subsonic ActiveRecord CreatedBy, ModifiedBy, etc

On ActiveRecord.tt


public void Update(IDataProvider provider){
...
}


removed the following block codes:


if(tbl.Columns.Any(x=>x.Name=="ModifiedBy")){
if(String.IsNullOrEmpty(this.ModifiedBy))
this.ModifiedBy=Environment.UserName;
}



if(tbl.Columns.Any(x=>x.Name=="ModifiedOn")){
this.ModifiedOn=DateTime.Now;
}


after that the method should look like the one below:


public void Update(IDataProvider provider) {
if(this._dirtyColumns.Count>0)
_repo.Update(this,provider);
OnSaved();
}


Similarly remove the rest of the Update() methods. Do the same with the Add() methods.

Tuesday, October 26, 2010

FILESTREAM feature doesn't have file system access enabled.

Run this:


sp_configure 'filestream access level',2


and then this:


RECONFIGURE WITH OVERRIDE


in the database in question (not in the master db)

I also enable these two options as well (but don't know if they have to be enabled):



Source: http://blogs.msdn.com/b/chrissk/archive/2009/02/08/example-using-transactional-replication-with-filestreams-in-sql-2008.aspx

Thursday, October 21, 2010

Add Column the safe way


if not exists ( select 1 from sys.tables t
join sys.columns c on c.object_id = t.object_id
where t.name = 'Users' and c.name = 'IsAdmin')
BEGIN
ALTER TABLE Users
ADD IsAdmin bit NOT NULL
END
GO

Tuesday, October 12, 2010

jeditable maxlength

In jquery.jeditable.js add:
if (settings.maxlength) { input.attr('maxlength', settings.maxlength); }

right below:
if (settings.height != 'none') { input.height(settings.height); }



Then set maxlength
$('.loremipsum').editable('http://www.example.com/save.php', {
    ...
    maxlength: 20
});

reference: http://www.appelsiini.net/projects/jeditable (user Sasi's comment)

Friday, October 8, 2010

Sintax

From:
http://alexgorbatchev.com/SyntaxHighlighter/integration.html
http://www.cyberack.com/2007/07/adding-syntax-highlighter-to-blogger.html

Adding to the pre tag the following: class="brush: sql;"

select * from users where 1 = 1


int i = 0;


function helloSyntaxHighlighter()
{
return "hi!";
}

http://alexgorbatchev.com/SyntaxHighlighter/

Thursday, October 7, 2010

FILESTREAM feature is disabled

Msg 5591, Level 16, State 1, Line 2
FILESTREAM feature is disabled.

In SQL Server Configuration Manager

Wednesday, October 6, 2010

The subscription(s) have been marked inactive and must be reinitialized

The subscription(s) have been marked inactive and must be reinitialized. NoSync subscriptions will need to be dropped and recreated. (Source: MSSQLServer, Error number: 21074)

At publisher:

use distribution
go

update MSSubscriptions set [status] = 2

To review pending commands to replicate. At plusblisher:

use distribution
go

exec sp_browsereplcmds

Tuesday, October 5, 2010

Binding settings (long messages)

One of the service's operations sends a pretty long response message, using the defaults settings will result in an exception.

To fix this, update maxBufferSize and maxReceivedMessageSize to a greater value (they both default to 65536) in the client.



...
< name="longHttpMessages" maxbuffersize="2147483647" maxreceivedmessagesize="2147483647">
...

end

Friday, September 10, 2010

Remove JSON object from array/list

JavaScript



Code

// list of objects where the 'number' property is unique
var _numbers = [{number: 4589, name: "lorem"}, {number: 2554, name: "ipsum"}, {number: 9880, name: "siamet"}];

// find index for the object we want to remove from the list
var idx = -1;
var num = 9880;
for (var i = 0; i < _numbers.length; i++) {
if (num == _numbers[i].number) {
idx = i;
break;
}
}
// remove object from the list
if (idx != -1)
_numbers.splice(idx, 1);

Tuesday, September 7, 2010

Helper method: Markup + Code behind

Markup (aspx, asmx)



Code behind (C#)



end

Wednesday, September 1, 2010

String.Format + DataBinder aspx

String.Format (asp.net aspx page)

Tuesday, August 31, 2010

jQuery checkbox state

Markup (html)

< id="chkMatchedSets" type="checkbox">

Javascript (jQuery)

var ischecked = $("#chkMatchedSets").is(':checked');

markup:



javascript:



firebug:



end

Saturday, August 21, 2010

SQL GUID NEWID

Random name

SELECT 'Jon ' + left(CAST(NEWID() as varchar(max)), 8) AS RandomName

Wednesday, June 23, 2010

Create a random number

This will create a 10-digits random number



public static string CreateRandomNumber()
{
return GenerateRandomPhoneNumber(3);
}

private static string GenerateRandomPhoneNumber(int seed)
{
string phoneNumber = String.Empty;

Random random = new Random((int)(DateTime.Now.Ticks % 5000000000 + seed));

phoneNumber += random.Next(1, 10).ToString();

for (int i = 0; i < 9; i++)
{
phoneNumber += random.Next(0, 10).ToString();
}

return phoneNumber;
}

Tuesday, June 22, 2010

Specify instance in Select statement

Something like:

SELECT * FROM [WINXP\CORP].[Northwind].[dbo].Employees

cannot be done. So what we can do is create something called a "linked server" like this:

select * from sys.servers

EXEC sp_addlinkedserver @server='CORP'
, @srvproduct=''
, @provider='SQLOLEDB'
, @datasrc='WINXP\CORP'

select * from sys.servers

and now we can perform a select:

SELECT * FROM CORP.Northwind.dbo.Eployees

Note that the CORP in @datasrc is the instance name in the WINXP server. If you want to access the default instance you only need to specify the server name.

To delete the linked server use:

exec sp_dropserver 'CORP'

Here are another examples:


EXEC sp_addlinkedserver @server='SQLV02' -- the "friendly name will use in our queries"
, @srvproduct=''
, @provider='SQLOLEDB'
, @datasrc='SQL-V02' -- the actual name of the server

EXEC sp_addlinkedserver @server='INC' -- same as above
, @srvproduct=''
, @provider='SQLOLEDB'
, @datasrc='SQL-V01\Inc' -- the server name and the db instance (Inc in this example)


Monday, June 7, 2010

Unique Index


-- To create a unique index:

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'IX_ClientsTable_ClientID_Name')

BEGIN

-- ClientID and Name will be unique per row

CREATE UNIQUE INDEX IX_ClientsTable_ClientID_Name

ON ClientsTable (ClientID, [Name])

END

GO