Wednesday 26 November 2014

Meta Data in DropDown List in CRM 2013

Hi,

this page explains how we can bring and show the metadata in dropdown list(in HTML page).

1. Download the latest SDK.

go to : SDK\SampleCode\JS\SOAPForJScript\SOAPForJScript\Scripts

   check SDK.MetaData.js is there or not..
if yes :

2. Create a javascript webresource with name of : SDK.MetaData
   example : new_/Scripts/SDK.MetaData.js (use same formate for naming)

3. attach the SDK.MetaData.js from bin folder.

4. now create a HTML webresource with name of : /MetaDataDemo.htm

example : new_/MetaDataDemo.htm (use same format for naming).

5. attach the file : SDK\SampleCode\JS\SOAPForJScript\SOAPForJScript\MetaDataDemo.htm

here you will see the start button.. by clicking on this we will get entities, by clicking on entity we will get attributes.

now need to modify according to our requirement.

copy paste this code on the html webresource;

<!DOCTYPE html>
<!--
This file is part of the Microsoft Dynamics CRM SDK code samples.

Copyright (C) Microsoft Corporation.  All rights reserved.

This source code is intended only as a supplement to Microsoft
Development Tools and/or on-line documentation.  See these other
materials for detailed information regarding Microsoft code samples.

THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
PARTICULAR PURPOSE.
-->
<!--<snippetMetaDataDemo>-->
<html lang="en-US">
<head>
    <title>Metadata Demonstration</title>
    <script src="../ClientGlobalContext.js.aspx" type="text/javascript"></script>
    <script src="hppscm_/Scripts/SDK.MetaData.js" type="text/javascript"></script>
    <script type="text/javascript">
        // An unordered list element to add Entity list items to
        var results;
        // An area to display messages
        var message;

        // Alert flag to indicate the changes
        // var alertFlag;

        function startSample() {
            ///<summary>
            /// Initializes the sample when the document is ready
            ///</summary>
            //Assign the global variables
            results = document.getElementById("results");
            message = document.getElementById("message");
            //    alertFlag = document.getElementById("dispalert");
            // document.getElementById("btnstartSample").setAttribute("disabled", "disabled");
            //Retrieve entities
            window.parent.SDK.Metadata.RetrieveAllEntities(window.parent.SDK.Metadata.EntityFilters.Entity,
             false,
             successRetrieveAllEntities,
             errorRetrieveAllEntities);
            // setText(message, "Loading...");

        }
        function btnSubmitValues() {
            var placeHValue = document.getElementById("placeholder");
            var dropdValue = document.getElementById("attributeselect");
            var EntityList= document.getElementById("entityselect");
            var seletedvalue = dropdValue.options[dropdValue.selectedIndex].text;
            var entityselectevalue = EntityList.options[EntityList.selectedIndex].text;
          //  var merge = placeHValue.value + seletedvalue;

            var Xrm;
            if (window.opener) { Xrm = window.opener.Xrm; }
            else if (window.parent) { Xrm = window.parent.Xrm; }
            var Formname = Xrm.Page.getAttribute("hppscm_name").getValue();
            var FormField = Xrm.Page.getAttribute("hppscm_field").getValue();

            Xrm.Page.getAttribute("hppscm_name").setValue(placeHValue.value);
            Xrm.Page.getAttribute("hppscm_field").setValue(seletedvalue);
            Xrm.Page.getAttribute("hppscm_entity").setValue(entityselectevalue);
           // alert(merge);

        }

        function successRetrieveAllEntities(entityMetadataCollection) {
            ///<summary>
            /// Receives the data from SDK.Metadata.RetrieveAllEntities and
            /// appends a list item to results for each one.
            ///</summary>

            entityMetadataCollection.sort(function (a, b) {
                if (a.LogicalName < b.LogicalName)
                { return -1 }
                if (a.LogicalName > b.LogicalName)
                { return 1 }
                return 0;
            });

            var EntityDropdown = document.getElementById('entityselect');
            var totalfields = entityMetadataCollection.length;
            var optionsList = new Array(totalfields);

            for (var i = 0; i < entityMetadataCollection.length; i++) {

                var entity = entityMetadataCollection[i];
                var entityNode = document.createElement("li");
                var entitySpan = document.createElement("span");

                setText(entitySpan, entity.SchemaName);
                entitySpan.id = entity.LogicalName;
                optionsList[i] = entity.LogicalName;
                entitySpan.title = "Click to Retrieve Attributes.";
                entitySpan.attributesRetrieved = false;
                // Add the event handler to retrieve attributes
                if (entity.LogicalName == "hppscm_visaapplication") {
                    entitySpan.onload = retrieveAttributes;
                   // EntityDropdown.options[i].selected=true;
                    entitySpan.onclick = retrieveAttributes;
                    entitySpan.style.cursor = "pointer";

                   // entityNode.appendChild(entitySpan);
                   // results.appendChild(entityNode);
                }
            }

            for (var i = 0; i < optionsList.length; i++) {
                option = new Option(optionsList[i], optionsList[i]);
                EntityDropdown.appendChild(option);// = option;
                if(optionsList[i]=="hppscm_visaapplication")
                {
                    EntityDropdown.options[i].selected = true;
                }
            }

            //setText(message, entityMetadataCollection.length +
            //" entities retrieved. Click each entity to retrieve the entity attributes.");

            retrieveAttributes();
        }
        function errorRetrieveAllEntities(error) {
            ///<summary>
            /// Displays the error returned from  SDK.Metadata.RetrieveAllEntities if it fails.
            ///</summary>
            setText(message, error.message);

        }

        function retrieveAttributes() {
            ///<summary>
            /// Retrieves attributes for the entity list item that is clicked
            ///</summary>
            //  if (this.attributesRetrieved == false) {
            var EntityList = document.getElementById("entityselect");
            //var seletedvalue = dropdValue.options[dropdValue.selectedIndex].text;
            var entityselectevalue = EntityList.options[EntityList.selectedIndex].text;
            var entityLogicalName = entityselectevalue;//this.id;
                // Display an entity list item level notification while retrieving data.
                var notification = document.createElement("span");


                setText(notification, "   Retrieving attributes for " + entityLogicalName + "...");
                notification.id = entityLogicalName + "Notification";
              //  entityLogicalName.parentElement.appendChild(notification);

                window.parent.SDK.Metadata.RetrieveEntity(window.parent.SDK.Metadata.EntityFilters.Attributes,
                entityLogicalName,
                null,
                false,
                function (entityMetadata) { successRetrieveEntity(entityLogicalName, entityMetadata); },
                errorRetrieveEntity);


           // }
            //this.attributesRetrieved = true;
          //  this.title = "";
        }

        function successRetrieveEntity(logicalName, entityMetadata) {
            ///<summary>
            /// Retrieves attributes for the entity list item that is clicked
            ///</summary>

            // Update the entity list item notification when data is retrieved.

            entityMetadata.Attributes.sort(function (a, b) {
                if (a.LogicalName < b.LogicalName)
                { return -1 }
                if (a.LogicalName > b.LogicalName)
                { return 1 }
                return 0;
            });

            //var notification = setText(document.getElementById(logicalName +
            //"Notification"), "   Retrieved " + entityMetadata.Attributes.length + " attributes.");

            var attributeList = document.createElement("ul");
            var dropdownlist = document.getElementById('attributeselect');
            var totalfields = entityMetadata.Attributes.length;
            var optionsList = new Array(totalfields);

            for (var i = 0; i < entityMetadata.Attributes.length; i++) {
                var attribute = entityMetadata.Attributes[i];
                var attributeNode = document.createElement("li");
                setText(attributeNode, attribute.SchemaName);
                attributeList.appendChild(attributeNode);
                optionsList[i] = attribute.SchemaName;

            }

            for (var i = 0; i < optionsList.length; i++) {
                option = new Option(optionsList[i], optionsList[i]);
                dropdownlist.appendChild(option);// = option;
            }

            //for (i = 0; i < attributeList.childNodes.length; i++)
            //{
            //    var opt = document.createElement("option");
            //    opt.text = attributeList.childNodes[i].innerText;
            //    opt.value = i;
            //    dropdownlist.appendChild(opt);

            //}
            // Access the entity list item element
      //      var entityNode = document.getElementById(logicalName).parentElement;

            // entityNode.appendChild(attributeList);
            // entityNode.attributesDisplayed = true;
            // Attach event handler to toggle display of attributes.
         //   entityNode.firstChild.onclick = toggleDisplayAttributes;
         //   entityNode.firstChild.title = "Click to hide attributes.";

        }
        function errorRetrieveEntity(error) {
            ///<summary>
            /// Displays the error returned from SDK.Metadata.RetrieveEntity if it fails.
            ///</summary>
            setText(message, error.message);

        }

        function toggleDisplayAttributes() {
            ///<summary>
            /// toggles whether the list of attributes is displayed.
            ///</summary>

            if (this.parentElement.attributesDisplayed) {
                this.parentElement.lastChild.style.display = "none";
                this.parentElement.attributesDisplayed = false;
                this.title = "Click to show attributes.";


            }
            else {
                this.parentElement.lastChild.style.display = "block";
                this.parentElement.attributesDisplayed = true;
                this.title = "Click to hide attributes.";


            }

        }

        // setText and getText mitigate differences in how browsers set or get text content.
        function setText(node, text) {
            if (typeof (node.innerText) != "undefined") {
                node.innerText = text;
            }
            else {
                node.textContent = text;
            }

        }

        function getText(node) {
            if (typeof (node.innerText) != "undefined") {
                return node.innerText;
            }
            else {
                return node.textContent;
            }
        }

    </script>
</head>
<body style="font-family: Segoe UI;" onload="startSample()">
    <!--<h1>
        Metadata Demonstration Sample
    </h1>
    <p>
        This form requires JavaScript and will update the page dynamically.
    </p>-->
    <p>
        <!--<input id="dispalert" name="dispalert" type="checkbox" value="alert" /><label for="dispalert">Display alert window when data changes.</label> <br>-->
        Place Holder: <input type="text" name="PlaceHolder" id="placeholder"> <br />
        Entity : <select id="entityselect" name="Entities" onchange ="retrieveAttributes()"></select>
        Field : <select id="attributeselect" name="Attributes"></select>
    </p>
    <p>
        <label id="lblstartSample" for="btnstartSample">
        </label>
        <input type="button" id="btnstartSample" name="btnstartSample" value="Submit" onclick="btnSubmitValues()" />
        <!--<input type="button" id="btnstartSample" name="btnstartSample" value="Submit" onclick="startSample()" />-->
    </p>
    <div id="message">
    </div>
    <ul id="results"></ul>
</body>
</html>
<!--</snippetMetaDataDemo>-->


then you will see the page:




Tuesday 23 September 2014

download file form notes in crm 2013 using c # code.


aspx page :

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="download.aspx.cs" Inherits="pdfdownload.download" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
        <asp:Label ID="Namelabel" runat="server" Text="Name"></asp:Label>
&nbsp;&nbsp;
        <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
&nbsp;&nbsp;
        <asp:HyperLink ID="hyperdownload" runat="server">Download</asp:HyperLink>
   
        <asp:Button ID="btndownload" runat="server" OnClick="btndownload_Click" Text="Download" />
   
    </div>
    </form>
</body>
</html>


C# code :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.Xrm.Sdk;
//using pdfdownload.ServiceReference1;
using Xrm;
using Microsoft.Xrm.Sdk.Client;
using System.Net;
using System.ServiceModel.Description;
//using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using System.Text;
using System.IO;
//using Microsoft.Crm.Sdk.Samples;
namespace pdfdownload
{
    public partial class download : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {


        }

        protected void btndownload_Click(object sender, EventArgs e)
        {
            ClientCredentials Credentials = new ClientCredentials();
            Credentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials;
            //This URL needs to be updated to match the servername and Organization for the environment.
            Uri OrganizationUri = new Uri("http://win-qctbmlihah0:5555/CRM2013Vanilla/XRMServices/2011/Organization.svc");
            Uri HomeRealmUri = null;

            //OrganizationServiceProxy serviceProxy;       
            using (OrganizationServiceProxy serviceProxy = new OrganizationServiceProxy(OrganizationUri, HomeRealmUri, Credentials, null))
            {
                serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());
                IOrganizationService service = (IOrganizationService)serviceProxy;

                //Instantiate the contact object and populate the attributes.      
                string annotationID = "A9FE2781-FB3F-E411-971A-0800274C12EC";
              //  byte[] fileData = DownloadAttachment(annotationID);

                string firstname = txtName.Text;
                byte[] fileData = DownloadAttachment(firstname);
               
            }
        }
        public  byte[] DownloadAttachment(string AnnotationId)
        {
              byte[] newFile1 = new byte[10];
            ClientCredentials Credentials = new ClientCredentials();
            Credentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials;
            //This URL needs to be updated to match the servername and Organization for the environment.
            Uri OrganizationUri = new Uri("http://win-qctbmlihah0:5555/CRM2013Vanilla/XRMServices/2011/Organization.svc");
            Uri HomeRealmUri = null;
            Guid ObjectreferenceID = new Guid();
            string referencenumber = AnnotationId;
            //OrganizationServiceProxy serviceProxy;       
            using (OrganizationServiceProxy serviceProxy = new OrganizationServiceProxy(OrganizationUri, HomeRealmUri, Credentials, null))
            {
                serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());
                IOrganizationService service = (IOrganizationService)serviceProxy;


                ConditionExpression condition = new ConditionExpression();
                condition.AttributeName = "firstname";
                condition.Operator = ConditionOperator.Equal;
                condition.Values.Add(referencenumber);

                FilterExpression filter1 = new FilterExpression();
                filter1.Conditions.Add(condition);


                QueryExpression query = new QueryExpression("contact");

                query.ColumnSet.AddColumns("firstname",  "lastname","contactid");

                query.Criteria.AddFilter(filter1);

                EntityCollection result1 = serviceProxy.RetrieveMultiple(query);

                foreach (Entity entities in result1.Entities)
                {
                    //EntityReference var1 = (EntityReference)entities.Attributes["contactid"];
                    ObjectreferenceID = entities.Id;
                    
                }


                ConditionExpression AnnotationCondition = new ConditionExpression();
                AnnotationCondition.AttributeName = "objectid";
                AnnotationCondition.Operator = ConditionOperator.Equal;
                AnnotationCondition.Values.Add(ObjectreferenceID);

                FilterExpression AnnotationFilter = new FilterExpression();
                AnnotationFilter.Conditions.Add(AnnotationCondition);


                QueryExpression AnotationQuery = new QueryExpression("annotation");

                AnotationQuery.ColumnSet.AddColumns("filename", "documentbody", "annotationid");

                AnotationQuery.Criteria.AddFilter(AnnotationFilter);

                EntityCollection AnnotationResult = serviceProxy.RetrieveMultiple(AnotationQuery);

                Guid annotationId = new Guid();
              
                foreach (Entity entities in AnnotationResult.Entities)
                {
                    string filename = entities["filename"].ToString();
                    annotationId = entities.Id;

                    using (FileStream fileStream = new FileStream(filename, FileMode.OpenOrCreate))
                    {

                        byte[] newFile = Convert.FromBase64String(entities["documentbody"].ToString());
                        //EntityReference var1 = (EntityReference)entities.Attributes["annotationId"];
                        string nameoffile = filename;
                        // fileStream fs = fileStream.Read(newFile, 0, newFile.Length);
                        fileStream.Write(newFile, 0, newFile.Length);
                        fileStream.Read(newFile, 0, newFile.Length);
                        Response.ClearContent();
                        Response.Clear();
                        Response.BinaryWrite(newFile);
                        Response.AddHeader("Content-Disposition", "attachment; filename=" + nameoffile);
                        Response.End();


                        return newFile;

                    }

                }


                return newFile1;
            }
        }
    }
}

in this we will see the byte coversion also.