Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Sunday, July 13, 2014

Android Drawable Cache (Xamarin / Mono)

The code below is useful if you need to cache images in Android. Weak references are used to help protect against memory leaks.

Drawable Cache Class:
public class DrawableCache
{
 public Context Context { get; set; }
 Dictionary<object, WeakReference<Drawable.ConstantState>> _cache = new Dictionary<object, WeakReference<Drawable.ConstantState>>();

 public DrawableCache(Context context)
 {
  Context = context;
 }

 public void Put(object key, Drawable drawable)
 {
  _cache[key] = new WeakReference<Drawable.ConstantState>(drawable.GetConstantState(), false);
 }

 public Drawable Get(object key)
 {
  WeakReference<Drawable.ConstantState> value;
  if (_cache.TryGetValue(key, out value))
  {
   Drawable.ConstantState target;
   if (value.TryGetTarget(out target))
   {
    return target.NewDrawable(Context.Resources);
   }
   _cache.Remove(key);
  }
  return null;
 }
}
Optional Drawable Cache Key class
public class DrawableCacheKey
{
 public int Key { get; set; }
 public int Flags { get; set; }

 public DrawableCacheKey(int key, int flags)
 {
  Key = key;
  Flags = flags;
 }

 public override int GetHashCode()
 {
  int hash = 17;
  hash = hash * 23 + Key.GetHashCode();
  hash = hash * 23 + Flags.GetHashCode();
  return hash;
 }

 public override bool Equals(object obj)
 {
  if (this == obj)
   return true;
  if (obj == null)
   return false;
  var cast = obj as DrawableCacheKey;
  return cast != null && Key == cast.Key && Flags == cast.Flags;
 }
}

Wednesday, February 22, 2012

Network Reachability Test for .NET

The code below is used to test if a specific server and port is reachable. This code uses a socket to connect to the server and doesn't wait for a response so it is quicker than using a full WebClient request, etc. This code will return true if the server was reachable and false if it was not (within the provided timeout).

public class NetworkReachability
{
 public static bool IsReachable(string url, int timeout)
 {
  return IsReachable(new Uri(url), timeout);
 }

 public static bool IsReachable(Uri uri, int timeout)
 {
  return IsReachable(uri.Host, uri.Port, timeout);
 }

 public static bool IsReachable(string host, int port, int timeout)
 {
  if (AppConfig.IsDebugCompile)
  {
   Thread.Sleep(250);
   return true;
  }

  try
  {
   using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
   {
    var handler = new ManualResetEvent(false);
    var e = new SocketAsyncEventArgs();
    e.RemoteEndPoint = new DnsEndPoint(host, port);
    e.Completed += delegate { handler.Set(); };
    if (!socket.ConnectAsync(e))
     handler.Set();

    return handler.WaitOne(timeout) &&
     e.ConnectByNameError == null &&
     socket.Connected;
   }
  }
  catch
  {
   return false;
  }
 }
}

Friday, November 4, 2011

Generic Method For Converting From DBNull

public static T FromDB<T>(object o)
{
   return o is DBNull ? default(T) : (T)o;
}

The method above is written in C# using generics. This method is used to cast weakly typed objects returned from a DataRow to strongly typed objects and it will automatically handle the conversion of DBNull. This method can also be used with nullable types which is convenient since capturing null values is often important when querying databases.

Below is a full example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            object i1 = 7;
            object i2 = DBNull.Value;
            object i3 = 3;
            object i4 = DBNull.Value;
            object i5 = "TEST";
            object i6 = DBNull.Value;

            int o1 = FromDB<int>(i1);
            int o2 = FromDB<int>(i2);
            int? o3 = FromDB<int?>(i3);
            int? o4 = FromDB<int?>(i4);
            string o5 = FromDB<string>(i5);
            string o6 = FromDB<string>(i6);

            Console.WriteLine("o1 = {0}", o1); //can't be null since its value type
            Console.WriteLine("o2 = {0}", o2); //can't be null since its value type
            Console.WriteLine("o3 = {0} {1}", o3, o3 == null ? "(NULL)" : "");
            Console.WriteLine("o4 = {0} {1}", o4, o4 == null ? "(NULL)" : "");
            Console.WriteLine("o5 = {0} {1}", o5, o5 == null ? "(NULL)" : "");
            Console.WriteLine("o6 = {0} {1}", o6, o6 == null ? "(NULL)" : "");
        }

        public static T FromDB<T>(object o)
        {
            return o is DBNull ? default(T) : (T)o;
        }
    }
}

The output would be:

o1 = 7
o2 = 0
o3 = 3
o4 = (NULL)
o5 = TEST
o6 = (NULL)

Monday, September 19, 2011

How to Connect to DB2 with .NET

First you must install either the IBM Data Server Client or the IBM Data Server Runtime Client. The IBM Data Server Client has some additional developer tools but they are optional, so if you are searching for the most lightweight install then choose the IBM Data Server Runtime Client.

Next you must determine if a license is required. If you are connecting through a DB2 Connect Gateway then a license is not required, but if you are connecting directly to the DB2 Database then a license must be activated on the client computer.

To activate the license you must locate the db2conpe.lic file on your DB2 / DB2 Connect install CD. Once you have located this file, copy it to the client computer in the following directory: "C:\Program Files\IBM\SQLLIB\BIN" (location where your DB2 Client was installed). Now open a command prompt and change the directory to "C:\Program Files\IBM\SQLLIB\BIN" and execute this command: "db2licm -a db2conpe.lic". It should say that your license was successfully activated. You can verify this by typing "db2licm -l".

Now you are ready to start programming. Open Visual Studio and start a new console project. Before you start add a new reference (Project -> Add Reference) and browse to "C:\Program Files\IBM\SQLLIB\BIN\netf20\IBM.Data.DB2.dll".

Now copy and paste this code into your class file:

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using IBM.Data.DB2;

namespace ConnectToDB2
{
    class Program
    {
        static void Main(string[] args)
        {
            string sql = "SELECT * FROM SYSIBM.SYSDUMMY1";
            DB2Connection con = new DB2Connection("Database=<DATABASE>;UserID=<USER_ID>;Password=<PASSWORD>;Server=<SERVER>:<PORT>");
            con.Open();

            DB2Command cmd = new DB2Command(sql, con);
            DB2DataReader reader = cmd.ExecuteReader();

            while (reader.Read())
            {
                Console.WriteLine(reader.GetString(0));
            }
        }
    }
}

Obviously replace the placeholders in the connection string with valid values.