Search code examples
tridiontridion-2011

How to get TCM URI of multimedia type through file extension


I want to fetch the TCM URI of a multimedia type by passing file extension as parameter to method. Below is the code which I'm using but I getting some exception:-

private static string GetMultimediaTypeTCMURI(FileExtensionsList lFileExtensions)
{
    string lTCMURI = "";
    try
    {
        SessionAwareCoreService2010Client client 
                                          = new SessionAwareCoreService2010Client();
        client.ClientCredentials.Windows.ClientCredential.UserName = "myUserName";
        client.ClientCredentials.Windows.ClientCredential.Password = "myPassword";
        client.Open();
        FileExtensionsList list = new FileExtensionsList();
        var mmType = client.GetSystemWideList(new MultimediaTypesFilterData())
              .Single(mt => ((MultimediaTypeData)mt).FileExtensions == lFileExtensions);
        lTCMURI = mmType.Id;
    }
    catch (Exception e)
    {
        throw new Exception("Please check either Mimetype" 
              + lFileExtensions + "is wrong or Mimetype does not exist in SDL Tridion.");
    }
    return lTCMURI;

}

Call to above method:-

FileExtensionsList list = new FileExtensionsList();
list.Add("js");

GetMultimediaTypeTCMURI(list);

I'm getting "Sequence contains no matching element" exception with above code, anyone please suggest how to do this.


Solution

  • Sequence contains no matching element is thrown if there's no match to your Linq expression. What I see is that you are trying to match list of extensions:

    mt => ((MultimediaTypeData)mt).FileExtensions == lFileExtensions
    

    It means that file extensions of multimedia type should exactly match your lFileExtensions, it should even have the same order. Instead, try searching by only 1 file extension you need:

    mt => ((MultimediaTypeData)mt).FileExtensions.Contains(myFileExtension)
    

    Consider also using SingleOrDefault method instead of Single. It will not throw exception, but return null if there's no match. You can later check multimedia type for null