Jim Rogers

Lives in Baton Rouge, LA, with two dogs, one cat, and one lovely wife. I'm a lead developer for GCR Incorporated.

Katrin and Jim

Month List

Sending email from a brinkster account in C#

by Jim May 20, 2011 1:52 PM

The examples on Brinkster’s support pages are hit and miss, and they’re in VB.

static void SendMessage(string email, string messageBody) {     var from = "you@yourdomain.com";     var credentials = new NetworkCredential(from, "password");     var message = new MailMessage()         {             From = new MailAddress(from),             Subject = "Subject",             Body = messageBody,             IsBodyHtml = true         };   message.To.Add(email);   var mailClient = new SmtpClient("mymail.brinkster.com", 2525)         {             DeliveryMethod = SmtpDeliveryMethod.Network,             UseDefaultCredentials = false,             Credentials = credentials         };     mailClient.Send(message); }

Things to note:

  • The from address must be the same email used to authenticate.
  • Port 25 is the standard, but if this doesn’t work (it didn’t for me,) try port 2525.

Hyperlink custom control for TFS

by Jim May 11, 2010 7:41 PM

The Custom Controls for TFS Work Item Tracking site on CodePlex has a couple of useful controls for your TFS work item forms. I need a link on our form which points to an external site that interfaces with TFS. And I needed to add parameters to this link, in order to transfer the work item id to the external site.hyperlink

My answer to this is a hyperlink custom control, which I added to the WITCustomControls project from the CodePlex link above.

To compile, install, and use this Hyperlink control, download the source files and add them to the CodePlex project. Follow the installation instructions there. The XML to include in your work item template looks like this:

<Control FieldName="System.Id" 
  Name="MyLink1"
  Type="HyperLinkControl" 
  Label="Some Page" 
  LabelPosition="Left"
  LinkText="Some Page"
  URL="http://MyServer/SomePage.aspx" 
  ParamNames="id,date" 
  ParamFields="System.Id,System.ChangedDate" />

The ParamNames list is optional; if not included, the control will use the field names for the URL parameter names.

Tags: ,

Code

Testing with WindowsTokenRoleProvider

by jim Apr 06, 2010 8:38 AM

For the second time recently, I’m working on an ASP.NET website that uses windows authentication, and gets roles from Active Directory (AD) using WindowsTokenRoleProvider. The roles correspond to the AD groups that the logged-in user is a member of.

I don’t have permission to modify AD group membership, so how do I test my application’s role and permission code? Do I ask our IT guy to swap me in and out of groups while I’m testing?

clip_image001

Yeah, that’s not going to happen.

My solution to this problem is to use a different provider for the roles; the role provider and the membership provider don’t need to be a matched pair. So I can continue to use windows authentication to verify membership (all domain logins are associated with the application, by default.) But I get roles from an XML file, making them easy to change.

How to set it up:

Microsoft has a description of role providers with an example, the ReadOnlyXmlRoleProvider, which is perfect for our purposes. That sample was for IIS6. If you’re using IIS7 on Vista or Windows 7, the provider must be in the Global Assembly Cache. You can find detailed instructions for creating and registering the provider for IIS7 here. We only need the role provider, but the membership provider might be useful in other scenarios. Be careful about that PublicKeyToken when adding the provider to web.config.

Once the provider is installed and configured, just add the desired windows accounts to Users.xml, in the App_Data folder.

<Users>
  <User>
    <UserName>MYDOMAIN\jsmith</UserName>
    <Password>boo</Password>    <!-- doesn't matter what's here -->
    <EMail>jsmith@mycompany.com</EMail>
    <Roles>Admin,SuperGuy,Etcetera</Roles>
  </User>
</Users>

Now we can access roles in the usual way, without having to bug IT…

string[] userRoles = ((RolePrincipal)User).GetRoles();
            
bool inRole = User.IsInRole(SomeRole);

In production, I just change the web.config to use WindowsTokenRoleProvider rather than my ReadOnlyXmlRoleProvider; no recompiling is necessary.

Tags: ,

Code

SOAP vs. HTTP Post Serialization

by Jim Dec 15, 2009 12:29 PM

We recently got bitten by a tricky bug in our web service (asmx.) One of the returned classes had a setter marked as internal, and the serialization failed for an HTTP Post request.

Now you’re thinking, “What’s tricky about that? XML serialization doesn’t work with readonly properties.”

But you would be wrong. The service passed all of our automated tests just fine. These were Visual Studio web tests, set up by default to send SOAP requests. When SOAP headers are sent, the SoapServerProtocol happily uses XMLSerializer to serialize the return value, complete with internal or private properties.

I’ll jump in here with the moral of the story: if you want to ensure that serialization will work regardless of how your service is called, then it should be tested with both SOAP and Post requests – or perhaps just Post, as this is the more restrictive.

Another option, if you aren't doing integration tests, is to add unit tests which simply serialize the service's arguments and return values. These should catch any new or changed properties which break serialization - assuming that they're kept up to date with the method signatures.

The explanation is more complicated. Two different ServerProtocol-derived classes handle these requests: HTTPServerProtocol and SOAPServerProtocol. They both use XMLSerializer.FromMappings() to create the XMLSerializer which handles the return value. This method is “not intended to be used directly from your code,” according to MSDN.

I attempted to use the Microsoft symbol server to step through the creation of the serializers, but it didn’t want to give me the appropriate web service classes. And .NET Reflector got tiring before I tracked down exactly what was going on. But somewhere in there is the capability to construct and use XMLSerializer in such a way as to serialize readonly properties – something that isn’t possible with the methods intended for public consumption.

Tags: ,

Code

ViewState Property Problems in VB

by Jim Nov 17, 2009 3:50 PM

Quick, what’s wrong with this property? It doesn’t return the value I was expecting.

Public Property ContractIsDeletable() As Boolean
    Get
        If ViewState("ContractDeletable") = Nothing Then
            Return True
        Else
            Return ViewState("ContractDeletable")
        End If
    End Get
    Set(ByVal value As Boolean)
        ViewState("ContractDeletable") = value
    End Set
End Property

Perfectly normal implementation of a ViewState-backed property, right? The following code will print both messages:

ViewState!BooleanCheck = False
If ViewState!BooleanCheck = Nothing Then
    Debug.WriteLine("false is not nothing!!")
End If

ViewState!IntegerCheck = 0
If ViewState!IntegerCheck = Nothing Then
    Debug.WriteLine("zero is not nothing!!")
End If

You can (and I apparently did) get away with the construct at top, if the default value returned in the case of a Nothing happens to be zero, or false. But that evaluation is incorrect. The correct way to make this property is:

    Public Property ContractIsDeletable() As Boolean
        Get
            If IsNothing(ViewState("ContractDeletable")) Then
                Return True
            Else
                Return ViewState("ContractDeletable")
            End If
        End Get
        Set(ByVal value As Boolean)
            ViewState("ContractDeletable") = value
        End Set
    End Property

Because bools and ints aren’t nullable types, the = comparison doesn’t work property. IsNothing does the trick.

Tags:

Code