C#: Get Current Month Name and Short Name

We had a requirement to get the current month name and its short name (example- November|Nov). While DateTime class does not provide these methods out of .net framework, we had to create methods which gives the similar output.. We have created similar methods through Extension Methods supported with recent .net framework.

Extension methods can be used as instance methods and it uses “this” keyword as a parameter. They are static and they must be defined on static class.

Here is the solution:

using System;
using System.Globalization;

namespace TestConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(DateTime.Today.Day + "." + DateTime.Today.Month + "." + DateTime.Today.Year);
            Console.WriteLine(DateTime.Now.AddMonths(-2).ToMonthName());
            Console.WriteLine(DateTime.Now.ToShortMonthName());
            
            // Update: Similar functionality can be achieved through below statements also.
            // Thanks Michael for inputs.
            Console.WriteLine(String.Format("{0:MMMM}", DateTime.Now));
            Console.WriteLine(String.Format("{0:MMM}", DateTime.Now));
            Console.WriteLine(DateTime.Now.ToString("MMMM"));
            Console.WriteLine(DateTime.Now.ToString("MMM"));
        }
    }

    static class DateTimeExtensions
    {
        public static string ToMonthName(this DateTime dateTime)
        {
            return CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(dateTime.Month);
        }

        public static string ToShortMonthName(this DateTime dateTime)
        {
            return CultureInfo.CurrentCulture.DateTimeFormat.GetAbbreviatedMonthName(dateTime.Month);
        }
    }
}

Output:
28.11.2014
September
Nov

Extension Methods in Visual Studio appears with special symbol:

Extension Methods

Extension Methods

Reference: http://www.dotnetperls.com/extension

Advertisements

CRM 2011: Object address not found on party or party is marked as non-emailable

While sending an Email message from either workflow/plugin or through sdk, if you get this message – “Object address not found on party or party is marked as non-emailable”; check below things:

  1. Check if the record is contact and the records is allowed for Emails or Bulk Email. These are Options available on Contact records and you can set them individually. Make sure both has Allow selected on contact.
  2. Check if your contact records is having a valid email address and not having blank value.

Happy Troubleshooting!!

CRM 2011, JavaScript: Set Customer Type of Lookup

Lets say you have to set Customer type of Lookup from JavaScript. Here is the code! You just have to set another attribute and you’re done!

Here I have given it in parameters as I had to open form with these parameters auto filled.

var params = {};
params["customerid"] = Xrm.Page.getAttribute("customerid").getValue()[0].id;
params["customeridname"] = Xrm.Page.getAttribute("customerid").getValue()[0].name;
params["customeridtype"] = Xrm.Page.getAttribute("customerid").getValue()[0].entityType;

//Open a new account record
Xrm.Utility.openEntityForm("incident", null, params);

Hope it helps!

CRM 2011, JavaScript: How to add some action after save record?

Hi there!

I recently had a requirement where I had to save the record and open another form once the button is pressed from ribbon.

I added the save JavaScript to the web resource and call it and call other function to open the form. This was not working for me.

Resolution for this:

Add an event on Save action by:

Xrm.Page.data.entity.addOnSave(openAccountForm); // openAccountForm is another function which opens the form
Xrm.Page.data.entity.save();
function openAccountForm() {
    Xrm.Utility.openEntityForm("account");
}

CRM 4.0: Create Dynamic Menu Items

We had a requirements to add Dynamic Menu Items to CRM 4.0 Toolbar. I have followed following blog post by Sonoma Partners for implementing Dynamic Menu Items. I have modified their code with simple JavaScript DOM.

http://blog.sonomapartners.com/2009/12/adding-dynamic-menu-items.html

You can follow above mentioned link to create a stub for the implementation and then refer below mentioned code which uses JavaScript DOM and not JQuery to create them.

function createLinksMenu() {

    var links = getCallLinks();
    var dummyElement;

    var ul = document.getElementById("mnuNew_0_CallCustomer");
    var items = ul.getElementsByTagName("li");
    for (var i = 0; i < items.length; ++i) {
        // do something with items[i], which is a <li> element
        if (items[i].innerHTML.indexOf("Dummy") > 0) {
            dummyElement = items[i].cloneNode(true);
            break;
        }
    }

    // Loop through all the links 
    //   then clone the dummy node, update it as necessary and append it to the menu
    for (var i = 0; i < links.length; i++) {
        //alert(links[i].Name);

        var elem = document.getElementById("mnuNew_0_CallCustomer");
        var newEle = dummyElement.cloneNode(true);
        newEle.id = "CallCustomerMenu" + i;
        newEle.className = "ms-crm-MenuItem-Label";
        newEle.tabIndex = -1;
        newEle.action = "callNumber('" + links[i].Url + "');";
        newEle.innerHTML = "<SPAN class='ms-crm-MenuItem-Label'><A class='ms-crm-MenuLink' tabIndex='-1' onclick='return false;' href='javascript:onclick();' target='_self'><SPAN class='ms-crm-MenuItem-Icon'></SPAN><SPAN class='ms-crm-MenuItem-Text' tabIndex='0'>" + links[i].Name + "</SPAN></A></SPAN>";
        elem.appendChild(newEle);
    }

    // remove dummy node
    items = ul.getElementsByTagName("li");
    for (var i = 0; i < items.length; i++) {
        //alert(items[i].innerHTML.indexOf("Dummy"));

        // do something with items[i], which is a <li> element
        if (items[i].innerHTML.indexOf("Dummy") > 0) {
            items[i].style.display = "none";
            break;
        }
    }
}

Hyper-V: The application encountered an error while attempting to change the state of

Hello,

I got following error while creating a new VM and booting it through a DVD drive from Hyper-V.

The application encountered an error while attempting to change the state of <Virtual Machine>. <Virtual Machine> failed to start.

Microsoft Emulated IDE Controller (Instance ID {83F8638B-8DCA-4152-9EDA-2CA8B33039B4}): Failed to Power on with Error ‘The process cannot access the file because it is being used by another process.’

Failed to open attachment ‘D:’. Error: ‘The process cannot access the file because it is being used by another process.’

Resolution:

You must be working on multiple Virtual Machines… and same DVD drive is being used by more than one Virtual Machines. Remove the DVD/Virtual Drives from other Virtual Machines and Start the VM you are working on.

Done! Voila!

How to access the VM from your host and how to provide Internet/external network access to Guest (CRM VM)?

How to access the VM from your host and how to provide Internet/external network access to Guest (CRM VM)?

http://blogs.msdn.com/b/chinmay/archive/2014/04/02/crm-dev-lab-series-dev-vm-and-connectivity-hyper-v.aspx

C#: The application has failed to start because its side-by-side configuration is incorrect. Please see the application event log or use the command-line sxstrace.exe tool for more detail.

Hello guys,

Before some time I had a situation where my console application would not run and without showing any screen/anything else it gave me this alert mentioned below:

The application has failed to start because its side-by-side configuration is incorrect. Please see the application event log or use the command-line sxstrace.exe tool for more detail.

Most of the google links will guide you to check your VC++ runtime and their versions. I checked everything and everything was as expected as other applications were working smooth without any error.

Also, I checked with a simple “Hello world!” console application but the output was same. And with no clue to my mind I removed the .config file from the directory.

If same is your situation then, suggested solution would be to rename the extension of the .config file to .xml file and run/parse it to any browser. In my case the .xml file did not meet with the standards as an value contained & (ampersand) and it was breaking the it to be well formed xml document.

Check with the standard list of invalid xml characters so that you can avoid this kind of situation in future. Check this link – http://www.w3.org/TR/2000/REC-xml-20001006#charsets to see well-formed xml document rules.

C#: Converting from Generic List to CSV and CSV to Generic List

CSV from List

public string GetCsvFromList(List<string> list)
{
    return String.Join(",", list.Select(x => x.ToString()).ToArray());
}

List from CSV

public List<T> GetListFromCsv<T>(string commaSplited)
{
    return (from e in commaSplited.Split(',')
            select (T)Convert.ChangeType(e.Trim(), typeof(T))).ToList();
}