This project is read-only.

Project Description

This is a small base framework for MVVM in winRT,Windows Phone, WPF and Silverlight. Also included some necessary extension methods.

NuGet

Also WinRT (For Windows 8 Store Applciations) version is available at NuGet http://www.nuget.org/packages/VMBase/

Details

As a developer you could build your viewmodel according to the our VMBase and VMPageBase.

VMBase

Inheriting VMBase to your ViewModels of your project will following abilities to your View Models:
  • Marshaling : VMBase objects could be marshaled as unmanaged memory bytes and could be read from unmanaged bytes.
  • XML : VMBase objects could be serialized to XML bytes and XML Strings and cloud deserialized form XML strings and XML bytes.
  • Json : VMBase objects could be serialized to JSON bytes and JSON Strings and cloud deserialized form JSON strings and JSON bytes. To do that Newtonsoft Json.NET has been used.
  • Storage: VMBase objects could be save themselves to the local data folder as serialized XML files. Also there are static methods in VMBase could save string and byte arrays in the data folder.
  • There are also virtual methods Initialize, Suspend and Clone. Those could be override in the Child class and used for registering / unregistering event handlers and resources.
  • Also INotifyPropertyChanged Interface is properly implemented. With public void NotifyPropertyChanged(string info) method any MVVM property can be notified in the setter.

ByteHelper

There is a static extension class called Byte Helper in it. There is good functions in that about Hex, Byte and String conversions and calculations.
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Threading.Tasks;
using sStream = Windows.Storage.Streams;
using storage = Windows.Storage;

namespace WinRTBase
{
    public static class ByteHepler
    {
        #region Compression
        private async static Task<byte[]> compress(byte[] raw)
        {
            using (MemoryStream memory = new MemoryStream())
            {
                using (GZipStream gzip = new GZipStream(memory, CompressionMode.Compress, true))
                {
                    await gzip.WriteAsync(raw, 0, raw.Length);
                }
                await memory.FlushAsync();
                return memory.ToArray();
            }
        }
        public static async Task<byte[]> CompressAsync(this byte[] raw) { return await compress(raw); }

        private async static Task<byte[]> decompress(byte[] gzip)
        {
            // Create a GZIP stream with decompression mode.
            // ... Then create a buffer and write into while reading from the GZIP stream.
            using (GZipStream stream = new GZipStream(new MemoryStream(gzip), CompressionMode.Decompress))
            {
                const int size = 4096;
                byte[] buffer = new byte[size];
                using (MemoryStream memory = new MemoryStream())
                {
                    int count = 0;
                    do
                    {
                        count = await stream.ReadAsync(buffer, 0, size);
                        if (count > 0)
                            await memory.WriteAsync(buffer, 0, count);
                    }
                    while (count > 0);
                    return memory.ToArray();
                }
            }
        }
        public static async Task<byte[]> DeCompressAsync(this byte[] raw) { return await decompress(raw); }
        #endregion
        #region Byte
        public static byte[] SubBytes(this byte[] bytes, int start, int lenght)
        {
            byte[] retVal = new byte[lenght];
            for (int i = start; i < bytes.Length; i++)
                retVal[i - start] = bytes[i];
            return retVal;
        }
        public static IEnumerable<byte[]> SplitWithBuffer(this byte[] bytes, int buffer = 65535)
        {
            for (var i = 0; i < bytes.Length; i += buffer)
                yield return bytes.SubBytes(i, Math.Min(buffer, bytes.Length - i));
        }
        public static byte[] CombineFromBuffer(this IEnumerable<byte[]> byteBufferCollection)
        {
            List<byte> retVal = new List<byte>();
            foreach (var bytes in byteBufferCollection)
                retVal.AddRange(bytes);
            return retVal.ToArray();
        }
        #endregion
        #region Hex
        public static string ToHex(this byte[] bytes)
        {
            char[] c = new char[bytes.Length * 2];
            byte b;
            for (int bx = 0, cx = 0; bx < bytes.Length; ++bx, ++cx)
            {
                b = ((byte)(bytes[bx] >> 4));
                c[cx] = (char)(b > 9 ? b + 0x37 + 0x20 : b + 0x30);

                b = ((byte)(bytes[bx] & 0x0F));
                c[++cx] = (char)(b > 9 ? b + 0x37 + 0x20 : b + 0x30);
            }
            return new string(c);
        }
        public static IEnumerable<string> ToHexWithBuffer(this byte[] bytes, int buffer = 65535)
        {
            int maxStrLen = buffer / 2;
            string hexStr = bytes.ToHex();
            IEnumerable<string> retVal = hexStr.SplitInParts(maxStrLen);
            return retVal;
        }

        public static byte[] HexToBytes(this string str)
        {
            if (str.Length == 0 || str.Length % 2 != 0)
                return new byte[0];

            byte[] buffer = new byte[str.Length / 2];
            char c;
            for (int bx = 0, sx = 0; bx < buffer.Length; ++bx, ++sx)
            {
                // Convert first half of byte
                c = str[sx];
                buffer[bx] = (byte)((c > '9' ? (c > 'Z' ? (c - 'a' + 10) : (c - 'A' + 10)) : (c - '0')) << 4);

                // Convert second half of byte
                c = str[++sx];
                buffer[bx] |= (byte)(c > '9' ? (c > 'Z' ? (c - 'a' + 10) : (c - 'A' + 10)) : (c - '0'));
            }

            return buffer;
        }
        public static byte[] BufferedHexToBytes(this IEnumerable<string> str, int buffer = 65535)
        {
            string myHexStr = string.Concat(str.ToArray());
            return myHexStr.HexToBytes();
        }
        #endregion
        #region Cryptology
        /// <summary>
        /// <param name="str">Unique key for encryption/decryption</param>
        /// <param name="key"></param>
        /// <param name="algorithm">Use Windows.Security.Cryptography.Core.SymmetricAlgorithmNames Class</param>
        /// <param name="hashAlgorithm">Use Windows.Security.Cryptography.Core.HashAlgorithmNames Class</param>
        /// <returns>Returns encrypted bytes.</returns>
        public static string Encrypt(this string str, string key, string algorithm, string hashAlgorithm)
        {
            return Cryptology.Algorithms.Encrypt(str, key, algorithm, hashAlgorithm);
        }
        /// <summary>
        /// <param name="str">Unique key for encryption/decryption</param>
        /// <param name="key"></param>
        /// <param name="algorithm">Use Windows.Security.Cryptography.Core.SymmetricAlgorithmNames Class</param>
        /// <param name="hashAlgorithm">Use Windows.Security.Cryptography.Core.HashAlgorithmNames Class</param>
        /// <returns>Returns decrypted bytes.</returns>
        public static string Decrypt(this string str, string key, string algorithm, string hashAlgorithm)
        {
            return Cryptology.Algorithms.Decrypt(str, key, algorithm, hashAlgorithm);
        }
        /// <summary>
        /// <param name="str"></param>
        /// <param name="key">Unique key for encryption/decryption</param>
        /// <param name="algorithm">Use Windows.Security.Cryptography.Core.SymmetricAlgorithmNames Class</param>
        /// <param name="hashAlgorithm">Use Windows.Security.Cryptography.Core.HashAlgorithmNames Class</param>
        /// <returns>Returns encrypted bytes.</returns>
        public static byte[] Encrypt(this byte[] bytes, string key, string algorithm, string hashAlgorithm)
        {
            return Cryptology.Algorithms.Encrypt(bytes, key, algorithm, hashAlgorithm);
        }
        /// <summary>
        /// <param name="str"></param>
        /// <param name="key">Unique key for encryption/decryption</param>
        /// <param name="algorithm">Use Windows.Security.Cryptography.Core.SymmetricAlgorithmNames Class</param>
        /// <param name="hashAlgorithm">Use Windows.Security.Cryptography.Core.HashAlgorithmNames Class</param>
        /// <returns>Returns decrypted bytes.</returns>
        public static byte[] Decrypt(this byte[] bytes, string key, string algorithm, string hashAlgorithm)
        {
            return Cryptology.Algorithms.Decrypt(bytes, key, algorithm, hashAlgorithm);
        }
        #endregion
        #region String
        public static IEnumerable<String> SplitInParts(this String s, Int32 partLength)
        {
            if (s == null)
                throw new ArgumentNullException("s");
            if (partLength <= 0)
                throw new ArgumentException("Part length has to be positive.", "partLength");

            for (var i = 0; i < s.Length; i += partLength)
                yield return s.Substring(i, Math.Min(partLength, s.Length - i));
        }
        public static int ToInt(this string str)
        {
            int retVal;
            int.TryParse(str, out retVal);
            return retVal;
        }
        public static double ToDouble(this string str)
        {
            double retVal;
            double.TryParse(str, out retVal);
            return retVal;
        }
        public static bool IsNumeric(this string str)
        {
            foreach (char c in str)
                if (!char.IsNumber(c))
                    return false;

            return true;
        }
        public static bool IsDouble(this string str)
        {
            double retVal;
            return double.TryParse(str, out retVal);
        }
        public static string TrimLast(this string str, int length)
        {
            return str.Length > length ? str.Substring(0, length) + "..." : str;
        }
        #endregion
        #region File
        public static async Task<byte[]> GetBytesAsync(this storage.StorageFile file)
        {
            sStream.IRandomAccessStream fileStream = await file.OpenAsync(storage.FileAccessMode.Read);
            var reader = new sStream.DataReader(fileStream.GetInputStreamAt(0));
            await reader.LoadAsync((uint)fileStream.Size);
            byte[] bytes = new byte[fileStream.Size];
            reader.ReadBytes(bytes);
            return bytes;
        }
        #endregion
    }
}

Cryptography

There is a good Cryptography wrapper for winRT. A lot of Encryption methods are implemented like static extensions. And used like value.Encrypt();
using System;
using System.Threading.Tasks;
using Windows.Security.Cryptography;
using Windows.Security.Cryptography.Core;
using Windows.Security.Cryptography.DataProtection;
using Windows.Storage.Streams;

namespace WinRTBase
{
    public static class Cryptology
    {
        /// <summary>
        /// .NET Framework Cryptography Model
        /// http://msdn.microsoft.com/en-us/library/0ss79b2x.aspx
        /// </summary>
        public sealed class Algorithms
        {
            /// <summary>
            /// Encrypt bytes using dual encryption method. Returns an encrypted bytes.
            /// </summary>
            /// <param name="toEncrypt">Bytes to be encrypted</param>
            /// <param name="key">Unique key for encryption/decryption</param>
            /// <param name="algorithm">Use Windows.Security.Cryptography.Core.SymmetricAlgorithmNames Class</param>
            /// <param name="hashAlgorithm">Use Windows.Security.Cryptography.Core.HashAlgorithmNames Class</param>
            /// <returns>Returns encrypted bytes.</returns>
            public static byte[] Encrypt(byte[] toEncrypt, string key, string algorithm, string hashAlgorithm)
            {
                // Get the MD5 key hash (you can as well use the binary of the key string)
                IBuffer keyHash = getHash(key, hashAlgorithm);
                // Create a buffer that contains the encoded message to be encrypted.
                IBuffer toDecryptBuffer = CryptographicBuffer.CreateFromByteArray(toEncrypt);
                // Open a symmetric algorithm provider for the specified algorithm.
                SymmetricKeyAlgorithmProvider provider = SymmetricKeyAlgorithmProvider.OpenAlgorithm(algorithm);
                // Create a symmetric key.
                CryptographicKey symetricKey = provider.CreateSymmetricKey(keyHash);
                // The input key must be securely shared between the sender of the cryptic message
                // and the recipient. The initialization vector must also be shared but does not
                // need to be shared in a secure manner. If the sender encodes a message string
                // to a buffer, the binary encoding method must also be shared with the recipient.
                IBuffer buffEncrypted = CryptographicEngine.Encrypt(symetricKey, toDecryptBuffer, null);
                // Convert the encrypted buffer to a string (for display).
                // We are using Base64 to convert bytes to string since you might get unmatched characters
                // in the encrypted buffer that we cannot convert to string with UTF8.
                byte[] retVal;
                CryptographicBuffer.CopyToByteArray(buffEncrypted, out retVal);
                return retVal;
            }
            /// <summary>
            /// Encrypt a string using dual encryption method. Returns an encrypted text.
            /// </summary>
            /// <param name="toEncrypt">String to be encrypted</param>
            /// <param name="key">Unique key for encryption/decryption</param>
            /// <param name="algorithm">Use Windows.Security.Cryptography.Core.SymmetricAlgorithmNames Class</param>
            /// <param name="hashAlgorithm">Use Windows.Security.Cryptography.Core.HashAlgorithmNames Class</param>
            /// <returns>Returns encrypted string.</returns>
            public static string Encrypt(string toEncrypt, string key, string algorithm, string hashAlgorithm)
            {
                // Get the MD5 key hash (you can as well use the binary of the key string)
                IBuffer keyHash = getHash(key, hashAlgorithm);
                // Create a buffer that contains the encoded message to be encrypted.
                IBuffer toDecryptBuffer = CryptographicBuffer.ConvertStringToBinary(toEncrypt, BinaryStringEncoding.Utf8);
                // Open a symmetric algorithm provider for the specified algorithm.
                SymmetricKeyAlgorithmProvider provider = SymmetricKeyAlgorithmProvider.OpenAlgorithm(algorithm);
                // Create a symmetric key.
                CryptographicKey symetricKey = provider.CreateSymmetricKey(keyHash);
                // The input key must be securely shared between the sender of the cryptic message
                // and the recipient. The initialization vector must also be shared but does not
                // need to be shared in a secure manner. If the sender encodes a message string
                // to a buffer, the binary encoding method must also be shared with the recipient.
                IBuffer buffEncrypted = CryptographicEngine.Encrypt(symetricKey, toDecryptBuffer, null);
                // Convert the encrypted buffer to a string (for display).
                // We are using Base64 to convert bytes to string since you might get unmatched characters
                // in the encrypted buffer that we cannot convert to string with UTF8.
                string strEncrypted = CryptographicBuffer.EncodeToBase64String(buffEncrypted);
                return strEncrypted;
            }

            /// <summary>
            /// Decrypt a string using dual encryption method. Return a Decrypted clear string
            /// </summary>
            /// <param name="cipherString">Encrypted string</param>
            /// <param name="key">Unique key for encryption/decryption</param>
            /// <returns>Returns decrypted text.</returns>
            public static string Decrypt(string cipherString, string key, string algorithm, string hashAlgorithm)
            {
                // Get the key hash (you can as well use the binary of the key string)
                IBuffer keyHash = getHash(key, hashAlgorithm);
                // Create a buffer that contains the encoded message to be decrypted.
                IBuffer toDecryptBuffer = CryptographicBuffer.DecodeFromBase64String(cipherString);
                // Open a symmetric algorithm provider for the specified algorithm.
                SymmetricKeyAlgorithmProvider provider = SymmetricKeyAlgorithmProvider.OpenAlgorithm(algorithm);
                // Create a symmetric key.
                CryptographicKey symetricKey = provider.CreateSymmetricKey(keyHash);
                IBuffer buffDecrypted = CryptographicEngine.Decrypt(symetricKey, toDecryptBuffer, null);
                string strDecrypted = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, buffDecrypted);
                return strDecrypted;
            }
            /// <summary>
            /// 
            /// </summary>
            /// <param name="cipherBytes">Encrypted string</param>
            /// <param name="key"></param>
            /// <param name="algorithm"></param>
            /// <param name="hashAlgorithm"></param>
            /// <returns></returns>
            public static byte[] Decrypt(byte[] cipherBytes, string key, string algorithm, string hashAlgorithm)
            {
                // Get the key hash (you can as well use the binary of the key string)
                IBuffer keyHash = getHash(key, hashAlgorithm);
                // Create a buffer that contains the encoded message to be decrypted.
                IBuffer toDecryptBuffer = CryptographicBuffer.CreateFromByteArray(cipherBytes);
                // Open a symmetric algorithm provider for the specified algorithm.
                SymmetricKeyAlgorithmProvider provider = SymmetricKeyAlgorithmProvider.OpenAlgorithm(algorithm);
                // Create a symmetric key.
                CryptographicKey symetricKey = provider.CreateSymmetricKey(keyHash);
                IBuffer buffDecrypted = CryptographicEngine.Decrypt(symetricKey, toDecryptBuffer, null);
                byte[] retVal;
                CryptographicBuffer.CopyToByteArray(buffDecrypted, out retVal);
                return retVal;
            }
        }

        #region Descriptors
        private const string _LOCAL = "LOCAL";
        private const string _WEBCREDENTIALS = "WEBCREDENTIALS";

        public static string UserDescriptor { get { return _LOCAL + "=user"; } }
        public static string MachineDescriptor { get { return _LOCAL + "=machine"; } }
        public static string WebCredentialsDescriptor(string password, string url) { return _WEBCREDENTIALS + "=" + password + "," + url; }
        public static string WebCredentialsDescriptor(string password) { return WebCredentialsDescriptor(password, string.Empty); }
        #endregion
        #region Example
        public static async void ProtectExample()
        {
            // Initialize function arguments.
            String strMsg = "This is a message to be protected.";
            String strDescriptor = "LOCAL=user";
            BinaryStringEncoding encoding = BinaryStringEncoding.Utf8;
            // Protect a message to the local user.
            IBuffer buffProtected = await SampleProtectAsync(strMsg, strDescriptor, encoding);
            // Decrypt the previously protected message.
            String strDecrypted = await SampleUnprotectData(buffProtected, encoding);
        }
        public static async Task<IBuffer> SampleProtectAsync(String strMsg, String strDescriptor, BinaryStringEncoding encoding)
        {
            // Create a DataProtectionProvider object for the specified descriptor.
            DataProtectionProvider Provider = new DataProtectionProvider(strDescriptor);
            // Encode the plaintext input message to a buffer.
            encoding = BinaryStringEncoding.Utf8;
            IBuffer buffMsg = CryptographicBuffer.ConvertStringToBinary(strMsg, encoding);
            // Encrypt the message.
            IBuffer buffProtected = await Provider.ProtectAsync(buffMsg);
            // Execution of the SampleProtectAsync function resumes here
            // after the awaited task (Provider.ProtectAsync) completes.
            return buffProtected;
        }
        public static async Task<String> SampleUnprotectData(IBuffer buffProtected, BinaryStringEncoding encoding)
        {
            // Create a DataProtectionProvider object.
            DataProtectionProvider Provider = new DataProtectionProvider();
            // Decrypt the protected message specified on input.
            IBuffer buffUnprotected = await Provider.UnprotectAsync(buffProtected);
            // Execution of the SampleUnprotectData method resumes here
            // after the awaited task (Provider.UnprotectAsync) completes
            // Convert the unprotected message from an IBuffer object to a string.
            String strClearText = CryptographicBuffer.ConvertBinaryToString(encoding, buffUnprotected);
            // Return the plaintext string.
            return strClearText;
        }
        #endregion
        #region IBuffer
        private static string iBufferToString(IBuffer buff)
        {
            //BinaryStringEncoding encoding = BinaryStringEncoding.Utf16BE;
            //return CryptographicBuffer.ConvertBinaryToString(encoding, buff);
            return CryptographicBuffer.EncodeToHexString(buff);
        }
        public static string IBufferToString(this IBuffer buff)
        {
            return iBufferToString(buff);
        }

        private static IBuffer StringToIBuffer(string str)
        {
            //BinaryStringEncoding encoding = BinaryStringEncoding.Utf16LE;
            //return CryptographicBuffer.ConvertStringToBinary(str, encoding);
            return CryptographicBuffer.DecodeFromHexString(str);
        }
        public static IBuffer ToIBuffer(this string str)
        {
            return StringToIBuffer(str);
        }
        private static IBuffer getHash(string key, string hashAlgo)
        {
            // Convert the message string to binary data.
            IBuffer buffUtf8Msg = CryptographicBuffer.ConvertStringToBinary(key, BinaryStringEncoding.Utf8);
            // Create a HashAlgorithmProvider object.
            HashAlgorithmProvider objAlgProv = HashAlgorithmProvider.OpenAlgorithm(hashAlgo);
            // Hash the message.
            IBuffer buffHash = objAlgProv.HashData(buffUtf8Msg);
            // Verify that the hash length equals the length specified for the algorithm.
            if (buffHash.Length != objAlgProv.HashLength)
                throw new Exception("There was an error creating the hash");

            return buffHash;
        }
        #endregion
    }
}

Analitics

There are good 2D calculation methods are implemented in the framework
using System;
using System.Collections.Generic;
using Windows.Foundation;
using Windows.UI.Xaml.Shapes;

namespace WinRTBase
{
    public sealed class Analitics
    {
        /// <summary>
        /// returns whether a point is on the line
        /// </summary>
        /// <param name="l">the line</param>
        /// <param name="p">the point</param>
        /// <returns></returns>
        public static bool IsPointOnTheLine(Line l, Point p, int precision)
        {
            return Math.Round(Math.Round(l.X2 - l.X1, precision) / Math.Round(l.Y2 - l.Y1, precision), precision) == Math.Round(Math.Round(l.X2 - p.X, precision) / Math.Round(l.Y2 - p.Y, precision), precision)
                    &&
                   (l.X2 >= p.X && p.X >= l.X1 || l.X1 >= p.X && p.X >= l.X2)
                    &&
                   (l.Y2 >= p.Y && p.Y >= l.Y1 || l.Y1 >= p.Y && p.Y >= l.Y2);
        }

        /// <summary>
        /// Returns wether 2 lines are collided and the collision point
        /// </summary>
        /// <param name="l1">Line 1</param>
        /// <param name="l2">Line 2</param>
        /// <param name="useBoundaries">use Lines as Line Segments</param>
        /// <returns>Point of collision</returns>
        public static Nullable<Point> IntersectionPoint(Line l1, Line l2, bool useBoundaries)
        {
            double[] x = new double[6];
            double[] y = new double[6];
            double[] m = new double[3];

            x[1] = l1.X1; x[2] = l1.X2; x[4] = l2.X1; x[5] = l2.X2;
            y[1] = l1.Y1; y[2] = l1.Y2; y[4] = l2.Y1; y[5] = l2.Y2;


            if ((x[2] != x[1]) && (x[5] != x[4]))
            {
                m[1] = (y[2] - y[1]) / (x[2] - x[1]);
                m[2] = (y[5] - y[4]) / (x[5] - x[4]);
                x[3] = (x[1] * m[1] - y[1] - x[4] * m[2] + y[4]) / (m[1] - m[2]);
                y[3] = (x[3] - x[1]) * m[1] + y[1];
            }
            else if (x[1] == x[2] && x[5] != x[4])
            {
                m[2] = (y[5] - y[4]) / (x[5] - x[4]);
                x[3] = x[1];
                y[3] = (x[3] - x[4]) * m[2] + y[4];
            }
            else if (x[1] != x[2] && x[5] == x[4])
            {
                m[1] = (y[2] - y[1]) / (x[2] - x[1]);
                x[3] = x[5];
                y[3] = (x[3] - x[1]) * m[1] + y[1];
            }
            else
                return null;

            Point ip = new Point(x[3], y[3]);

            if (!useBoundaries)
                return ip;
            else if (IsPointOnTheLine(l1, ip, 1) && IsPointOnTheLine(l2, ip, 1))
                return ip;
            else
                return null;
        }

        /// <summary>
        /// returns a intersection point of direction and Line segment
        /// </summary>
        /// <param name="startPoint">direction start point</param>
        /// <param name="l">Line</param>
        /// <param name="dx">delta X</param>
        /// <param name="dy">delta Y</param>        
        /// <returns></returns>
        public static Nullable<Point> IntersectionPoint(Point startPoint, Line l, double dx, double dy)
        {
            Point? ip;

            Line l1 = new Line();
            l1.X1 = startPoint.X;
            l1.Y1 = startPoint.Y;
            l1.X2 = l1.X1 + dx;
            l1.Y2 = l1.Y1 + dy;

            ip = IntersectionPoint(l, l1, false);

            if (!ip.HasValue) return null;

            Line l2 = new Line();
            l2.X1 = startPoint.X;
            l2.Y1 = startPoint.Y;
            l2.X2 = ip.Value.X;
            l2.Y2 = ip.Value.Y;

            if (IsPointOnTheLine(l2, new Point(l1.X2, l1.Y2), 1))
                return ip;
            else
                return null;
        }

        /// <summary>
        /// distance between two points
        /// </summary>
        /// <param name="p1"></param>
        /// <param name="p2"></param>
        public static double Distance(Point p1, Point p2)
        {
            return Math.Sqrt(Math.Pow(p2.Y - p1.Y, 2) + Math.Pow(p2.X - p1.X, 2));
        }

        /// <summary>
        /// Converts a rectangle to 4 lines TOP, RIGHT,BOTTOM, LEFT line
        /// </summary>
        /// <returns>lines of rect</returns>
        private static Line[] RectangleLines(Rect r)
        {
            //List<Line> retVal = new List<Line>(4);
            Line[] retVal = new Line[4];

            Line Line1 = new Line();
            Line1.X1 = r.Left; Line1.Y1 = r.Top; Line1.X2 = r.Right; Line1.Y2 = r.Top;

            Line Line2 = new Line();
            Line2.X1 = r.Right; Line2.Y1 = r.Top; Line2.X2 = r.Right; Line2.Y2 = r.Bottom;

            Line Line3 = new Line();
            Line3.X1 = r.Right; Line3.Y1 = r.Bottom; Line3.X2 = r.Left; Line3.Y2 = r.Bottom;

            Line Line4 = new Line();
            Line4.X1 = r.Left; Line4.Y1 = r.Bottom; Line4.X2 = r.Left; Line4.Y2 = r.Top;

            retVal[0] = Line1;
            retVal[1] = Line2;
            retVal[2] = Line3;
            retVal[3] = Line4;

            return retVal;
        }

        /// <summary>
        /// Returns the Intersection points of Line and Rectangle
        /// </summary>
        /// <param name="l">Line</param>
        /// <param name="r">Rectangle</param>
        /// <returns>Intersection Points</returns>
        public static List<Point> IntersectionPoints(Line l, Rect r)
        {
            List<Point> retVal = new List<Point>();

            Line[] rectLines = RectangleLines(r);

            foreach (Line rl in rectLines)
            {
                Point? i = IntersectionPoint(rl, l, true);
                if (i.HasValue)
                    retVal.Add(i.Value);
            }

            return retVal;
        }

        public static bool IsIntersected(Line l, Rect r)
        {
            Line[] rectLines = RectangleLines(r);

            foreach (Line rl in rectLines)
            {
                Point? i = IntersectionPoint(rl, l, true);
                if (i.HasValue)
                    return true;
            }

            return false;
        }

        /// <summary>
        /// Returns the Intersection points of many rectangles
        /// </summary>
        /// <param name="R">List Of rectange to be checked</param>
        /// <returns>Intersection Points</returns>
        public static List<Point> IntersectionPoints(List<Rect> R)
        {
            List<Point> retVal = new List<Point>();

            foreach (Rect r in R)
                foreach (Rect r1 in R)
                    if (r1 != r)
                        retVal.AddRange(IntersectionPoints(r, r1));
            return null;
        }

        /// <summary>
        /// Returns the Intersection points of Rectangle and Rectangle
        /// </summary>
        /// <param name="r1">First Rectangle</param>
        /// <param name="r2">Second Rectangle</param>
        /// <returns>Intersection Points</returns>
        public static List<Point> IntersectionPoints(Rect r1, Rect r2)
        {
            List<Point> retVal = new List<Point>();
            foreach (Line r1l in RectangleLines(r1))
                retVal.AddRange(IntersectionPoints(r1l, r2));

            return retVal;
        }
    }
}
Also there is a Geographic distance calculator in this framework.
using System;

namespace WinRTBase
{
    public static class GeoMath
    {
        /// <summary>
        /// The distance type to return the results in.
        /// </summary>
        public enum MeasureUnits { Miles, Kilometers };

        /// <summary>
        /// Returns the distance in miles or kilometers of any two
        /// latitude / longitude points. (Haversine formula)
        /// </summary>
        public static double Distance(double latitudeA, double longitudeA, double latitudeB, double longitudeB, MeasureUnits units)
        {
            if (latitudeA <= -90 || latitudeA >= 90 || longitudeA <= -180 || longitudeA >= 180
                || latitudeB <= -90 && latitudeB >= 90 || longitudeB <= -180 || longitudeB >= 180)
            {
                throw new ArgumentException(String.Format("Invalid value point coordinates. Points A({0},{1}) B({2},{3}) ",
                                                          latitudeA,
                                                          longitudeA,
                                                          latitudeB,
                                                          longitudeB));
            }

            double R = (units == MeasureUnits.Miles) ? 3960 : 6371;
            double dLat = toRadian(latitudeB - latitudeA);
            double dLon = toRadian(longitudeB - longitudeA);
            double a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2) +
            Math.Cos(toRadian(latitudeA)) * Math.Cos(toRadian(latitudeB)) *
            Math.Sin(dLon / 2) * Math.Sin(dLon / 2);
            double c = 2 * Math.Asin(Math.Min(1, Math.Sqrt(a)));
            double d = R * c;
            return d;
        }

        /// <summary>
        /// Convert to Radians.
        /// </summary>      
        private static double toRadian(double val) { return (Math.PI / 180) * val; }
    }
}

follow me on twitter: twitter.com/oguzkoroglu

my linked in profile : http://tr.linkedin.com/in/oguzkoroglu/

my personal web site : http://oguzkoroglu.net/

Last edited Apr 18, 2014 at 8:49 PM by ogu, version 6