04 December 2007

WCF - The remote server returned an unexpected response: (400) Bad Request.

The WCF fault "The remote server returned an unexpected response: (400) Bad Request.", might be caused by some quota or timeout on server / client side.The solution is to increase reader quota values from binding configuration on both sides:

<bindings>
<wsHttpBinding>
    <binding name="WSHttpBinding_IService" closeTimeout="00:01:00" 
    openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
    bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard"
    maxBufferPoolSize="2000000" maxReceivedMessageSize="2000000"
    messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true"
    allowCookies="false">
        <readerQuotas maxDepth="2000000" maxStringContentLength="2000000" maxArrayLength="2000000"
        maxBytesPerRead="2000000" maxNameTableCharCount="2000000" />
        <reliableSession ordered="true" inactivityTimeout="00:10:00" enabled="false" />
        <security mode="Message">
            <transport clientCredentialType="Windows" proxyCredentialType="None" realm="" />
            <message clientCredentialType="Windows" negotiateServiceCredential="true"
            algorithmSuite="Default" establishSecurityContext="true" />
        </security>
    </binding>
</wsHttpBinding>
</bindings>
<services>
    <service name="MyService" behaviorConfiguration="MyServiceTypeBehaviors">
        <endpoint address="" binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IService" contract="MyIService"/>
        <endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex"/>
     </service>
</services>

30 November 2007

14 March 2007

Visual Studio 2005 Code Snippets

IntelliSense Code Snippets are reusable, task-oriented blocks of code. Visual Studio 2005 has some code snippets. There are some additional Code Snippets

Download, install and enjoy.

10 January 2007

Visual Studio 2005 SP1, dotnetfx 3.0, LINQ => Refactoring gone

I installed Visual Studo 2005 SP1, dotnet 3.0, Visual Studio Code Name "Orcas" and LINQ.
When I wanted to use the refactoring the SmartTags stopped working and the Refactor option was missing!!!
I needed to refactor some .net 2.0 code and even nothing.
So I went googling and found the solution here!!!
Only the last option worked for me :)

The steps are:
1) Launch regedit.exe
Open HKEY_LOCAL_MACHINE\Software\Microsoft\VisualStudio\8.0\Packages\{A066E284-DCAB-11D2-B551-00C04F68D4DB}\SatelliteDLL
Edit the "Path" value and change it from "C:\Program Files\Microsoft Visual Studio 8\VC#\VCSPackages\1033\" to "C:\Program Files\Microsoft Visual Studio 8\VC#\VCSPackages\"
Restart Visual Studio and see if these problems are fixed?

2) Open a command prompt, go to
C:\Program Files\Microsoft Visual Studio 8\Common7\IDE
Run
(i) devenv /setup
(ii) devenv /resetuserdata
(iii) devenv /resetsettings CSharp

When installing orcas / LINQ, be afraid, be very afraid.

02 January 2007

How to Pad Left a number?

Padding left a number using SQL Server is implemented using the REPLICATE TSQL function.
Here is an example to format a date:
DECLARE @Date VARCHAR(8)
SET @Date = CAST(YEAR(GETDATE()) AS VARCHAR(4))
SET @Date = @Date + REPLICATE('0', 2 - DATALENGTH(CAST(MONTH(GETDATE()) as VARCHAR))) + CAST(MONTH(GETDATE()) as VARCHAR) 
SET @Date = @Date + REPLICATE('0', 2 - DATALENGTH(CAST(DAY(GETDATE()) as VARCHAR))) + CAST(DAY(GETDATE()) as VARCHAR) 
SELECT @Date


Create a SQL Server function for padleft and padright and you job will be simplefied. Here is a good place to start.

18 December 2006

Visual Studo 2005 SP1 is here

Today I tried to install Visual Studo 2005 SP1 and had some setup issues.
I hope this guide will help you as a reference of what to do:
1) Remove SP beta - Activate show updates in add-remove programs.
Don't forget to have your original VS.Net installation medium available!!!
2) Unistall the Web Application Project, since it is built-in to SP1
3) The following error is normal:
The installation of C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\ZNW442\VS80sp1-KB926601-X86-ENU.msp is not permitted due to an error in software restriction policy processing. The object cannot be trusted.
A workaround:
i) Open Administrative Tools
ii) Open Local Security Policy
iii) Select Software Restriction Policies
iv) If no software restrictions are defined, right click the Software Restriction Policies node and select New Software Restriction Policy
v) Double click Enforcement and select "All users except local administrators"
vi) Click OK
vii) Reboot the machine

More information on Heath Stewart's Blog
To learn more about Visual Studio SP1 visit Development Catharsis

Unobtrusive Flash Objects (UFO)

Unobtrusive Flash Objects (UFO) is a DOM script that embeds the Flash object and resolves the flash activation problem.
UFO is free and supports the W3C standards.

Example:

<html>
<head>
<script src="ufo.js" type="text/javascript"></script>
<script type="text/javascript">
var FO = { movie:"FlashMovie.swf", width:"200", height:"100",
majorversion:"6", build:"40" };
UFO.create(FO, "FlashLayer");
</script>
</head>
<body>
<div id="FlashLayer">
<p>Alternate Content


</div>
</body>
</html>

More information and dowload here.

How to place flash on back of HTML?

To place flash on back of HTML, set the flash container with z-index to -1:
<div id="flashContent" style="z-index:-1" ></div>

and set flash variable wmode to opaque.

06 October 2006

How to fix: Version mismatch. BAML stream has version number '0.96' but parser can read only version '0.94'.

After you uninstall .Net 3.0 runtime, windows sdk and orcas, you ran the uninstall utility, which should work in most cases. If it does not, uninstall everything again and run the uninstall utility again.

After all this, reboot and check folder C:\Program Files\Reference Assemblies\Microsoft. If there are any folders or files in this folder, then manually removed them. After you restart your PC; only install the .Net 3.0 Runtime. Verify that it works first before proceeding with the install of the SDK and Orcas. You should be able to verify that the runtime is installed correctly if you go to http://xaml.net/ and click on the Snowboarder image. The image will load a xaml page with an animated snowboarder. If this works, proceed with the install of SDK and Ocras.

02 August 2006

Convert a string to TimeSpan

How to Convert a string to TimeSpan in C#


To convert a string with hours, minutes and seconds to a time span, use:

TimeSpan.Parse("00:30:00");

Microsoft Message Queue in C#

How to read/write to a Message Queue in c#:

Write:
MessageQueue queue = null;
if (context.Cache["QueueKey"] == null)
{
queue = new MessageQueue(".\private$\queueName", false, true);
context.Cache["QueueKey"] = queue;
}
else
{
queue = (MessageQueue)context.Cache["QueueKey"];
}
queue.Formatter = new XmlMessageFormatter(new Type[] { typeof(System.String) });
queue.Send(msg);

Read using a windows service:
public partial class QueueService : ServiceBase
{
int _threadCount= 5;
TimeSpan _joinThreadsTimeSpan = TimeSpan.Parse("00:00:02");

Thread[] workerThreads;
QueueReader[] threadHandlers;

public QueueService ()
{
InitializeComponent();
}

protected override void OnStart(string[] args)
{
arrWorkers = new QueueReader[_threadCount];
threadHandlers = new Thread[_numberOfThreads];

for (int i = 0; i < _threadCount; i++)
{
threadHandlers[i] = new QueueReader();
threadHandlers[i].ServiceStarted = true;

ThreadStart st = new ThreadStart(threadHandlers[i].ExecuteTask);
workerThreads[i] = new Thread(st);
}

for (int i = 0; i < _threadCount; i++)
{
workerThreads[i].Start();
}
}

protected override void OnStop()
{
for (int i = 0; i < _threadCount; i++)
{
threadHandlers[i].ServiceStarted = false;
workerThreads[i].Join(_joinThreadsTimeSpan);
}
}
}

QueueReader Threads
public class QueueReader
{
private MessageQueue _queue = null;
private TimeSpan _timeToWait = TimeSpan.Parse("00:00:05");
private bool _serviceStarted = false;

public QueueReader()
{

_queue = new MessageQueue(".\private$\queueName");
_queue.ReceiveCompleted += new ReceiveCompletedEventHandler(OnReceiveCompleted);
_queue.Formatter = new XmlMessageFormatter(new Type[] { typeof(System.String) });
_queue.BeginReceive(_timeToWait);
}


public bool ServiceStarted
{
get
{
return _serviceStarted;
}
set
{
_serviceStarted = value;
}
}

public void ExecuteTask()
{
while (_serviceStarted)
{
Thread.Sleep(_timeToWait);
}

Thread.CurrentThread.Abort();
}


private void OnReceiveCompleted(object sender, ReceiveCompletedEventArgs e)
{
MessageQueue senderQueue = null;

try
{
senderQueue = (MessageQueue)sender;

Message message = senderQueue.EndReceive(e.AsyncResult);


}
catch (MessageQueueException)
{
}
catch (Exception ex)
{
throw(ex);
}
finally
{
_queue.BeginReceive(_timeToWait);
}
}
}

01 September 2005

Firefox recognized as an uplevel browser in ASP.Net

Just paste in <system.web> of web.config or machine.config:


<browserCaps>
<case match="^Mozilla/5\.0 \([^)]*\) (Gecko/[-\d]+)(?'VendorProductToken'
(?'type'[^/\d]*)([\d]*)/(?'version'(?'major'\d+)(?'minor'\.\d+)(?'letters'\w*)))?">

browser=Gecko
<filter>
<case match="(Gecko/[-\d]+)(?'VendorProductToken'
(?'type'[^/\d]*)([\d]*)/(?'version'(?'major'\d+)(?'minor'\.\d+)(?'letters'\w*)))">

type=${type}
</case>
<case> <!-- plain Mozilla if no VendorProductToken found -->
type=Mozilla
</case>
</filter>
frames=true
tables=true
cookies=true
javascript=true
javaapplets=true
ecmascriptversion=1.5
w3cdomversion=1.0
css1=true
css2=true
xml=true
tagwriter=System.Web.UI.HtmlTextWriter
<case match="rv:(?'version'(?'major'\d+)(?'minor'\.\d+)(?'letters'\w*))">
version=${version}
majorversion=0${major}
minorversion=0${minor}
<case match="^b" with="${letters}">
beta=true
</case>
</case>
</case>
</browserCaps>

31 August 2005

How to convert from hexadecimal to int?


public string IntToHex(int number)
{
return String.Format("{0:x}", number);
}

public int HexToInt(string hexString)
{
return int.Parse(hexString,
System.Globalization.NumberStyles.HexNumber, null);
}

09 August 2005

Invalidade ASP.Net Cache to reload dependent user controls

If you have two user controls (ascx) in the asp.net cache and need to update a user control if the other changes, you can use the following method:

On the dependent ascx, that needs to refresh:
PartialCachingControl pcc= Parent as PartialCachingControl;
StaticPartialCachingControl spcc= Parent as StaticPartialCachingControl;

if (pcc !=null) pcc.Dependency=new CacheDependency(null, new string[]{"HighLightChange"});

This will create a cache dependency on the HighLightChange string.

On the ascx that needs to invalidate the cache:
HttpRuntime.Cache.Insert("HighLightChange","true");

The change on the HighLightChange will invalidate the cache dependency of the user control that must do a data refresh.

02 August 2005

How to get the ApplicationPath in ASP.Net?

If you have a virtual directory:
string path = HttpContext.Current.Request.ApplicationPath;

If your site is on the root or a virtual directory:

string path = HttpContext.Current.Request.ApplicationPath;
if (path == "/")
path = "http://" + Request.Url.Host;
else
path += "/";

05 May 2005

XML Serialization

This is a sample of how to serialize a class in .Net

using System;

using System.Xml;
using System.Xml.Serialization;
using System.IO;
using System.Text;

namespace WindowsApplication1
{
public class AppConfig
{
private long _Code;
private string _Description;
private string _Obs;
public long Code
{
get {return _Code;}
set { _Code = value;}
}

public string Description
{
get {return _Description;}
set { _Description = value;}
}

public string Obs
{
get {return _Obs;}
set { _Obs = value;}
}

}

///
/// Summary description for Configuration.
///

[XmlInclude(typeof(AppConfig))]
public class Configuration
{
private AppConfig _AppConfig = null;
public Configuration()
{
_AppConfig = new AppConfig();
}

public void SetConfiguration(long code, string desc, string obs)
{
_AppConfig.Code = code;
_AppConfig.Description = desc;
_AppConfig.Obs = obs;
}

public void Searialize()
{
XmlTextWriter writer = new XmlTextWriter("test.xml", Encoding.Unicode);
writer.Formatting = Formatting.Indented;
XmlSerializer serializer = new XmlSerializer(typeof(AppConfig));
serializer.Serialize(writer, _AppConfig);
writer.Close();
}
}
}


29 July 2004

Web Page Unit Tests

Web page Unit Tests is the process of testing your pages, to validate the controls state and the scripts developed.
You need to bypass the browser and access your site from the test code.
Tools for developing unit tests for web pages are available for the most common languages. These tools emulate the browser behavior and allow you to examine the pages contents.
Web pages unit tests are hard to develop. Before you start to implement them, first decide if they are really necessary.
Tools:
1)ASP.Net
HttpUnit.NET - Port of HttpUnit for .Net - Not yet available
nHttpUnit - Port of HttpUnit for .Net - Not yet available
CSHttpUnit - C# API for accessing web sites without a browser
NUnitASP - ASP.NET web pages Testing
2) JavaScript
jsUnit - Testing framework for client-side (in-browser) JavaScript
3) HTML and JavaScript Tests with JUnit
htmlUnit
actiWATE
3) IE
Samie - IE test automation with perl scripts

ieUnit - Test logical behaviors of web pages
4) ASP
ASPUnit

26 July 2004

Database Refactorings

Database refactoring is the process of modifying the database schema (tables, stored procedures, triggers, ...) to improve the design, while retaining both its behavioral and informational semantics.
The database refactoring is implemented as:
1) After application coded and database schema is developed and unit tested,  a refactoring is detected because of an error or a new requirement.
2) Choose the database refactoring
3) Determine data cleanup
4) Write Unit Tests
5) Implement the changes
6) Run Tests

The most common database refactorings are:
1) Add Default Value
2) Add Nullable Column
3) Drop Column
4) Make Column Non Nullable
5) Remove Default Value
6) Add Foreign Key Constraint
7) Add Unique Index
8) Drop Table
9) Make Column Nullable
10) Add Non Nullable Column
11) Update Data
12) Delete Data
13) Insert Data
14) Move Data

Database testing tools
spUnit - Stored Procedures Unit Tests
tsqlUnit - Transact-SQL Unit Tests
DBUnit - JUnit extension
utPLSQL - PL/SQL Unit Tests


References
Agile Data 
List Of Database Refactoring - Martin Fowler

Books
Agile Database Techniques

21 July 2004

Refactoring

Refactoring is the process of restructing the code, without changing its behavior. 
The process will improve the design of existing code.
There are some patterns, look in look in Martin Fowler Refactoring site  http://www.refactoring.com/catalog/index.html for a comprehensive list.

The most common patterns are:
Extract Method
: Group related pieces of code into a method.
Rename: Rename any symbol (namespace, type, method, class, package,field,...) to an understanding name
Move Type: Nove types between namespaces/packages
Extract type to a new file: Move code, implementing it in a new file
Change Signature: Add/remove/reorder/rename/change parameters of a method
Introduce Variable: Create a local variable to make code more readable
Inline variable: Inverse of introduce variable refactoring. Replace variable with its initializer.
Convert method to property
Convert property to method 
Unit tests should also be refactored, since they are implemented as code.

Tools
There are some Refactoring tools available, look at http://www.refactoring.com/tools.html for a complete list.
c# free tools
http://opnieuw.com/
http://softwarestudio.smartcoding.org

Exercises:
http://www.xp123.com/rwb/
References:
http://www.refactoring.com/
http://www.xp123.com/

20 July 2004

TDD

Test Driven Development (TDD) is a lightweight programming methodology, in witch the tests are implemented before writing code. The steps are very simple:
1) Write a small test
2) Run the test
3) Write enough code to make the test succeed
4) Refactor: Clean up the code
5) Repeat
TDD Mantra
The TDD mantra is very simple: red/green/refactor (like a traffic light).
Red - Test Fails
Green - Test succeeds
Refactor - Clean up
This is the xUnit terminology.

xUnit can be seen has the language for writting tests. The xUnit is a framework that makes possible to define assertions.
xUnit is implemented in all main computer languages. The first was sUnit, for Smalltalk.
There are others like nUnit, clrUnit, and csUnit for Microsoft .Net framework, jUnit in Java and vbUnit for Visual Basic.

References:
http://www.testdriven.com/
http://www.xprogramming.com/

xUnit:
nUnit
csUnit
clrUnit
jUnit
vbUnit
sUnit
VB Lite Unit
Open Source Testing: The open source testing site
http://www.opensourcetesting.org/