Saturday, 4 February 2012

WhoAmIRequest from a Silverlight Web Resource in MS Dynamics CRM 2011

Probably the simplest request that can be made in MS Dynamics CRM, is a WhoAmI request. This request returns details (UserId, BusinessUnitId & OrganizationId) of the current user or the user under whose context the code is running.

Note that this code, assumes that you have followed the "Use the SOAP Endpoint for Web Resources with Silverlight" walkthrough from the SDK, which can also can be found here.
private void WhoAmIButton_Click(object sender, RoutedEventArgs e)
{
    OrganizationRequest req = new OrganizationRequest() { RequestName = "WhoAmI" };
    IOrganizationService service = SilverlightUtility.GetSoapService();

    service.BeginExecute(req, new AsyncCallback(WhoAmIResult), service);
}
As per usual with Silverlight, it is necessary to make a callback to get the response, which is below:
private void WhoAmIResult(IAsyncResult result)
{
  try
  {
      OrganizationResponse response =  
              ((IOrganizationService)result.AsyncState).EndExecute(result);
 
      Guid userId = new Guid(response["UserId"].ToString());
  }
  catch (Exception ex)
  {                
      throw ex;
  }
}
Do note that if you need the UserId value to perform another query, you'll need to ensure that the second query is not made until this one (WhoAmIResult) has finished.

Friday, 3 February 2012

Making an Appointment Request from a Silverlight Web Resource in MS Dynamics CRM 2011

I’ve been looking at upgrading one of our Apps to MS Dynamics CRM 2011 and one of the things that we do a lot of is appointment booking.

At the moment, we have an iFrame showing an ASP.NET webpage with some buttons that when pressed, make an ajax call to a web method hosted in the ISV folder. Once the appointment is selected, the actual booking of the appointment is handled by a plug-in. I wanted to see whether we could remove the iFrame and use a Silverlight webresource.

I have to say that I found it a bit confusing and it took me quite a few attempts to get the RequestName right, this post by Jamie Miller sent me in the right direction. The search for appointments is started by a user clicking a button.

Note that this code, assumes that you have followed the "Use the SOAP Endpoint for Web Resources with Silverlight" walkthrough from the SDK, web link can be found here.

Here is the method that makes the appointment request:

private void checkButton_Click(object sender, RoutedEventArgs e)
{           
    AppointmentRequest appReq = new AppointmentRequest
    {
        Objectives = new ObservableCollection<ObjectiveRelation>(),
        RequiredResources = new ObservableCollection<RequiredResource>(),
        AppointmentsToIgnore = new ObservableCollection<AppointmentsToIgnore>(),
        Constraints = new ObservableCollection<ConstraintRelation>(),
        Sites = new ObservableCollection<Guid>(),
        Duration = 60,
        Direction = SearchDirection.Forward,
        NumberOfResults = 5,
        ServiceId = new Guid("DD535FD0-F84B-E111-8F2F-00505688095F"),
        SearchWindowStart = DateTime.UtcNow,
        SearchWindowEnd = DateTime.UtcNow.AddDays(7.0),
        AnchorOffset = 300
    };
   
    OrganizationRequest req = new OrganizationRequest() { RequestName = "Search" };
    
    req["AppointmentRequest"] = appReq;

    IOrganizationService service = SilverlightUtility.GetSoapService();

    service.BeginExecute(req, new AsyncCallback(GetAppReqResult), service);
}
As this is Silverlight, an asynchronous callback is needed to actually invoke the request, which is done by the method below.
private void GetAppReqResult(IAsyncResult res)
{
   try
   {
     OrganizationResponse resp = 
                          ((IOrganizationService)res.AsyncState).EndExecute(res);
   
     SearchResults results = (SearchResults)resp["SearchResults"];
   
     this.Dispatcher.BeginInvoke(() => ProcessAppointments(results));        
   
   }
   catch (Exception)
   {
       MessageBox.Show("Error Occurred");
   }
}

Not shown here is the ProcessAppointments method, which updates a DataGrid object in the Silverlight Web Resource.

Monday, 30 January 2012

Dual-Booting McAfee Endpoint Encryption - Linux Kernel Upgrade

I used the package manager to upgrade the kernel to 3.0.0-15-generic in my laptop, yesterday evening and when I tried to boot into Windows this morning, I couldn't: there was no Windows entry in the Grub Boot Menu.

After a bit of cursing, when I finally calmed down, I realized what had happened. When a new kernel is installed, a new grub configuration file (grub.cfg) file will be generated and this is based, I think, on the output of os-prober, but, and this is crucial, because my Windows installation is encrypted, the installation is not detected and thus missed off the new grub configuration file.

In order to rectify this, I had to manually edit the grub configuration file (/boot/grub/grub.cfg) and add, following the last menuentry entry, this entry:
menuentry "Windows" {
        set root='(hd0,1)'
        chainloader +1
}
If your Windows installation is in another partition, then you'll need to modify the second line, e.g. set root='(hd1,1)' for the first partition of your second hard drive.

Do be careful when modifying /boot/grub/grub.cfg as you could end up when a non booting system and bear in mind that if you run update-grub2, this file will be overwritten, with whatever grub detects.

Tuesday, 24 January 2012

It's a self signed world - Part 2. The joy of certificates - Part 7

Back in August I wrote a blog post describing how to use makecert to create a self signed CA, I also said that I would repeat the process but using OpenSSL, well your prayers have been answered. Since OpenSSL ships with most Linux distros and also works in Windows, this is the ideal tool for the job.

The key point of a self signed certificate is that, well, it is self signed, which means that it is only really good for development or testing as it won't be trusted by external users, particularly if accessing a website using a modern web browser. I guess you could also use it for internal services too.

At any rate, I'm running this from CentOS 6.2 using OpenSSL 1.0.0-fips 29 Mar 2010. In order to get the OpenSSL version just type:
openssl version
These are the steps needed to create a  self signed certificate using OpenSSL:
  1. Create server certificate private key: 
    openssl genrsa -des3 -out phpmyadmin.key 1024
  2. Create Certificate Signing Request, this is what you would normally pass to a CA (e.g. Verisign) for them to generate a signed certificate with. They normally check that you say who you are and after money has exchanged hands they issue with the public key signed by their CA:
    openssl req -new -key phpmyadmin.key -out phpmyadmin.csr
  3. Remove Passphrase from key. If you want to be prompted for the passphrase everytime Apache starts, then skip to step 4:
    cp phpmyadmin.key phpmyadmin.key.pass
    openssl rsa -in phpmyadmin.key.pass -out phpmyadmin.key
  4. Create public server certificate:
    openssl x509 -req -days 1000 -in phpmyadmin.csr -signkey phpmyadmin.key -out phpmyadmin.crt
That is it, you now have a private/public key pair that can be used for Apache, see this post for details on how to configure the certificates. Do note, that you don't actually have a CA so these two lines need to be commented out:
#   Server Certificate Chain:
SSLCertificateChainFile /etc/httpd/conf.d/certs/win2k8ca.cer

#   Certificate Authority (CA):
SSLCACertificateFile /etc/httpd/conf.d/certs/win2k8ca.cer
If you want to use this private/public key with IIS, then you need to convert it into a pkcs#12 format certificate, which you can do with the following command:
openssl pkcs12 -export -in phpmyadmin.crt -inkey phpmyadmin.key -out phpmyadmin.pfx
Please remember to import the certificate to the trusted root certification authorities of the server as well as your personal store to prevent any problems.

Installing secure phpMyAdmin on CentOS 6.2

Following on from Sunday's post on how to set up phpMyAdmin on CentOS 6.2, I thought it would be a good idea to set up phpMyAdmin as a secure website (HTTPS), rather than in clear-text (HTTP). This will ensure that all traffic between the web browser and phpMyAdmin is encrypted.

In a previous post I set up a Certification Authority so I will be using this CA to generate the necessary certificates, but don't worry if you don't have one, you can use makecert or OpenSSL to generate a self signed certificate.

All that is needed is a server and CA certificate, if you've followed my previous post on phpMyAdmin, you can go directly to step 7. Thus armed with a pkcs#12 server certificate (phpMyAdmin.pfx) and a CA certificate (win2kca.cer) we can start:
  1. Set SELinux to allow Apache to bind to a non-default port:
    setsebool -P allow_ypbind 1
  2. Download EPEL Release to enable usage of EPEL Repository: 
    wget http://download.fedora.redhat.com/pub/epel/6/i386/epel-release-6-5.noarch.rpm
  3. Install EPEL Release package:
    yum install epel-release-6-5.noarch.rpm -y
  4. Install phpMyAdmin:
    yum install phpmyadmin -y
  5. Create new directory to host the phpMyAdmin website: 
    mkdir /var/www/phpMyAdmin
  6. Copy phpMyAdmin installation to the directory created in the previous step: 
    cp -r /usr/share/phpMyAdmin/. /var/www/phpMyAdmin
  7. Extract public and private key from server certificate:
    openssl pkcs12 -in phpMyAdmin.pfx -out phpMyAdmin.key -nodes -nocerts
    openssl pkcs12 -in phpMyAdmin.pfx -out phpMyAdmin.crt -nodes -nokeys
  8. Restrict permissions on key file:
    chmod 400 phpMyAdmin.key
  9. Create certificate and key directories and move certificates and keys to them:
    mkdir /etc/httpd/conf.d/certs
    mkdir /etc/httpd/conf.d/keys
    mv phpMyAdmin.crt /etc/httpd/conf.d/certs
    mv phpMyAdmin.key /etc/httpd/conf.d/keys
    cp win2k8ca.cer /etc/httpd/conf.d/certs
  10. Set SELinux to permissive, this is to prevent issues with SELinux preventing Apache from working properly:
    setenforce 0
  11. Edit Apache's SSL configuration file (/etc/httpd/conf.d/ssl.conf). I have changed the port to 7777 and prevented LOW ciphers from being accepted. The rest is simply providing the location of the certificates. Only listing relevant parts of ssl.conf:
    Listen 7777

    <VirtualHost _default_:7777>

    #   SSL Cipher Suite:
    SSLCipherSuite ALL:!ADH:!EXPORT:!SSLv2:RC4+RSA:+HIGH:+MEDIUM

    #   Server Certificate:

    SSLCertificateFile /etc/httpd/conf.d/certs/phpMyAdmin.crt

    #   Server Private Key:

    SSLCertificateKeyFile /etc/httpd/conf.d/certs/phpMyAdmin.key

    #   Server Certificate Chain:
    SSLCertificateChainFile /etc/httpd/conf.d/certs/win2k8ca.cer

    #   Certificate Authority (CA):
    SSLCACertificateFile /etc/httpd/conf.d/certs/win2k8ca.cer

    </VirtualHost>
    1. You can check that the apache configuration file is correct by using:
      apachectl -t 
  12. Restart Apache:
    apachectl -k restart or service httpd restart
  13. Open firewall for port 7777 and save IPTables configuration:
    iptables -I INPUT -p tcp --dport 7777 -j ACCEPT; service iptables save
  14. You can now navigate to https://phpmyadmin.dev.com:7777/setup (If you are using Chrome, you will see this screen first. Other browsers will show similar screens). Note that you'll need a entry on your hosts file that points phpmyadmin.dev.com to the IP address of the Server: 
  15. Click Procceed anyway. You are seeing this because your CA is not trusted by Chrome.
    Although it would seem that the connection is not encrypted, the icon is misleading, it just means that it is not trusted. See below for confirmation:
  16. Because I'm lazy, I'm going to reuse the screenshots and text from my previous phpMyAdmin post, so .. Click New Server. I only changed the name and compression, accepted defaults for everything else:
  17. Go To Authentication Tab. See this link for an overview of the authentication types:
  18. Click Save, which will bring you to the screen below:
  19. Download the configuration file (config.inc.php) and copy it to /var/www/phpMyAdmin.
  20. You can now start using phpMyAdmin on https://phpmyadmin.dev.com:7777:
  21. All that remains is to renable SELinux and deal with the policy violations:
    cat /var/log/audit/audit.log | grep denied > ssl
    audit2allow -M apachessl -i ssl
    semodule -i apachessl.pp
    setenforce 1
Note that steps 2 & 3 simply add repository for the EPEL repository to your yum repository collection and install the repository key.

In theory, the setup script should be able to generate the configuration file for you, but I've not been able to get it to work. Instructions can be found here if you are interested. 

I haven't thoroughly tested this setup so it is possible, as always, that there could be SELinux issues. All I can suggest is that, if you have some inexplicable issue, have a look at the SELinux log (/var/log/audit/audit.log).

    Sunday, 22 January 2012

    Installing phpMyAdmin in CentOS 6.2 (netinstall)

    I really have no issue with using a terminal, in fact I quite love the geekiness associated with it, but for some reason I never feel comfortable using a terminal to manage mySQL, which is why I love phpMyAdmin.

    I am installing phpMyAdmin in a machine that hosts Joomla, see this post for more details, in practical terms this means that a second website will be needed to host phpMyAdmin, whether you host this site on a different port or a host header it's up to you, the process is fairly similar. Do bear in mind that using a different port has implications to your firewall configuration, in this post I will be using a different port.

    It is worth bearing in mind that this configuration is not secure and as such should only be used on internal networks. Although running the website on a non-standard port will provide obscurity, it does not provide security. Have a look at this post for a secure phpMyAdmin installation guide.

    Unfortunately phpMyAdmin is not, at the time of writing, included with RHEL based systems. Luckily, it is part of the Extra Packages for Enterprise Linux (EPEL) interest group. This means that the EPEL repository can be used to install phpMyAdmin thus obviating the need to install it from source.

    Here are the steps needed to install phpMyAdmin in a CentOS 6.2 server:
    1. Set SELinux to allow Apache to bind to a non-default port:
      setsebool -P allow_ypbind 1
    2. Download EPEL Release to enable usage of EPEL Repository: 
      wget http://download.fedoraproject.org/pub/epel/6/i386/epel-release-6-5.noarch.rpm
    3. Install EPEL Release package:
      yum install epel-release-6-5.noarch.rpm -y
    4. Install phpMyAdmin:
      yum install phpmyadmin -y
    5. Create new directory to host the phpMyAdmin website: 
      mkdir /var/www/phpMyAdmin
    6. Copy phpMyAdmin installation to the directory created in the previous step: 
      cp -r /usr/share/phpMyAdmin/. /var/www/phpMyAdmin
    7. Add a new virtual host to Apache, by editing the Apache configuration file /etc/httpd/conf/httpd.conf, see this post for more details. Relevant parts of httpd.conf:
      Listen 80
      Listen 8888

      NameVirtualHost *:80
      NameVirtualHost *:8888

      <VirtualHost *:80>
          ServerAdmin manyrootsofallevil@myhost.com
          DocumentRoot /var/www/html
          ServerName  Joomla
          ErrorLog logs/Joomla_error
          CustomLog logs/Joomla-access_log common
      </VirtualHost>

      <VirtualHost *:8888>
          ServerAdmin manyrootsofallevil@myhost.com
          DocumentRoot /var/www/phpMyAdmin
          ServerName  Joomla
          ErrorLog logs/phpMyAdmin_error
          CustomLog logs/phpMyAdmin-access_log common
      </VirtualHost>
      1. You can check that the apache configuration file is correct by using:
        apachectl -t 
    8. Restart Apache:
      apachectl -k restart or service httpd restart
    9. Open firewall for port 8888 and save IPTables configuration:
      iptables -I INPUT -p tcp --dport 8888 -j ACCEPT; service iptables save
    10. From a browser navigate to http://localhost:8888/setup :
    11. Click New Server. I only changed the name and compression, accepted defaults for everything else:
    12. Go To Authentication Tab. See this link for an overview of the authentication types:
    13. Click Save, which will bring you to the screen below:
    14. Download the configuration file (config.inc.php) and copy it to /var/www/phpMyAdmin.
    15. You can now start using phpMyAdmin on http://192.168.1.65:8888

    Note that steps 2 & 3 simply add repository for the EPEL repository to your yum repository collection and install the repository key.

    In theory, the setup script should be able to generate the configuration file for you, but I've not been able to get it to work. Instructions can be found here if you are interested.

    Thursday, 19 January 2012

    Regional Settings in Windows 2003

    We've got a SOAP webservice that parses a string into a datetime object and today after over three months, one of our test servers starting throwing errors back.

    After I got over the shock of learning that they were promoting some code into production this weekend without letting us know, hey after all, we are only the guys who look after the app, I started digging.

    The first thing I learnt was that all the failures were due the same input date, 22/01/2012, which should have worked. Except that it didn't, because it was expecting MM/DD/YYYY format rather than DD/MM/YYYY format, in other words US date settings.

    I remembered that this issue had taken place at some point in the past and they had taken the server down. I also remember setting the regional settings to UK for the service account and bringing the server back up or at least I thought I did.

    I logged on to the server with the service account and sure enough it was set to UK settings, eh??

    So I decided to ask the Oracle, which threw this link back at me: 

    On the Avanced Settings tab:
    Click to select the Apply all settings to the current user account and to the default user profile check box to apply changes to the default user profile.
    So I did and lo and behold it started working again.

    I must say that I don't really understand why it wasn't working before, but it would seem that the default profile was having an effect, perhaps it is used by the .NET framework to determine regional settings, I'm not too sure and I can't investigate from home.

    Still quite funny to receive calls from the PM, the programme manager and then the account executive telling me that the issue needed fixing A.S.A.P. as it would result in embarrassment if the latest build wasn't promoted to production this weekend. Never mind that there was no real issue, somebody had determined that a failure had occurred and it needed fixing. This place....

    Monday, 16 January 2012

    Change Trace Logging Directory in MS Dynamics CRM 2011


    Microsoft has finally decided that we are all big boys now and that we can make some decisions, including where the trace logging files should go. The TraceDirectory key in the registry still gets summarily ignored, but it is possible to change the directory using PowerShell. It's a fairly simple process:
    1. Start PowerShell.
    2. Load the CRM PS Snap in:  Add-PSSnapin Microsoft.Crm.PowerShell
    3. Store Trace Settings into variable to allow easy editing: $trace = Get-CRMSetting TraceSettings
    4. Change Directory to your preferred value: $trace.Directory=”D:\Trace”
    5. Save Settings: Set-CRMSetting $trace
    6. You can check that the new setting has been set with: Get-CRMSetting TraceSettings
    CallStack     : True
    Categories    : *:Error
    Directory     : D:\Trace
    Enabled       : True
    FileSize      : 10
    ExtensionData : System.Runtime.Serialization.ExtensionDataObject
    Note that the directory on step 4 needs to exist.

    If you haven’t enabled trace logging, you can do it before step 4:
    $trace.Enabled =”True”
    Thank you Microsoft.

    Sunday, 15 January 2012

    Windows Azure from Windows XP

    A few days ago a colleague pointed out that thanks to our subscription to MSDN we get free access to the Microsoft cloud system, Windows Azure. So I thought I would give it a try, boy was I in for a surprise.

    After signing up and logging in, I made an attempt to get the SDK to see what all the fuss was about and this is where all the fun began. Microsoft's answer to Yum or Aptitute,  Microsoft Web Platform Installer was installed and then all the pre-requisites are installed in order, which takes an awful long time and when you think it has finished, you realized it has failed to install everything because, and I'm not kidding, IIS 7.x is needed, say what? I'm running Windows XP, why the b£$%^& h!"£ would it not check this first? I appreciate that each installer will run its own checks but why doesn't MS Web PI check this? Why isn't it clear that development on Windows XP for the Windows Azure is no longer supported, if it ever was. I sometimes dispear with Microsoft.

    You need to go to the microsoft download page, e.g. sdk 1.4 itself to check the pre-requisites as there is nothing on the Windows Azure page itself. If you click install this launches MS Web PI and then you run through the whole frustrating process.

    Saturday, 14 January 2012

    The Linux usability problem

    It seems that every time that I want to do something quickly in front of my Kubuntu Laptop it almost always turns into a bit of a nightmare. I'm quite conformable using a console, vi does not intimidate me anymore and I consider myself to be reasonably tech savvy, but Linux at home really does try my patience. 

    At work, I really don't mind if I have to spend two hours to do something that takes 3 minutes in Windows (e.g. joining a RHEL 6 box to a Windows 2003 AD); I consider it the price one pays for freedom and most of all I really do relish the challenge. If something is hard when it's finally achieved it feels like so much more of an achievement, because it is, even if in reality it isn't, you just didn't know how to do it. 
    However, when I'm at home I want things to work, I already spend 8 to 10 hours a day dealing with frustration, I don't want to do the same at home and Windows 7 just works. Just two examples that have led to loads of frustration recently:
    1. I wanted to have a look at a web page that had a java applet, which kinda works out of the box in Windows, yet I could not get it to work in Firefox and when I got it working in rekong, it did not work properly. I know there are guides to install the java plugin for firebadger but I couldn't get it to work. I also know I'm an idiot and an ignoramus for not getting to work, still. I had similar issues with Flash before I upgraded to 11.10.
    2. I acquired a Logitech webcam to do video conferencing with friends and family. I've also used it to record a few videos clowning about for said friends and family from my Windows 7 desktop. I wanted to do some clowning about in the sitting room using my kubuntu laptop but I could not get any of the various options (VLC, Mplayer,  Cheese, UVC) to work properly. No sound, would not record, would crash, etc.. Compared to plug and play, download Windows Movie Maker and off I went, it's not contest.
    I guess if I didn't work in application development/support I might enjoy the challenge at home, I know I used to, but now it's just a lot of hassle for relatively little reward, I think I'm sticking with Windows 7 for home use for the time being.

    To a some extent the problem is due to lack of manufacturer support, but seeing as Linux currently commands a 1% share of the desktop market, they figure it's not worth the hassle and thus fewer people will make the jump, thus not giving manufacturers a reason to invest in Linux, in other words a classical catch-22 situation.