Archive for the ‘Tech Recipes’ Category

How to connect a Debian machine to a Windows 2008 PPTP VPN

  1. #apt-get install pptp-linux
  2. #apt-get install ca-certificates
  3. Copy certificate to /usr/share/ca-certificates . If your certificate extension is .cer then change it to .crt
  4. #dpkg-reconfigure ca-certificates //Select your certificate from the list
  5. Follow the pppt client debian configuration instructions on http://pptpclient.sourceforge.net/howto-debian.phtml
  6. Create a /etc/ppp/ip-up.d/ppp0 with routing information:
    #!/bin/sh
    /sbin/route add -net 192.168.1.0 netmask 255.255.255.0 dev ppp0
  7. #chmod +x /etc/ppp/ip-up.d/ppp0
  8. Add the next lines to you /etc/ppp/peers/provider file if you want your connection to be reconnected if it fails and if you want to assign a static ip address to your connection
    persist
    192.168.1.10:

How to install Linux Integration Services Version 2.1 on a Hyper-V virtual machine running Debian

Linux Integration Services Version 2.1 now has support for Timesync, Integrated Shutdown and Symmetric Multi-Processing (SMP) up to 4 virtual processors.

  1. Get the Linux Integration Services 2.1 Beta from https://connect.microsoft.com/site495
  2. Extract the files and insert the .iso as a disk in your virtual machine
  3. Now the hard/long part, update your Kernel with version 2.6.27.47 (This is out of scope, so you will have to look for info on how to do this).
  4. Reboot and choose your new Kernel
  5. #mount /cdrom
  6. #mkdir /opt/linux_ic_v21_rc
  7. #cp /cdrom/* /opt/linux_ic_v21_rc -R
  8. #mkdir /etc/sysconfig/network
  9. # cd /opt/linux_ic_v21_rc  -R
  10. Modify the Mafile file replacing all the occurrences of —reload-rules with —reload_rules
  11. Modify the scripts/updateinitrd.pl file commenting lines 79 to 87 and adding this line after that $initrdfile = “/boot/initrd.img-2.6.27.47″;  
  12. Modify scripts/updategrub.pl file replacing line 55 with $grubfile = “/boot/grub/menu.lst”;
  13. #apt-get install chkconfig
  14. #make
  15. #make install
  16. Modify your /etc/init.d/vmbus file commenting lines 55 to 61 and 108 to 112. Also replace line 73 with return 0 and 75 with return 1
  17. Modify your /etc/network/interfaces file replacing eth0 with seth0
  18. Modify your /etc/initramfs-tools/modules file adding a vmbus line and a netvsc line
  19. #update-initramfs –u –k 2.6.27.47
  20. Shutdown your virtual machine #init 0
  21. Replace your legacy network adapter with a normal Network adapter copying your old adapter’s MAC to your new adapter
  22. Start your virtual machine
  23. That’s it, now you have a Debian Hyper-V virtual machine with Integration Services.

How to shrink a database log file in SQL Server 2008

ALTER DATABASE database SET RECOVERY SIMPLE;
dbcc shrinkfile (database_log, 1);
ALTER DATABASE database SET RECOVERY FULL;

How to use SSL in a WCF service

1. Enable SSL configuration on your site
2. Set your binding security mode to Transport.
3. Set you service behavior serviceAuthorization PrincipalPermissionMode to None.

public class ServiceHostFactory : WebServiceHostFactory
    {
        protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
        {
            ServiceHost host = new ServiceHost(typeof(Services), baseAddresses);
            host.Authorization.PrincipalPermissionMode = PrincipalPermissionMode.None;
            ServiceEndpoint endpoint = host.AddServiceEndpoint(typeof(IServices), new WebHttpBinding(WebHttpSecurityMode.Transport), "");
            endpoint.Behaviors.Add(new WebHttpBehaviorEx());
            return host;
        }
    }

How to publish WCF services using IIS6

1. C:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis –i
2. C:\Windows\Microsoft.NET\Framework\v3.0\Windows Communication Foundation\ServiceModelReg.exe –i
3. Do all the things you normally do on IIS7, you are all set.

How to go beyond PUT and DELETE limitations on RESTful Scenarios

One of the biggest problems you will have while implementing RESTful services is that most of today’s browsers and firewalls will not allow PUT and DELETE requests. An easy way to fix this is to add a custom HTTP header to your post requests and send the real method in there. Since Google is using “X-HTTP-Method-Override” it looks like a smart choice to follow that pattern and use it too.

This simple jquery code shows how to do it in the client side:

$.ajax({
    type: "POST",
    url: serviceURL,
    data: "data",
    success: function(data, textStatus) { alert("success"); },
    error: function(xhr, status, error) { alert("error"); },
    beforeSend: function(xhr) { xhr.setRequestHeader("X-HTTP-Method-Override", "DELETE"); }
});

This C# code shows how to use the custom header in a WCF server:

public String PostProxy(String data)
{
    switch (HttpContext.Current.Request.Headers["X-HTTP-Method-Override"])
    {
        case "PUT": return Add(data);
        case "DELETE": return Delete(data);
        default: return Update(data);
    }
}

Big files transfer using WCF services

If you need to receive files bigger than 4MB using WCF services you have to change the default configuration in your web.config file to allow the size required.

<system.web>
    <httpRuntime maxRequestLength="131072" />
</system.web>

Note: this should work for any ASP application.

Declarative permissions for WCF services

When you develop WCF services you might want to have some protected and unprotected methods on the same service. To do this you will need to do as follows.
Publish your service on an unprotected area of your site; change your web.config file to do it:

<location path="services">
    <system.web>
        <authorization>
            <allow users="*" />
        </authorization>
    </system.web>
</location>

Add this line of code to your service constructor method:

public Service()
{
    Thread.CurrentPrincipal = HttpContext.Current.User;
}

Finally use declarative permissions on the service methods you want to protect:

[PrincipalPermission(SecurityAction.Demand)]
public String YourMethod()
{
    return String.Empty;
}

How to change ASP MembershipProvider ResetPassword method to provide easier passwords

First of all you don’t. You have to change the GeneratePassword method used in the ResetPassword method. To do this you need to write your own membership provider and override it like in this example:

public class MembershipProvider : System.Web.Security.SqlMembershipProvider
{
    const String UPPER = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    const String LOWER = "abcdefghijklmnopqrstuvwxyz";
    const String NUMBERS = "1234567890";
    const String SPECIAL = "*$-+?&=!%/";

    public override string GeneratePassword()
    {
        Random rand = new Random();
        String password = "";
        List<String> data = new List<String>();
        for (int i = 0; i < 10; i++)
        {
            if ( i < 3 ) data.Add(UPPER[rand.Next(UPPER.Length)].ToString());
            else if ( i < 6 ) data.Add(LOWER[rand.Next(LOWER.Length)].ToString());
            else if ( i < 8 ) data.Add(NUMBERS[rand.Next(NUMBERS.Length)].ToString());
            else if ( i < 10 ) data.Add(SPECIAL[rand.Next(SPECIAL.Length)].ToString());
        }
        while (data.Count > 0)
        {
            int pos = rand.Next(data.Count);
            password += data[pos];
            data.RemoveAt(pos);
        }
        return password;
    }
}

Note: After you do this you will not be able to use the IIS7 management for your users.

Calling Facebook RESTful API using C# (Without Microsoft Facebook SDK)

To continue with our previous posts about Facebook I’m going explain how to use the RESTful API from C# code. This time I’m writing a console application to read user Facebook’s statuses. This illustrates that you can really use the RESTful API from any application including desktop.
A very important thing you need to do before this code works is to ask your user for authorization to read his stream with offline access as shown in this post. After your user grants your application to have offline access you can read his session_key and use it everywhere because it will never expire.

You can download the source code for this post here.

First we need to write a Class that mimics Status FQL table.

public class Status
{
    public String status_id { get; set; }
    public String time { get; set; }
    public String source { get; set; }
    public String message { get; set; }
}

Then we create a method to generate our data signature.

public static String GetSignature(Dictionary<String, String> parameters)
{
    MD5 md5 = MD5.Create();
    String data = "";
    String[] keys = parameters.Keys.OrderBy(k => k.ToString()).ToArray();
    for (int i = 0; i < keys.Length; i++)
    {
        String key = keys[i];
        String value = parameters[key];
        data += key + "=" + value;
    }
    data += "APPLICATION_SECRET";
    byte[] bytes = md5.ComputeHash(Encoding.UTF8.GetBytes(data));
    String signature = "";
    foreach (byte b in bytes) signature += b.ToString("x2");
    return signature;
}

After that we just build our post data, post our request, read our response and deserialize the status objects.

static void Main(string[] args)
{
    Dictionary<String, String> parameters = new Dictionary<String, String>();
    parameters.Add("format", "json");
    parameters.Add("method", "Fql.query");
    parameters.Add("query", "select status_id, time, source, message from status where uid = USER_ID");
    parameters.Add("session_key", "SESSION_KEY");
    parameters.Add("api_key", "API_KEY");
    parameters.Add("v", "1.0");
    parameters.Add("call_id", DateTime.Now.Ticks.ToString());
    parameters.Add("sig", GetSignature(parameters));
    String postData = "";
    for (int i = 0; i < parameters.Keys.Count; i++)
    {
        String key = parameters.Keys.ElementAt(i);
        String value = parameters[key];
        String param = key + "=" + HttpUtility.UrlEncode(value);
        postData += param;
        if (i < parameters.Keys.Count - 1) postData += "&";
    }
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://api.facebook.com/restserver.php");
    request.Method = "POST";
    request.ContentType = "application/x-www-form-urlencoded";
    StreamWriter writer = new StreamWriter(request.GetRequestStream());
    writer.Write(postData);
    writer.Close();
    DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Status[]));
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    Status[] statuses = (Status[])serializer.ReadObject(response.GetResponseStream());
    foreach (Status s in statuses)
    {
        DateTime time = new DateTime(long.Parse(s.time));
        Console.WriteLine(time.ToString() + ", " + s.message);
    }
    Console.ReadLine();
}

Note that you can use this approach to call any method in the RESTful API, not to just make FQL queries.

Return top

Idea Manglar

Idea Manglar is a private held startup located in Cali, Colombia, South America. It began as an idea lab and quickly became an intuitive and innovative software developer. 1136 and Dynamic Crystal will be the first ideas going online on 2010. http://www.manglar.com