What Was I Thinking?

Follies & Foils of .NET Development
posts - 85 , comments - 251 , trackbacks - 0

Wednesday, April 16, 2014

Reinstalling NuGet Packages from the Package Manager Console

Reinstall all packages in ALL PROJECTS of the current solution:

Update-Package -Reinstall

 

Reinstall all packages in SPECIFIC PROJECT of the current solution:

Update-Package -ProjectName 'ProjectNameGoesHere' -Reinstall

Posted On Wednesday, April 16, 2014 1:27 PM | Comments (0) |

Thursday, February 6, 2014

Resharper: Add “Locate in Solution Explorer” to the Code Window Tab Context Menu

I Love Resharper’s Find In Solution Explorer command.  It locates the currently active code file in the solution explorer.  Using my keyboard layout I can activate it using Shift+Alt+L, but most times I prefer to select it from the context menu of my code window tab, you know, this thing:

image

Here’s how I added it:

  1. From the Tools menu select Customize
  2. On the Customize dialog click the Commands tab
  3. Select the Context Menu Radio button
  4. In the Context Menu drop down, scroll to the bottom and locate Other Context Menus | Easy MDI Document Window
  5. Scroll to the bottom of the list and click the Add Command button
  6. In the Add Command dialog, select Resharper from the Categories list.
  7. From the Commands list, select Resharper_LocateInSolutionExplorer
  8. SNAGHTML606d5b5
  9. Click Ok.
  10. Click the Move Up / Move Down buttons to place the command where you want it within the context menu.
  11. Optional – If you want a separator line above the command, with the command selected click  the Modify Selection button and check Begin a Group
  12. Click the Close  button.

That’s it!  Now your active source file is one click away!

Posted On Thursday, February 6, 2014 1:52 AM | Comments (0) |

Saturday, February 1, 2014

Invoking IDbSet<T>.FirstOrDefault(predicate) using reflection

 

Assuming you have a data context with a property of IDBSet<Person> and person has a property called Id, you can issue:

var person = context.PersonDbSet.FirstOrDefault(i=>i.Id=3);

here’s how you do it with reflection:

Assuming you have a reference to your data set, called dbset

Begin with defining the predicate (the where statement)

ParameterExpression parameter = Expression.Parameter(entityType, "Id");
MemberExpression property = Expression.Property(parameter, 3);
ConstantExpression rightSide = Expression.Constant(refId);
BinaryExpression operation = Expression.Equal(property, rightSide);
Type delegateType = typeof (Func<,>).MakeGenericType(entityType, typeof (bool));
LambdaExpression predicate  = Expression.Lambda(delegateType, operation, parameter);

 

Now a reference to the extension method:

    var method = typeof (System.Linq.Queryable).GetMethods(BindingFlags.Static | BindingFlags.Public)
                .FirstOrDefault(m => m.Name == "FirstOrDefault" && m.GetParameters().Count() == 2);

   MethodInfo genericMethod = method.MakeGenericMethod(new[] { entityType });            

 

Finally execute the method:

object retVal = genericMethod.Invoke(null, new object[] {dbSet, predicate});

Posted On Saturday, February 1, 2014 3:15 PM | Comments (0) |

Tuesday, January 22, 2013

A consolidated View of Broker Service Queues

USE [CatalogWithMessageBroker]

GO

select q.name as QueueName, p.rows as MsgCount, case sq.is_receive_enabled when 0 then 'Disabled' else 'Enabled' end as QueueEnabled
from sys.objects as o
join sys.partitions as p on p.object_id = o.object_id
join sys.objects as q on o.parent_object_id = q.object_id
join sys.service_queues sq on sq.name = q.name
where p.index_id = 1

Posted On Tuesday, January 22, 2013 9:14 AM | Comments (0) |

Friday, December 7, 2012

Troubleshooting Blocked Transaction in SQL Server

While troubleshooting a blocked transaction issue recently, I found this code online.  My apologies in not citing its source, but its lost in my browse history some where.

 

While the transaction is executing and blocked, open a connection to the database containing the transaction and run the following to return both the SQL statement blocked (the Victim), as well as the statement that’s causing the block (the Culprit)

 

--

prepare a table so that we can filter out sp_who2 results

DECLARE @who TABLE(BlockedId INT,

Status VARCHAR(MAX),

LOGIN VARCHAR(MAX),

                   HostName VARCHAR(MAX),

                   BlockedById VARCHAR(MAX),

                   DBName VARCHAR(MAX),

                   Command VARCHAR(MAX),

                   CPUTime INT,

                   DiskIO INT,

                   LastBatch VARCHAR(MAX),

                   ProgramName VARCHAR(MAX),

                   SPID_1 INT,

                   REQUESTID INT)

INSERT INTO @who EXEC sp_who2

--select the blocked and blocking queries (if any) as SQL text

SELECT

(

SELECT TEXT

FROM sys.dm_exec_sql_text(

(SELECT handle 

FROM (

SELECT CAST(sql_handle AS VARBINARY(128)) AS handle

FROM sys.sysprocesses WHERE spid = BlockedId

) query)

)

) AS 'Blocked Query (Victim)',

(

SELECT TEXT

FROM sys.dm_exec_sql_text(

(SELECT handle 

FROM (

SELECT CAST(sql_handle AS VARBINARY(128)) AS handle

FROM sys.sysprocesses WHERE spid = BlockedById

) query)

)

) AS 'Blocking Query (Culprit)'

FROM @who 

WHERE BlockedById != '  .'

Posted On Friday, December 7, 2012 4:45 PM | Comments (0) |

Monday, December 3, 2012

More useful Sql Server Serivce Broker Queries

SELECT 'Checking Broker Service Status...'
IF (select Top 1 is_broker_enabled from sys.databases where name = 'NWMESSAGE')=1
    SELECT ' Broker Service IS Enabled'  -- Should return a 1.
ELSE
    SELECT '** Broker Service IS DISABLED ***'
/* If Is_Broker_enabled returns 0, uncomment and run this code
ALTER DATABASE NWMESSAGE SET SINGLE_USER WITH ROLLBACK IMMEDIATE
GO
Alter Database NWMESSAGE Set enable_broker
GO
ALTER DATABASE NWDataChannel SET MULTI_USER
GO
*/


SELECT 'Checking For Disabled Queues....'
-- ensure the queues are enabled
--  0 indicates the queue is disabled.
Select '** Receive Queue Disabled: '+name from sys.service_queues where is_receive_enabled = 0
--select [name], is_receive_enabled from sys.service_queues;

/*If the queue is disabled, to enable it
alter queue QUEUENAME with status=on; – replace QUEUENAME with the name of your queue
*/

-- Get General information about the queues
--select * from sys.service_queues

-- Get the message counts in each queue
SELECT 'Checking Message Count for each Queue...'
select q.name, p.rows
from sys.objects as o
join sys.partitions as p on p.object_id = o.object_id
join sys.objects as q on o.parent_object_id = q.object_id
join sys.service_queues sq on sq.name = q.name
where p.index_id = 1


-- Ensure all the queue activiation sprocs are present
SELECT 'Checking for Activation Stored Procedures....'
SELECT  '** Missing Procedure:  '+q.name 
From sys.service_queues q
Where NOT Exists(Select * from sysobjects where xtype='p' and name='activation_'+q.name)
and q.activation_procedure is not null

DECLARE @sprocs Table (Name Varchar(2000))
Insert into @sprocs Values ('Echo')
Insert into @sprocs Values ('HTTP_POST')
Insert into @sprocs Values ('InitializeRecipients')
Insert into @sprocs Values ('sp_EnableRecipient')
Insert into @sprocs Values ('sp_ProcessReceivedMessage')
Insert into @sprocs Values ('sp_SendXmlMessage')

SELECT 'Checking for required stored procedures...'
SELECT  '** Missing Procedure:  '+s.name 
From @sprocs s
Where NOT Exists(Select * from sysobjects where xtype='p' and name=s.name)
GO
-- Check the services
Select 'Checking Recipient Message Services...'
Select '** Missing Message Service:' + r.RecipientName +'MessageService'
From Recipient r
Where not exists (Select * from sys.services s where  s.name  COLLATE SQL_Latin1_General_CP1_CI_AS= r.RecipientName+'MessageService')

DECLARE @svcs Table (Name Varchar(2000))
Insert into @svcs Values ('XmlMessageSendingService')

SELECT  '** Missing Service:  '+s.name 
From @svcs s
Where NOT Exists(Select * from sys.services where name=s.name COLLATE SQL_Latin1_General_CP1_CI_AS)
GO

/*** To Test a message send Run:
sp_SendXmlMessage  'TSQLTEST', 'CommerceEngine','<Root><Text>Test</Text></Root>'
*/

Select CAST(message_body as XML) as xml, * From XmlMessageSendingQueue

/*** clean out all queues
declare @handle uniqueidentifier

declare conv cursor for
  select conversation_handle from sys.conversation_endpoints

open conv
fetch next from conv into @handle

while @@FETCH_STATUS = 0
Begin
   END Conversation @handle with cleanup
   fetch next from conv into @handle
End

close conv
deallocate conv

***********************

Posted On Monday, December 3, 2012 4:50 PM | Comments (0) |

Wednesday, September 26, 2012

Convert VARCHAR() columns to NVARCHAR()

We recently underwent an upgrade that required us to change our database columns from varchar to NVarchar, to support unicode characters.

Digging through the internet, I found a base script which I modified to handle reserved word table names, and maintain the NULL/NotNull constraint of the columns.

 

I Ran this script

use NWOperationalContent – Your Catalog Name here

GO

SELECT 'ALTER TABLE ' + isnull(schema_name(syo.id), 'dbo') + '.[' +  syo.name +'] '
    + ' ALTER COLUMN [' + syc.name + '] NVARCHAR(' + case syc.length when -1 then 'MAX'
        ELSE convert(nvarchar(10),syc.length) end + ') '+
        case  syc.isnullable when 1 then ' NULL' ELSE ' NOT NULL' END +';'
   FROM sysobjects syo
   JOIN syscolumns syc ON
     syc.id = syo.id
   JOIN systypes syt ON
     syt.xtype = syc.xtype
   WHERE
     syt.name = 'varchar'
    and syo.xtype='U'

 

which produced a series of ALTER statements which I could then execute the tables.  In some cases I had to drop indexes, alter the tables, and re-create the indexes.  There might have been a better way to do that, but manually dropping them got the job done.

 

use NWMerchandisingContent
GO
ALTER TABLE Locale Drop Constraint PK_Locale
ALTER TABLE Country DROP CONSTRAINT PK_Country

GO
ALTER TABLE dbo.[Campaign]  ALTER COLUMN [ActorKey] NVARCHAR(200)  NOT NULL;
ALTER TABLE dbo.[BundleLocalization]  ALTER COLUMN [Locale] NVARCHAR(8)  NOT NULL;
ALTER TABLE dbo.[BundleLocalization]  ALTER COLUMN [UnitOfmeasure] NVARCHAR(200)  NULL;
ALTER TABLE dbo.[BundleLocalization]  ALTER COLUMN [ActorKey] NVARCHAR(200)  NOT NULL;
ALTER TABLE dbo.[BundleComponentLocalization]  ALTER COLUMN [Locale] NVARCHAR(8)  NOT NULL;
ALTER TABLE dbo.[BundleComponentLocalization]  ALTER COLUMN [Imperative] NVARCHAR(MAX)  NULL;
ALTER TABLE dbo.[BundleComponentLocalization]  ALTER COLUMN [Instructions] NVARCHAR(MAX)  NULL;
ALTER TABLE dbo.[BundleComponentLocalization]  ALTER COLUMN [ActorKey] NVARCHAR(200)  NOT NULL;
ALTER TABLE dbo.[BundleComponent]  ALTER COLUMN [ActorKey] NVARCHAR(200)  NOT NULL;
ALTER TABLE dbo.[Bundle]  ALTER COLUMN [ActorKey] NVARCHAR(200)  NOT NULL;
ALTER TABLE dbo.[Banner]  ALTER COLUMN [ActorKey] NVARCHAR(200)  NOT NULL;
ALTER TABLE dbo.[Video]  ALTER COLUMN [Link] NVARCHAR(512)  NOT NULL;
ALTER TABLE dbo.[Video]  ALTER COLUMN [ActorKey] NVARCHAR(200)  NOT NULL;
ALTER TABLE dbo.[ProductUsage]  ALTER COLUMN [VideoLink] NVARCHAR(512)  NOT NULL;
ALTER TABLE dbo.[ProductUsage]  ALTER COLUMN [ActorKey] NVARCHAR(200)  NOT NULL;
ALTER TABLE dbo.[Thumbnail]  ALTER COLUMN [ActorKey] NVARCHAR(200)  NOT NULL;
ALTER TABLE dbo.[SkuLocalization]  ALTER COLUMN [Locale] NVARCHAR(8)  NOT NULL;
ALTER TABLE dbo.[SkuLocalization]  ALTER COLUMN [UnitOfMeasure] NVARCHAR(150)  NOT NULL;
ALTER TABLE dbo.[SkuLocalization]  ALTER COLUMN [SwatchColor] NVARCHAR(50)  NOT NULL;

etc..

GO
ALTER TABLE Locale ADD CONSTRAINT PK_Locale PRIMARY KEY (LocaleId)
ALTER TABLE Country ADD CONSTRAINT PK_Country PRIMARY KEY (CountryId)

Note that this alter is non-destructive to the data.

 

Hope this helps.

Posted On Wednesday, September 26, 2012 6:46 PM | Comments (1) |

Thursday, September 6, 2012

Solved: Operation is not valid due to the current state of the object

We use public static methods decorated with [WebMethod] to support our Ajax Postbacks.

 

Recently, I received an error from a UI developing stating he was receiving the following error when attempting his post back:

{
  "Message": "Operation is not valid due to the current state of the object.",
  "StackTrace": "   at System.Web.Script.Serialization.ObjectConverter.ConvertDictionaryToObject(IDictionary`2 dictionary, Type type, JavaScriptSerializer serializer, Boolean throwOnError, Object& convertedObject)\r\n   at System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeInternal(Object o, Type type, JavaScriptSerializer serializer, Boolean throwOnError, Object& convertedObject)\r\n   at System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeMain(Object o, Type type, JavaScriptSerializer serializer, Boolean throwOnError, Object& convertedObject)\r\n   at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)\r\n   at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeDictionary(Int32 depth)\r\n   at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)\r\n   at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeDictionary(Int32 depth)\r\n   at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)\r\n   at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer)\r\n   at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit)\r\n   at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](String input)\r\n   at System.Web.Script.Services.RestHandler.GetRawParamsFromPostRequest(HttpContext context, JavaScriptSerializer serializer)\r\n   at System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData, HttpContext context)\r\n   at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)",
  "ExceptionType": "System.InvalidOperationException"
}

 

Goggling this error brought me little support.  All the results talked about increasing the aspnet:MaxJsonDeserializerMembers value to handle larger payloads.  Since 1) I’m not using the asp.net ajax model and 2) the payload is very small, this clearly was not the cause of my issue.

Here’s the payload the UI developer was sending to the endpoint:

{
  "FundingSource": {
    "__type": "XX.YY.Engine.Contract.Funding.EvidenceBasedFundingSource,  XX.YY.Engine.Contract",
    "MeansType": 13,
    "FundingMethodName": "LegalTender",
  },
  "AddToProfile": false,
  "ProfileNickName": "",
  "FundingAmount": 0
}

By tweaking the JSON I’ve found the culprit.

Apparently the default JSS Serializer used doesn’t like the assembly name in the __type value.  Removing the assembly portion of the type name resolved my issue.

{
"FundingSource": {
"__type": "XX.YY.Engine.Contract.Funding.EvidenceBasedFundingSource",
"MeansType": 13,
"FundingMethodName": "LegalTender",
},
"AddToProfile": false,
"ProfileNickName": "",
"FundingAmount": 0
}

Posted On Thursday, September 6, 2012 2:05 PM | Comments (0) |

Thursday, April 26, 2012

Query SQL Server’s schema to find all tables containing a column named ‘x’

The following query will find all tables in my catalog with a column name like ‘city’

SELECT t.name AS table_name,
SCHEMA_NAME(schema_id) AS schema_name,
c.name AS column_name
FROM sys.tables AS t
INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID
WHERE c.name LIKE '%City%'
ORDER BY schema_name, table_name;

Posted On Thursday, April 26, 2012 10:59 AM | Comments (2) |

Thursday, March 1, 2012

Specifying DNS Servers at the command prompt

Did you know you can set your DNS Servers from the command prompt using the NETSH command (available in win 2003 and later)?

You can even specify the order in which the servers are registered in the DNS lookup

netsh interface ip set dns "Local Area Connection" static 8.8.8.8
netsh interface ip add dnsservers "Local Area Connection"  8.8.4.4 index=2
netsh interface ip add dnsservers "Local Area Connection" 10.0.8.100 index=3

If you want to configure DNS to use DHCP:

netsh interface ip set dns “Local Area Connection” dhcp

if you want to clear the table entirely:

netsh interface ip set dns “Local Area Connection” address=none

 

You’ll need to replace “Local Area Connection” with your LAN Connection name, should it differ.

Posted On Thursday, March 1, 2012 4:02 PM | Comments (0) |

Wednesday, February 29, 2012

How to get a Product() (multiplication result) rather than a SUM() (addition result) using T-Sql

Get a summary aggregation of rows in T-Sql is easy thanks to the Sum operator:

Select Sum(Qty) From Table

Why is there no Product() aggregation operation for T-Sql?  Sometimes I want the values multiplied, not added.

 

Luckily, some one who is much smarter in math than I, observed:

log(A * B) = log(A) + log(B)

So, summing the log, and converting back to its exponential value will yield its product.

Select CAST(EXP(SUM(LOG(Qty))) as int) as ExtendedQTY

Happy Calculating!

 

UPDATE: The above expression seems to calculate the wrong value when the value being multiplied is a large number.  For example:

Select CAST(EXP(LOG(11111)) as int)  yields 11110, not 11111.

 

Try this instead:

  DECLARE @ExtendedQty FLOAT

Select  @ExtendedQTY = COALESCE(@ExtendedQTY, 1) * Table.Qty From Table

Select @ExtendedQty

As always, your feedback is welcome.

Posted On Wednesday, February 29, 2012 2:32 PM | Comments (1) |

Saturday, January 28, 2012

Enabling Sql Server Broker Service Hangs

If your connection hangs while attempting to start sql server broker service, its likely caused by the system trying to gain exclusive access to your database.   Some people recommend stopping and restarting the sql server instance.  I find that a little heavy-handed, like swatting a fly with a sledge hammer.  Instead switch the database into single user mode, enable the broker service, and restore the database to multi-user mode.

 

1) Set the database to single user mode:

ALTER DATABASE [DBNAME] SET SINGLE_USER WITH ROLLBACK IMMEDIATE

 

2) Enable Broker Service on the database

ALTER DATABASE [DBNAME] SET ENABLE_BROKER;

 

3)Restore the database to multi-user mode

ALTER DATABASE [DBNAME] SET MULTI_USER

Of course you’ll need proper permissions, but enabling the service this way prevents interruption to any other databases running on your server.

 

Also make sure Broker Service is enabled:

SELECT is_broker_enabled FROM sys.databases WHERE name = ‘DBNAME’;It should return 1 if its enabled.
-- Enable Service Broker:
ALTER DATABASE [DBNAME] SET ENABLE_BROKER;

-- Disable Service Broker:
ALTER DATABASE [DBNAME] SET DISABLE_BROKER;

 

 

More useful SSBS Queries

 

If your activation stored procured isn’t firing, it might be because the queue is disabled.  Check the status of the queues with:

select [name], is_receive_enabled from sys.service_queues; – 0 indicates the queue is disabled.

 

To enable the queue:

alter queue QUEUENAME with status=on; – replace QUEUENAME with the name of your queue

 

Here’s a link to a great site with lots of useful broker service queries

http://myadventuresincoding.wordpress.com/2007/11/22/sql-server-service-broker-tips-and-tricks/

Posted On Saturday, January 28, 2012 3:53 PM | Comments (0) |

Wednesday, October 26, 2011

Google’s Public DNS Servers

Tired of ISP DNS service errors?  switch to use Google’s.  They are FAST and ALWAYS available.

Primary: 8.8.8.8

Secondary: 8.8.4.4

Posted On Wednesday, October 26, 2011 2:48 PM | Comments (1) |

Performing Case-Insensitive joins using EXCEPT operator in LINQ

   1:   var daysOfWeek = new[] { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
   2:   var workDays = daysOfWeek.Except( new []{ "SUNDAY", "SaTURdaY"}); // Performs a case sensitive search and yields Sunday,Monday - Saturday. 
   3:  workDays = daysOfWeek.Except(new[] { "SUNDAY", "SaTURdaY" },StringComparer.OrdinalIgnoreCase); // Performs a case insensitive search and yields Monday-Friday

 

The except operator takes a comparer that tells it how to evaluate the two lists.  Nice one!

Posted On Wednesday, October 26, 2011 1:20 AM | Comments (0) |

Thursday, June 30, 2011

How can I include my derived class type name in the serialized JSON?

Sometimes working with the js Serializer is easy, sometimes its not.   When I attempt to serialize an object that is derived from a base, the serializer decided whether or not to include the type name.

When its present, the type name is represented by a ___type attribute in the serialized json like this:

{"d":{"__type":"Commerce.Integration.Surfaces.OrderCreationRequest","RepId":0}}

The missing type name is a problem if I intend to ship the object back into a web method that needs to deserialize the object.   Without the Type name, serialization will fail and result in a ugly web exception.

The solution, which feels more like a work-around, is to explicitly tell the serializer to ALWAYS generate the type name for each derived type.  You make this declaration by adding a [GenerateScriptType())] attribute for each derived type to the top of the web page declaration.

 

For example, assuming I had 3 derivations of OrderCreationRequest; PersonalOrderCreationRequest, CompanyOrderCreationRequest, InternalOrderCreationRequestion, the code-behind for my web page would be decorated as follows:

    [GenerateScriptType(typeof(PersonalOrderCreationRequest))]
    [GenerateScriptType(typeof(CompanyOrderCreationRequest))]
    [GenerateScriptType(typeof(InternalOrderCreationRequest))]
    public partial class OrderMethods : Page
{
...
}
With the type names generated in the serialized JSON, the serializer can successfully deserialize instances of any of these types passed into a web method.
Hope this helps you as much as it did me. 

Posted On Thursday, June 30, 2011 8:35 PM | Comments (2) |

Thursday, April 28, 2011

QuickTip: Determine if Type implements IEnumerable<T>

I was working on a project that required a determination if the type was an IEnumerable collection of some type. 

 

Using a bit of reflection and the handy-dandy GetGenericTypeDefinition method, I arrive at this:

Code Snippet
  1. public static bool IsIEnumerableOfT(Type type)
  2.       {
  3.           return type.GetInterfaces().Any(t => t.IsGenericType && t.GetGenericTypeDefinition() == typeof (IEnumerable<>)) ;
  4.       }

Happy Coding!

Posted On Thursday, April 28, 2011 8:26 AM | Comments (10) |

Wednesday, April 20, 2011

Reorder Your Accounts in Thunderbird

Ever wanted to re-order your Thunderbird accounts?

 

You can either modify the prefs.js manually

1. Exit Thunderbird if its running.

2. Locate your prefs.js file (default location is c:\users\[your account]AppData\Thunderbird\Profiles

3. create a backup , just in case.

4. Open the prefs.js in any text editor and look for: user_pref("mail.accountmanager.accounts", "account1,account2,account3,account4…"); line

5. Change the order of the accounts manually

6. Restart Thunderbird

 

OR

1. Download and install the FolderPane add-on.

2. From Thunderbird, select Tools->Add ons –> Folderpane and reorder the accounts using the “Move Up” and “Move Down” buttons.

3. Close and restart Thunderbird.

 

The choice is yours.

Posted On Wednesday, April 20, 2011 11:57 AM | Comments (4) |

Tuesday, March 29, 2011

QuickTip: Selecting Children from a Parent Item in Linq

I’m posting this here because I keep forgetting the syntax, and thought others might benefit as well.

 

Given :

public class ParentItem

{

   IEnumerable<ChildItem> Children

}

 

Selecting all the childitem instances from an IEnumerable<ParentItem>:

var allChildren = ParentItems.SelectMany(parent=>parent.Children);

 

Selecting matching childItem instances from an IEnumerable<ParentItem>:

var selectedChildren = ParentItems.SelectMany(parent=>parent.Children).Where(child=><boolean expression for filtering children>)

Posted On Tuesday, March 29, 2011 3:47 PM | Comments (1) |

Saturday, March 19, 2011

Words of Wisdom

Culture beats Strategy every time.

Posted On Saturday, March 19, 2011 10:59 AM | Comments (0) |

Tuesday, March 15, 2011

How to set x509 Certificate private key access rights for AppPoolIdentity

If your website uses the AppPoolIdentity and requires access to the private key of an x509Certficate, you’ll need to grant the read permissions to the iis application pool.

 

To grant permissions to the AppPoolIdentity:

  1. Run Certificates.MMC (or Start->run->mmc.exe, Add Certificate Snap-In for LocalMachine)
  2. Select the certificate (Personal node on the certificate tree) , right click and Manage Permissions.
  3. Add a new user to the permissions list.
  4. Enter "IIS AppPool\AppPoolName" on the local machine". Replace "AppPoolName" with the name of your application pool.

Posted On Tuesday, March 15, 2011 12:09 PM | Comments (1) |

Tuesday, February 15, 2011

Fixing LINQ Error: Sequence contains no elements

I’ve read some posts regarding this error when using the First() or Single() command.   They suggest using FirstOrDefault() or SingleorDefault() instead.

But I recently encountered it when using a Sum() command in conjunction with a Where():

 

Code Snippet
  1. var effectiveFloor = policies.Where(p => p.PricingStrategy == PricingStrategy.EstablishFloor).Max(p => p.Amount);

 

When the Where() function eliminated all the items in the policies collection, the Sum() command threw the “Sequence contains no elements” exception.

 

Inserting the DefaultIfEmpty() command between the Where() and Sum(), prevents this error:

Code Snippet
  1. var effectiveFloor = policies.Where(p => p.PricingStrategy == PricingStrategy.EstablishFloor).DefaultIfEmpty().Max(p => p.Amount);

 

but now throws a Null Reference exception!

 

The Fix:

Using a combination of DefaultIfEmpty() and a null check in the Sum() command solves this problem entirely:

Code Snippet
  1. var effectiveFloor = policies.Where(p => p.PricingStrategy == PricingStrategy.EstablishFloor).DefaultIfEmpty().Max(p =>  p==null?0 :p.Amount);

Posted On Tuesday, February 15, 2011 8:59 AM | Comments (7) |

Tuesday, January 18, 2011

Making Cross-Domain / Cross-Protocol Ajax calls with flXHR, jQuery & ASP.NET

If you attempt to make an ajax call that cross domain or protocol boundaries, the default XHR (XmlHttpRequest) processor will fail.  The out-of-the-box implementation forbids crossing boundaries.

Enter flXHR.  A flash-based proxy that implements (and extends) the XHR API.  That’s good news for JQuery developers.  It means you can use flXHR just like the native Jquery XHR.  There’s also a Jquery proxy plugin that makes it SIMPLE.

 

You can download the sample here.  In my example, I’m hosting the website under IIS and have created an alias for localhost called CMDEV.  I’ve also configured the website for SSL.  This gives me 1 website with multiple domain names, and allows me to simulate cross-domain & cross-protocol calls.   The service code resides in the code behind page and is a static method decorated with the [WebMethod] attribute.

 

About crossdomain.xml:  The file must reside in the website root (unless you specify its location with the PolicyURL setting)  and is VERY picky about the structure of the file.  My sample sets the security policy wide open and is not recommended for production use.

<?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM "http://www.adobe.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
  <site-control permitted-cross-domain-policies="master-only" />
  <allow-access-from domain="*" secure="false" />
  <allow-http-request-headers-from domain="*" headers="*" secure="false" />
</cross-domain-policy>

 

If you wish to support cross-protocol calls (calling an HTTPS service from an HTTP page), you must include the secure=false attribute for both allow-access-from and allow-http-request-headers-from tags.  You’ll also need to specify the noCacheHeader:false setting when configuring the proxy.

(from the Unsecured.aspx page in the sample)

$.flXHRproxy.registerOptions(URL_SECURED + "/", { xmlResponseText: false, noCacheHeader: false });

 

a final word, flXHR only works for asynchronous calls.  If you attempt to make a syncrhonous ajax callback, the xhr proxy will select the default processor, and you’ll get a failure (“Access is denied”) message.

Posted On Tuesday, January 18, 2011 2:10 PM | Comments (0) |

Tuesday, November 23, 2010

Fixing “ResGen.exe" exited with code–1073741701” in Visual Studio 2010

I found this fix online which appears to have resolve this issue, so I wanted to share it here.   I take no credit/responsibility for it, except to say that it has resolved the issue for me.

 

Set the 32-bit flag on resgen.exe

a. Open a Visual Studio command-prompt as an administrator

b. Navigate to the Microsoft SDKs\Windows\v7.0A\bin directory.

c. ***SAVE A COPY*** of your original resgen.exe file.  This is very important if you want to be able to replace our tweak with the original file without having to repair your installation.
copy resgen.exe regen.exe.old

d. Set the 32-bit flag to true using corflags.exe
corflags.exe resgen.exe /32BIT+ /Force

e. Note the warning about strong name issues. On my machine the build now succeeds, without needing to do any additional work due to strong name issues. IF you have problems after trying this method, you can try the following to skip string name verification for that assembly-

f. Register resgen.exe for strong name verification skipping using sn.exe
sn.exe –Vr resgen.exe
WARNING! This is a security risk. You are bypassing strongname verification for this assembly, making it possible for malicious code posing as resgen.exe to execute. To turn verification back on, use sn.exe –Vu resgen.exe

Posted On Tuesday, November 23, 2010 11:59 AM | Comments (2) |

Friday, November 5, 2010

QuickTip: Don’t rely on HTTPPostedFile.FileName

Supposedly, HTTPPostedFile.FileName is supposed to contain just the name of the uploaded file.  It should exclude the original filename path.  This doesn’t always appear to be the case, and seems to vary by the  browser doing an upload.

 

To avoid the browser issue entirely, use a FileInfo(HttpPostedFile.FileName) to return just the file name (and extension) portion of the file.

 

Change this:

Code Snippet
  1. var saveFileName = Path.Combine(UploadedFileServerPath, FilePackage.PostedFile.FileName);

to this:

Code Snippet
  1. var saveFileName = Path.Combine(UploadedFileServerPath, new FileInfo(FilePackage.PostedFile.FileName).Name);

Posted On Friday, November 5, 2010 8:57 PM | Comments (1) |

Migrating SQL Server Broker Service (SSBS) Objects

I recently migrated my dev environment to a new pc.  I moved over all the databases and reattached them.  Unfortunately, I soon discovered my SSBS services weren’t working. I was sending messages to my service, but nothing was showing up in the queue. I added logging and monitoring to the stored procs that act as an entry point to the services, and the stored procs I use for activation.   Still, nothing.

When I ran the Broker Server Diagnostic tool (ssbdiagnose) (available in {Program files}\Microsoft Sql Server\100\tools\binn, it reported the following issues:

Service Broker Diagnostic Utility
The EXECUTE AS for the user dbo specified for activation on queue dbo.FulfillerQueue_Initiator_Mock cannot be impersonated due to an exception Cannot execute as the database principal because the principal "dbo" does not exist, this type of principal cannot be impersonated, or you do not have permission.


The EXECUTE AS for the user dbo specified for activation on queue dbo.FulfillerQueue_Target_Mock cannot be impersonated due to an exception Cannot execute as the database principal because the principal "dbo" does not exist, this type of principal cannot be impersonated, or you do not have permission.

Could not validate the SEND permission of user dbo on service FulfillerService_Target_Mock due to exception Cannot execute as the database principal because the principal "dbo" does not exist, this type of principal cannot be impersonated, or you do not have permission.
3 Errors, 0 Warnings

So what's going on here? I use integrated security on my dev machine, why is it complaining that the principal "dbo" doesn't exist?

The problem is the result of moving my database from another server (my previous dev machine).  The underlying SID of the owner object is no longer valid in my new database.  Since the owner id of these objects don’t match the owner id of the currently executing user, SQL Server generated a permission exception. 

 

The fix is pretty easy, I just needed to change the ownership of these objects back to the SA user:

ALTER AUTHORIZATION ON DATABASE [MYDATABASE] TO [SA]

Running SSBDiagnose with the CONFIGURATION option generated happier results:

C:\Program Files\Microsoft SQL Server\100\Tools\Binn>ssbdiagnose.exe -d FulfillmentMessaging CONFIGURATION FROM SERVICE FulfillerService_Initiator_Mock TO SERVICE Fulfiller Service_Target_Mock ON CONTRACT FulfillerContract ENCRYPTION OFF
Microsoft SQL Server 10.0.2531.0
Service Broker Diagnostic Utility
0 Errors, 0 Warnings

With my permissions errors resolved, my SSBS services were working once again.

Posted On Friday, November 5, 2010 4:58 PM | Comments (2) |

Powered by: