Thursday, May 30, 2013

C# Assign values to hard coded objects when you don't know their names; i.e dynamically at runtime

I have an method that gets passed a collection of KeyValue pairs.
These KeyValues consist of a Key, which contains the name of the property, or variable, and a Value. For example:

KeyValue1
  • Key="InvoiceId"
  • Value="3436" //the type is string


KeyValue2
  • Key="DateDue"
  • Value="1/17/2013 6:00:00 AM" //the type is DateTime

So the objective is as follows:
  1. Find the variable named dbi.InvoiceId
    1. Then assign it the Value of 3436, as a string
  2. Find the variable named dbi.DateDue
    1. Then assign it the Value of "1/17/2013 6:00:00 AM", as a DateTime
Looks complicated. But its not.

Make sure the reference System.Reflection. The framework on my project is .Net 4.
Here's the code:
        public string SendByteArrayToSharepoint(Byte[] bytes, string fileName, SharepointGatewayCustomAttributes customAttributes)
        {
            try
            {
                //THIS IS THE TARGET OBJECT
                DropBoxItem dbi = new DropBoxItem()
                {
                    ContentType = contentType,
                    Name = Path.GetFileName(fileName),
                    Title=fileName,
                    Path = fileName
                };

                //Now iterate through the AttributeCollection
                foreach (var v in customAttributes.AttributeCollection)
                {
                    // this locates the object
                    PropertyInfo pi = dbi.GetType().GetProperty(v.Key);

                    //this assigns the value of the object, using the correct type
                    pi.SetValue(dbi, ChangeNullableType(v.Value, pi.PropertyType), null);
                }


This is the method called ChangeNullableType:
Credit for this method goes to Peter Johnson's Blog at http://weblogs.asp.net/pjohnson/archive/2006/05/19/447154.aspx
public static object ChangeNullableType(object value, Type conversionType)
        {
            // Note: This if block was taken from Convert.ChangeType as is, and is needed here since we're
            // checking properties on conversionType below.
            if (conversionType == null)
            {
                throw new ArgumentNullException("conversionType");
            } // end if

            // If it's not a nullable type, just pass through the parameters to Convert.ChangeType

            if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
            {
                // It's a nullable type, so instead of calling Convert.ChangeType directly which would throw a
                // InvalidCastException (per http://weblogs.asp.net/pjohnson/archive/2006/02/07/437631.aspx),
                // determine what the underlying type is
                // If it's null, it won't convert to the underlying type, but that's fine since nulls don't really
                // have a type--so just return null
                // Note: We only do this check if we're converting to a nullable type, since doing it outside
                // would diverge from Convert.ChangeType's behavior, which throws an InvalidCastException if
                // value is null and conversionType is a value type.
                if (value == null)
                {
                    return null;
                }

                // It's a nullable type, and not null, so that means it can be converted to its underlying type,
                // so overwrite the passed-in conversion type with this underlying type
                NullableConverter nullableConverter = new NullableConverter(conversionType);
                conversionType = nullableConverter.UnderlyingType;
            }

            // Now that we've guaranteed conversionType is something Convert.ChangeType can handle (i.e. not a
            // nullable type), pass the call on to Convert.ChangeType
            return Convert.ChangeType(value, conversionType);
        }





Friday, May 17, 2013

Read XML into an Object Model using XDocument

The intent is to read an XML file, and create corresponding classes, collections of classes etc.

ENTRY POINT 


Create an XML Document on the fly

I want to produce this:



<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE CreateLoanPrincipalPayment SYSTEM "CreateLoanPrincipalPayment.dtd">
<CreateLoanPrincipalPayment
loanAlias="CHG8F47RP"
effectiveDate="10/07/2005"
requestedAmount="1000000"
version="1.0">
</CreateLoanPrincipalPayment>

C# Code:


using Services.LoanIq;


        private string GetXml(string functionName)
        {
            try
            {
                XDocument xdoc = new XDocument();
                XDocumentType documentType = new XDocumentType("CreateLoanPrincipalPayment",
                                                 null,
                                                 "CreateLoanPrincipalPayment.dtd",
                                                 null);
                xdoc.AddFirst(documentType);
                xdoc.Declaration = new XDeclaration("1.0",
                                       "utf-8",
                                       null); // Note: this will get dropped off automatically
                xdoc.Add(new XElement("CreateLoanPrincipalPayment",
                             new XAttribute("version", "1.0"),
                             new XAttribute("requestedAmount", "1000000"),
                             new XAttribute("effectiveDate", "10/07/2005"),
                             new XAttribute("loanAlias", "CHG8F47RP")));

                //So you have to add it back here
                string returnValue=xdoc.Declaration + Environment.NewLine + xdoc;
               
                return returnValue;

            }
            catch (Exception ex)
            {
               
                throw;
            }
        }



Wednesday, May 15, 2013

Visual Studio Tean System - Adding a project to source control error

This is the error:

The item 'LoanIqToXRM.sln' is already under source control at the selected location. If you are trying to rebind a project that you have already added to source control outside Microsoft Visual Studio, you should use the Change Source Control command. If you are adding this project for the first time, you should either choose a different server folder for the project or move the existing project to a different server folder.

To fix it,  click the project in Solution Explorer and click File in the main menu. Select Source Control then Change Source Control.

Now select the projects you want to include, then click Bind and click OK:


Tuesday, May 14, 2013

ASP.Net display XML in Grid


        protected void ButtonExtractNow_Click(object sender, EventArgs e)
        {
            try
            {
                using (LoanIqAdapter _adapter = new LoanIqAdapter())
                {

                    string results = _adapter.SendInquiry("ost_tranById('" + DropDownList1.SelectedValue + "')", false);
                    XDocument xDoc = XDocument.Parse(results);
                    IOrganizationService xrmService = GetXrmService("JamesDev");
                    foreach (XElement childElement in xDoc.XPathSelectElements("//osttran/Record"))
                    {
                        //SendToXRM(xrmService, childElement);
                       
                    }

                    StringReader sr = new StringReader(results);
                    DataSet ds = new DataSet();
                    ds.ReadXml(sr);
                    ds.Merge(ds, true);

                    GridView1.DataSource = ds.Tables[0];
                    GridView1.DataBind();

                }
            }
            catch (Exception ex)
            {
                //throw;
            }


Monday, May 13, 2013

TCP Socket Reader



using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Web;

namespace Applications.Common.Utilities
{
    public class TcpUtilities : IDisposable
    {
        #region Private members

        private Socket _socket;
        private string _serverName;
        private int _portNumber;

        #endregion

        #region Constructor/Destructor
        public TcpUtilities(string serverName, int portNumber)
        {
            _portNumber = portNumber;
            _serverName = serverName;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        protected virtual void Dispose(bool disposing)
        {

            if (disposing)
                if (_socket != null)
                {
                    _socket.Dispose();
                    _socket = null;
                }
        }
        ~TcpUtilities()
        {
            Dispose(false);
        }
        #endregion

        #region General public methods

        public void OpenSocket()
        {
            IPHostEntry hostEntry = null;
            hostEntry = Dns.GetHostEntry(_serverName);
            IPEndPoint ipe = new IPEndPoint(Dns.GetHostAddresses(_serverName)[0], _portNumber);
            _socket = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            _socket.Connect(ipe);
        }

        public void CloseSocket()
        {
            if (_socket.Connected == true)
                _socket.Close();
        }

        public string SendReceive(string request)
        {

            OpenSocket();

            Byte[] bytesSent = Encoding.UTF8.GetBytes(request);

            _socket.Send(bytesSent, bytesSent.Length, SocketFlags.None);

            int bytes = 0;
            string response = "";

            // The following will block until the entire string is transmitted.
            do
            {
                Byte[] bytesReceived = new Byte[1024];
                bytes = _socket.Receive(bytesReceived, bytesReceived.Length, SocketFlags.None);
                response += Encoding.ASCII.GetString(bytesReceived, 0, bytes);
            }
            while (bytes > 0);
            //response = HttpUtility.UrlDecode( response.Substring( response.IndexOf( '0' ) + 1 ) );
            CloseSocket();
            return response;
        }

        #endregion



    }
}



Implementation

_tcpUtilities = new TcpUtilities(_serverName, _portNumber);
        public string SendInquiry( string command , bool returnRawData )
        {
           
            string formattedQuery = FormatInquiryRequest( command );
            string result = _tcpUtilities.SendReceive( formattedQuery );
            string returnValue = DeFormatInquiryResult( result , returnRawData );

            return ( returnValue );
        }




Friday, May 10, 2013

How to add a CRM Navigation section (a tab) to a form

CRM forms have a section of links on the left, that default to General and Notes.
This is how to add another section:

  1. Make sure the Body section is highlighted. In the pic above, it is orange.
  2. Click the Insert tab on the ribbon, and in the Tab section, click the One Column button.
  3. A new tab is created on your form - doublc click it and give it a meaningful name.
There. Easy once you know that this is NOT considered a navigation feature!

Wednesday, May 8, 2013

Convert State ID to State Name, Get State Name from State ID

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace Agware_Sales_Extract
{
    public static class StateStuff
    {
        public static string GetStateIdByName(string stateName)
        {
            switch (stateName.ToUpper())
            {
                case "ALABAMA":
                return "AL";
 
                case "ALASKA":
                return "AK";
 
                case "AMERICAN SAMOA":
                return "AS";
 
                case "ARIZONA":
                return "AZ";
 
                case "ARKANSAS":
                return "AR";
 
                case "CALIFORNIA":
                return "CA";
 
                case "COLORADO":
                return "CO";
 
                case "CONNECTICUT":
                return "CT";
 
                case "DELAWARE":
                return "DE";
 
                case "DISTRICT OF COLUMBIA":
                return "DC";
 
                case "FEDERATED STATES OF MICRONESIA":
                return "FM";
 
                case "FLORIDA":
                return "FL";
 
                case "GEORGIA":
                return "GA";
 
                case "GUAM":
                return "GU";
 
                case "HAWAII":
                return "HI";
 
                case "IDAHO":
                return "ID";
 
                case "ILLINOIS":
                return "IL";
 
                case "INDIANA":
                return "IN";
 
                case "IOWA":
                return "IA";
 
                case "KANSAS":
                return "KS";
 
                case "KENTUCKY":
                return "KY";
 
                case "LOUISIANA":
                return "LA";
 
                case "MAINE":
                return "ME";
 
                case "MARSHALL ISLANDS":
                return "MH";
 
                case "MARYLAND":
                return "MD";
 
                case "MASSACHUSETTS":
                return "MA";
 
                case "MICHIGAN":
                return "MI";
 
                case "MINNESOTA":
                return "MN";
 
                case "MISSISSIPPI":
                return "MS";
 
                case "MISSOURI":
                return "MO";
 
                case "MONTANA":
                return "MT";
 
                case "NEBRASKA":
                return "NE";
 
                case "NEVADA":
                return "NV";
 
                case "NEW HAMPSHIRE":
                return "NH";
 
                case "NEW JERSEY":
                return "NJ";
 
                case "NEW MEXICO":
                return "NM";
 
                case "NEW YORK":
                return "NY";
 
                case "NORTH CAROLINA":
                return "NC";
 
                case "NORTH DAKOTA":
                return "ND";
 
                case "NORTHERN MARIANA ISLANDS":
                return "MP";
 
                case "OHIO":
                return "OH";
 
                case "OKLAHOMA":
                return "OK";
 
                case "OREGON":
                return "OR";
 
                case "PALAU":
                return "PW";
 
                case "PENNSYLVANIA":
                return "PA";
 
                case "PUERTO RICO":
                return "PR";
 
                case "RHODE ISLAND":
                return "RI";
 
                case "SOUTH CAROLINA":
                return "SC";
 
                case "SOUTH DAKOTA":
                return "SD";
 
                case "TENNESSEE":
                return "TN";
 
                case "TEXAS":
                return "TX";
 
                case "UTAH":
                return "UT";
 
                case "VERMONT":
                return "VT";
 
                case "VIRGIN ISLANDS":
                return "VI";
 
                case "VIRGINIA":
                return "VA";
 
                case "WASHINGTON":
                return "WA";
 
                case "WEST VIRGINIA":
                return "WV";
 
                case "WISCONSIN":
                return "WI";
 
                case "WYOMING":
                return "WY";
            }
 
            return ("State Not Available:" + stateName);
        }
        public static string GetState(string stateId)
        {
           
 
            switch (stateId)
            {
                case "AL":
                return "ALABAMA";
 
                case "AK":
                return "ALASKA";
 
                case "AS":
                return "AMERICAN SAMOA";
 
                case "AZ":
                return "ARIZONA";
 
                case "AR":
                return "ARKANSAS";
 
                case "CA":
                return "CALIFORNIA";
 
                case "CO":
                return "COLORADO";
 
                case "CT":
                return "CONNECTICUT";
 
                case "DE":
                return "DELAWARE";
 
                case "DC":
                return "DISTRICT OF COLUMBIA";
 
                case "FM":
                return "FEDERATED STATES OF MICRONESIA";
 
                case "FL":
                return "FLORIDA";
 
                case "GA":
                return "GEORGIA";
 
                case "GU":
                return "GUAM";
 
                case "HI":
                return "HAWAII";
 
                case "ID":
                return "IDAHO";
 
                case "IL":
                return "ILLINOIS";
 
                case "IN":
                return "INDIANA";
 
                case "IA":
                return "IOWA";
 
                case "KS":
                return "KANSAS";
 
                case "KY":
                return "KENTUCKY";
 
                case "LA":
                return "LOUISIANA";
 
                case "ME":
                return "MAINE";
 
                case "MH":
                return "MARSHALL ISLANDS";
 
                case "MD":
                return "MARYLAND";
 
                case "MA":
                return "MASSACHUSETTS";
 
                case "MI":
                return "MICHIGAN";
 
                case "MN":
                return "MINNESOTA";
 
                case "MS":
                return "MISSISSIPPI";
 
                case "MO":
                return "MISSOURI";
 
                case "MT":
                return "MONTANA";
 
                case "NE":
                return "NEBRASKA";
 
                case "NV":
                return "NEVADA";
 
                case "NH":
                return "NEW HAMPSHIRE";
 
                case "NJ":
                return "NEW JERSEY";
 
                case "NM":
                return "NEW MEXICO";
 
                case "NY":
                return "NEW YORK";
 
                case "NC":
                return "NORTH CAROLINA";
 
                case "ND":
                return "NORTH DAKOTA";
 
                case "MP":
                return "NORTHERN MARIANA ISLANDS";
 
                case "OH":
                return "OHIO";
 
                case "OK":
                return "OKLAHOMA";
 
                case "OR":
                return "OREGON";
 
                case "PW":
                return "PALAU";
 
                case "PA":
                return "PENNSYLVANIA";
 
                case "PR":
                return "PUERTO RICO";
 
                case "RI":
                return "RHODE ISLAND";
 
                case "SC":
                return "SOUTH CAROLINA";
 
                case "SD":
                return "SOUTH DAKOTA";
 
                case "TN":
                return "TENNESSEE";
 
                case "TX":
                return "TEXAS";
 
                case "UT":
                return "UTAH";
 
                case "VT":
                return "VERMONT";
 
                case "VI":
                return "VIRGIN ISLANDS";
 
                case "VA":
                return "VIRGINIA";
 
                case "WA":
                return "WASHINGTON";
 
                case "WV":
                return "WEST VIRGINIA";
 
                case "WI":
                return "WISCONSIN";
 
                case "WY":
                return "WYOMING";
            }
 
            return ("State Not Available:" + stateId);
        }
    }
}