May 21, 2015

Easy Encrypt and Decrypt functionality for ASP.Net text fields

Some times you want to store some data into hidden fields and want to ensure that data is unreadable to humans but is only used by server side variables.

The easiest way it to utilize the RSACryptoServiceProvider class in System.Security.Cryptography.


Utilize the class shown below:


using System.Security.Cryptography;

namespace SampleNamespace
{
    public class EncryptDecrypt
    {
        static RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider(2048);


        public EncryptDecrypt()
        {

        }


        public static string Encrypt(string text)
        {
            return Convert.ToBase64String(rsaProvider.Encrypt(System.Text.Encoding.UTF8.GetBytes(text), true));
        }

        public static string Decrypt(string text)
        {
            return System.Text.Encoding.UTF8.GetString(rsaProvider.Decrypt(Convert.FromBase64String(text), true));
        }
    }
}

Please note that this works only for smaller strings. You may get an error: Bad Length for longer strings. For longer string we need to use hybrid encryption alogrithm.

To encrypt longer string use the code below:

using System.Security.Cryptography;

namespace SampleNamespace
{
    /// This size of the IV (in bytes) must = (keysize / 8).  Default keysize is 256, so the IV must be
    /// 32 bytes long.  Using a 16 character string here gives us 32 bytes when converted to a byte array.
    private const string initVector = "E5IaHPeVT3Mvt5Lk";
    /// This constant is used to determine the keysize of the encryption algorithm
    private const int keysize = 256;
    /// Passpharase to be used for encryption and decryption
    private const string passPhrase = "QjM2vWxgat";

    /// <summary>
    /// Encrypts provided String
    /// </summary>
    /// <param name="plainText">Text to be encrypted</param>
    /// <returns>Encrypted String</returns>
    public static string EncryptString(string plainText)
    {
        byte[] initVectorBytes = Encoding.UTF8.GetBytes(initVector);
        byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
        PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null);
        byte[] keyBytes = password.GetBytes(keysize / 8);
        RijndaelManaged symmetricKey = new RijndaelManaged();
        symmetricKey.Mode = CipherMode.CBC;
        ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes);
        MemoryStream memoryStream = new MemoryStream();
        CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);
        cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
        cryptoStream.FlushFinalBlock();
        byte[] cipherTextBytes = memoryStream.ToArray();
        memoryStream.Close();
        cryptoStream.Close();
        return Convert.ToBase64String(cipherTextBytes);
    }

    /// <summary>
    /// Decrypts provided String
    /// </summary>
    /// <param name="cipherText">Text to be decrypted</param>
    /// <returns>Decrypted String</returns>
    public static string DecryptString(string cipherText)
    {
        byte[] initVectorBytes = Encoding.UTF8.GetBytes(initVector);
        byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
        PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null);
        byte[] keyBytes = password.GetBytes(keysize / 8);
        RijndaelManaged symmetricKey = new RijndaelManaged();
        symmetricKey.Mode = CipherMode.CBC;
        ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes);
        MemoryStream memoryStream = new MemoryStream(cipherTextBytes);
        CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
        byte[] plainTextBytes = new byte[cipherTextBytes.Length];
        int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
        memoryStream.Close();
        cryptoStream.Close();
        return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
    }
}


Apr 24, 2015

SDL Tridion Core Service : Read All Components from a Publication based on Schema URI

The best way to fetch all components from a specific publication is by using the SearchQueryData class as:


SearchQueryData query = new SearchQueryData()
   {
          BasedOnSchemas = new BasedOnSchemaData[] { new BasedOnSchemaData() { Schema = new LinkToSchemaData() { IdRef = SchemaTcmUri } } },
          SearchIn = new LinkToIdentifiableObjectData() { IdRef = PublicationUri },
          ItemTypes = new ItemType[] { ItemType.Component }
   };
   try
   {
          XElement xResults = client.GetSearchResultsXml(query);
   }
   catch (System.ServiceModel.CommunicationException commProblem)
   {
          Console.WriteLine("There was a communication problem. " + commProblem.Message + commProblem.StackTrace);
          Console.Read();
   }

But, it requires the search to be properly configured in Tridion CMS. If you can search for an item based in Title/Text than most probably your code should work.

But if search is not properly configured, the code will throw the following error:


The remote server returned an error: (403) Forbidden.
Server stack trace:
   at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc)
   at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
   at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs)
   at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
   at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]:
   at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
   at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
   at Tridion.ContentManager.CoreService.Client.ICoreService.GetSearchResultsXml(SearchQueryData filter)
   at Tridion.ContentManager.CoreService.Client.CoreServiceClient.GetSearchResultsXml(SearchQueryData filter)
A more detailed warning can be seen in Event Viewer


Error: The remote server returned an error: (403) Forbidden. 
Component: Tridion.ContentManager.CoreService Errorcode: 854 
User: server\tridion_admin 
StackTrace Information Details: System.Net.HttpWebRequest.GetResponse() 
Tridion.ContentManager.Search.SolrClient.ProcessResponse(HttpWebRequest,Boolean,Boolean,String&) 
Tridion.ContentManager.Search.SolrClient.Post(String,String,String&) 
Tridion.ContentManager.Search.SolrClient.Query(String,Int32,Nullable`1,String&) 
Tridion.ContentManager.Search.SearchQueryEngine.GetSearchResultsFromSolr(SearchQueryData,Int32,Nullable`1) 
Tridion.ContentManager.Search.SearchQueryEngine.GetSearchResultsFromSolr(SearchQueryData,Int32,Nullable`1) 
Tridion.ContentManager.Search.SearchQueryEngine.GetSearchResults(SearchQueryData,Int32) 
Tridion.ContentManager.Search.ComWrapper.SearchQueryEngineFacade.GetSearchResults(Int32,Int32) 
SearchBLST.GetListData SearchBLST.GetSearchResults 
at Tridion.ContentManager.ContentManagement.SearchQuery.GetListResults(Int32 startRowIndex, Int32 maxRows) 
at Tridion.ContentManager.Query.GetListResults() 
at Tridion.ContentManager.CoreService.CoreServiceBase.GetSearchResultsXml(SearchQueryData filter) 
at SyncInvokeGetSearchResultsXml(Object , Object[] , Object[] ) 
at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs) 
at Tridion.ContentManager.CoreService.TransactionSupportInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs)
at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc) 
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc) 
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc& rpc) 
at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)  
CM Version: SDL Tridion 2011 SP 1


There is still a way to fetch List of TcmUri of related componets. It can be achieved through code:


UsingItemsFilterData usingComponentsFilter = new UsingItemsFilterData
{
    BaseColumns = ListBaseColumns.IdAndTitle, // to specify the detail in the XML
    ItemTypes = new[] { ItemType.Component },  // to specify certain items
    IncludedVersions = VersionCondition.OnlyLatestVersions //do not include old versions
};
IEnumerable<XElement> usingComponentXMLList = from comp in client.GetListXml(schemaTcmUri, usingComponentsFilter).Elements()
                                                select comp;
Hope this post helps others!!