Tuesday, January 22, 2013
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
Friday, December 7, 2012
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 != ' .'
Monday, December 3, 2012
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
***********************
Wednesday, September 26, 2012
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.
Thursday, September 6, 2012
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
}
Thursday, April 26, 2012
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;
Thursday, March 1, 2012
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.
Wednesday, February 29, 2012
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.
Saturday, January 28, 2012
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/
Wednesday, October 26, 2011
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
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!
Thursday, June 30, 2011
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.
Thursday, April 28, 2011
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
- public static bool IsIEnumerableOfT(Type type)
- {
- return type.GetInterfaces().Any(t => t.IsGenericType && t.GetGenericTypeDefinition() == typeof (IEnumerable<>)) ;
- }
Happy Coding!
Wednesday, April 20, 2011
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.
Tuesday, March 29, 2011
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>)
Saturday, March 19, 2011
Culture beats Strategy every time.
Tuesday, March 15, 2011
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:
- Run Certificates.MMC (or Start->run->mmc.exe, Add Certificate Snap-In for LocalMachine)
- Select the certificate (Personal node on the certificate tree) , right click and Manage Permissions.
- Add a new user to the permissions list.
- Enter "IIS AppPool\AppPoolName" on the local machine". Replace "AppPoolName" with the name of your application pool.
Tuesday, February 15, 2011
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
- 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
- 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
- var effectiveFloor = policies.Where(p => p.PricingStrategy == PricingStrategy.EstablishFloor).DefaultIfEmpty().Max(p => p==null?0 :p.Amount);
Tuesday, January 18, 2011
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.
Tuesday, November 23, 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
Friday, November 5, 2010
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
- var saveFileName = Path.Combine(UploadedFileServerPath, FilePackage.PostedFile.FileName);
to this:
Code Snippet
- var saveFileName = Path.Combine(UploadedFileServerPath, new FileInfo(FilePackage.PostedFile.FileName).Name);
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.
Friday, October 8, 2010
Many of the examples of databinding use datasource or objectsource controls. I prefer to databind from the code-behind. I feel I have finer control over how to data is prepared before I load it.
The downside to doing this “late binding” of the data, and I can’t use the strongly typed names in my declarative markup. The following code fails because the compiler can’t resolve the “Products” reference.
Code Snippet
- <asp:DataList ID="DataList1" runat="server" RepeatColumns="1" DataSource='<%#Products%>'>
instead, you must use the Eval() method of the Databinder to resolve the references. The following works fine for any type of binding (late or early):
Code Snippet
- <asp:DataList ID="DataList1" runat="server" RepeatColumns="1" DataSource='<%#DataBinder.Eval(Container.DataItem,"Products")%>'>
Happy Coding!
Tuesday, September 28, 2010
Code Snippet
- ThreadPoolHelper.QueueUserWorkItem(arg1, arg2, arg3,
- (localArg1, localArg2, localArg3) =>
- {
- /* code block */
- });
Monday, September 27, 2010
I’m posting this because I never seem to be able to recall this value when I need it. Under Windows 7:
Environment.SpecialFolders.Programs resolves to: C:\Users\[username]\AppData\Roaming\Microsoft\Windows\Start Menu\Programs