Thursday, October 20, 2011

Impersonation in CRM2011

Impersonate in Plugins:

ICrmService service = context.CreateCrmService(context.InitiatingUserId);
Instead of context.InitiatingUserId use the user guid of the user.

ICrmService service = context.CreateCrmService(userId);

To Impersonate in WebPages:
Create crmservice and assign callerid property to the user to be impersonated.

Friday, June 10, 2011

Date as per User Settings


//*********************************************************************
//**  DEFAULT DUE DATE:  UPON LOAD OF THE FORM, FOR CREATE ONLY, WE 
//**  SET THE DUE DATE TO THE CURRENT DATE AND TIME FOR THE CRM USER.
//*********************************************************************
var result = new Date();
if(crmForm.FormType ==1 )
{

fetchUserTime();
crmForm.all.scheduledend.DataValue = result;
}
//**************** **************************************
//*****************Get Current User ************************
//*******************************************************
function getCurrentUser()
{
//Create the XML that will fetch the required info.
var XMLRequest = "" + 
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" + 
"<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" + GenerateAuthenticationHeader() +
" <soap:Body>" + 
" <RetrieveMultiple xmlns=\"http://schemas.microsoft.com/crm/2007/WebServices\">" + 
" <query xmlns:q1=\"http://schemas.microsoft.com/crm/2006/Query\" xsi:type=\"q1:QueryExpression\">" + 
" <q1:EntityName>systemuser</q1:EntityName>" + 
" <q1:ColumnSet xsi:type=\"q1:ColumnSet\">" + 
" <q1:Attributes>" + 
" <q1:Attribute>systemuserid</q1:Attribute>" + 
" <q1:Attribute>fullname</q1:Attribute>" + 
" </q1:Attributes>" + 
" </q1:ColumnSet>" + 
" <q1:Distinct>false</q1:Distinct>" + 
" <q1:Criteria>" + 
" <q1:FilterOperator>And</q1:FilterOperator>" + 
" <q1:Conditions>" + 
" <q1:Condition>" + 
" <q1:AttributeName>systemuserid</q1:AttributeName>" + 
" <q1:Operator>EqualUserId</q1:Operator>" + 
" </q1:Condition>" + 
" </q1:Conditions>" + 
" </q1:Criteria>" + 
" </query>" + 
" </RetrieveMultiple>" + 
" </soap:Body>" + 
"</soap:Envelope>" + 
"";
try
{
//Create Http request object
var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
xmlHttpRequest.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
xmlHttpRequest.setRequestHeader("SOAPAction","http://schemas.microsoft.com/crm/2007/WebServices/RetrieveMultiple");
xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xmlHttpRequest.setRequestHeader("Content-Length", XMLRequest.length);
xmlHttpRequest.send(XMLRequest);

//Store the response which would be XML
var Result = xmlHttpRequest.responseXML;

/*
The return is of type "BusinessEntity" if you were using similar code one server side.
Hence we need to select node of type "BusinessEntity"

In our case It should be not more one than one node
*/
var BusinessEntityNodes = Result.selectNodes("//RetrieveMultipleResult/BusinessEntities/BusinessEntity");

// Check If data was retrived
if (BusinessEntityNodes.length != 0)
{
    var BusinessEntityNode = BusinessEntityNodes[0]; 
    var SystemUserId = BusinessEntityNode.selectSingleNode("q1:systemuserid");
    var FullName = BusinessEntityNode.selectSingleNode("q1:fullname");
    var SystemUserId = (SystemUserId == null) ? null : SystemUserId.text;
    var FullName = (FullName == null) ? null : FullName.text;
}
return SystemUserId ;
}
catch (e)
{
alert(e.message);
}

}
//****************************************************************************
//***********************Fetch User Time in CRM**********************************
//****************************************************************************
function fetchUserTime()
{
var xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + 
"  <soap:Header>" + 
"    <CrmAuthenticationToken xmlns=\"http://schemas.microsoft.com/crm/2007/WebServices\">" + 
"      <AuthenticationType xmlns=\"http://schemas.microsoft.com/crm/2007/CoreTypes\">0</AuthenticationType>" + 
"      <OrganizationName xmlns=\"http://schemas.microsoft.com/crm/2007/CoreTypes\">"+ORG_UNIQUE_NAME +"</OrganizationName>" + 
"      <CallerId xmlns=\"http://schemas.microsoft.com/crm/2007/CoreTypes\">00000000-0000-0000-0000-000000000000</CallerId>" + 
"    </CrmAuthenticationToken>" + 
"  </soap:Header>" + 
"  <soap:Body>" + 
"      <Request xsi:type=\"RetrieveUserSettingsSystemUserRequest\" ReturnDynamicEntities=\"true\">" + 
"        <EntityId>"+getCurrentUser()+"</EntityId>" + 
"        <ColumnSet xmlns:q1=\"http://schemas.microsoft.com/crm/2006/Query\" xsi:type=\"q1:ColumnSet\">" + 
"          <q1:Attributes>" + 
"            <q1:Attribute>timezonebias</q1:Attribute>" + 
"          </q1:Attributes>" + 
"        </ColumnSet>" + 
"      </Request>" + 
"    </Execute>" + 
"  </soap:Body>" + 
"</soap:Envelope>" + 
"";

var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");

xmlHttpRequest.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
xmlHttpRequest.setRequestHeader("SOAPAction","http://schemas.microsoft.com/crm/2007/WebServices/Execute");
xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
xmlHttpRequest.send(xml);

var resultXml = xmlHttpRequest.responseXML;
//Create an XML document that can be parsed.
var oXmlDoc = new ActiveXObject("Microsoft.XMLDOM");
oXmlDoc.async = false;
oXmlDoc.loadXML(resultXml.xml);
//Value the user is interesed in in string form
var times = oXmlDoc.getElementsByTagName("Property");
var difference = Number(times[0].text);

//And the result - Date object
var gmtday= result.getUTCDate();
var gmtmonth = result.getUTCMonth();
gmtmonth=gmtmonth;
var gmtYear = result.getUTCFullYear();
var gmthours = result.getUTCHours();
var gmtminutes = result.getUTCMinutes();

result.setFullYear(gmtYear);
result.setMonth(gmtmonth);
result.setDate(gmtday);
result.setHours(gmthours);
result.setMinutes(gmtminutes);
result.setMinutes ( result.getMinutes() - difference);
}

//********************************************************************
//***************End of Fetch User Time**********************************
//********************************************************************

Tuesday, May 3, 2011

Modify Views of System entities

I had always been thinking that queue views cannot be modified. Thanks to Vince Bullinger i found out how to do that.
go to Workplace/home_workplace.aspx. 


just alert the sViewId from this method. 

function nodeSelect( sQueueId, sViewId, sMenuId )
{
crmGrid.SetParameter("viewid", sViewId);
crmGrid.SetParameter("qid", sQueueId);
crmGrid.Reset();
resetMenuItems(sMenuId);
}

use the following url:
http://crm/tools/viewEditor/viewManager.aspx?id={00000000-0000-0000-00AA-000010001400}
crm - your organisation name 
id = the alerted sViewId. 

You can change the view and then publish all customizations. View is now customized. 





Wednesday, April 13, 2011

filtered lookup in Jscript


crmForm.all.new_subcategoryid.AddParam("search","<fetch mapping='logical'><entity name='new_casesubcategory'><filter><condition attribute='new_categoryid' operator='eq' value='" + crmForm.all.new_categoryid.DataValue[0].id + "' /></filter></entity></fetch>");

Tuesday, April 12, 2011

GridView/Listviews do not retain values inside CRM but work fine in dev environment

You need to enableviewstate in web.config file

<pages enableViewState="true">
or
do the same individually at pagelevel

as <@Page EnableViewState="true" />










A common issue raised in the CRM Development forum is of custom web pages that work correctly in a development environment, but then fail to work when deployed into the CRM web site. The most common reason for this is that the CRM web.config overrides some of the default ASP.Net configuration settings.

The relevant entries in the CRM web.config (in the root of the CRM web site) are:

<pages buffer="true" enableSessionState="false" enableViewState="false" validateRequest="false/">
<sessionState mode="Off"/>

These have 2 main consequences:

  1. Session State is disabled. This issue is relatively easy to diagnose, as you tend to get a clear error message if trying to use session state when it is disabled
  2. ViewState is disabled. This can be a more subtle effect, as developers often rely on viewState without necessarily being aware of it. ViewState is what allows ASP.Net web controls to maintain property values across web requests; if it is disabled then it leads to symptoms such as values not being retained, or list boxes losing their contents
The solution for viewState is straightforward. You can reenable viewState for you application either in the web.config in your application directory, or at the page level within the <@Page> directive. These looks like the following:
web.config:
<pages enableViewState="true" />
Page directive:
<@Page EnableViewState="true" />
Session state is a bit more complex, as this is configured at the web application level. Personally, I've never seen any reason to use session state within custom code in the CRM web site; CRM doesn't use this, and I find it best to mimic CRM behaviour wherever possible.
And one final point about best practise; as this post demonstrates, it is best not to rely on the default ASP .Net configuration settings, rather I find it best to always explicitly enable or disable settings in the local web.config

Monday, April 11, 2011

Attach and Retrieve files and notes/annotations

---------------------------------ASPX------------------------------------

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="CaseNotes.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Case History</title>
  
</head>
<body>
    <form id="form1" runat="server">
    <div>

        <table width="100%">
        <tr style="width:100%">
        <td style="width:90%">
                <asp:Label Text="Title" ID="lblTitle" Width="10%" runat="server" Font-Bold="true" Font-Names="Tahoma" Font-Size="Small"></asp:Label>
            </td>
            </tr>
         <tr style="width:100%">
            <td style="width:100%">
            <asp:TextBox ID="txtTitle" runat="server" TextMode="SingleLine"
                    Width="90%"  Font-Names="Tahoma"  Font-Size="Small"></asp:TextBox>
    </td>    
        </tr>
            <tr style="width:100%"><td >
                <asp:Label ID="Message" runat="server" Text="Comments" Font-Bold="true" Font-Names="Tahoma" Font-Size="Small" ></asp:Label>
            </td>
            </tr>
            <tr style="width:100%">
            <td style="width:100%">
            <asp:TextBox ID="txtNotes" runat="server" TextMode="MultiLine"
                    Height="91px" Width="90%"  Font-Names="Tahoma"  Font-Size="Small"></asp:TextBox>
    </td>    
        </tr>
        </table>
        <table width="90%">
        <tr style="width:100%">
             <td style="width:50%">
                <asp:Label ID="lblAttach" runat="server" Text="Attach a File "  Font-Bold="true"  Font-Names="Tahoma" Font-Size="Small"
                    ></asp:Label>
              <asp:FileUpload ID="FileUpload1" runat="server"  Font-Names="Tahoma" Font-Size="Small"/>
</td><td style="width:50%" align="right">
      <asp:Button ID="btnAddNotes" runat="server" Text="Add Case Notes"
            onclick="btnAddNotes_Click" Font-Bold="true"  Font-Names="Tahoma" Font-Size="Small"/>
        </td>
        </tr>
        </table>

       <%-- <asp:TextBox ID="txtHistory" runat="server" Height="299px" Width="777px" TextMode="MultiLine" Visible="false"></asp:TextBox>
        <asp:Panel ID="pnlHistory" runat="server" Height="299px" Width="777px" Direction="LeftToRight" HorizontalAlign="Justify" Visible="false">
        <asp:Table ID="tblhistory" runat="server" Width="100%" HorizontalAlign="Left">
        </asp:Table>
        </asp:Panel>--%>
        <asp:GridView ID="gvNotes" runat="server" onrowdatabound="gvNotes_RowDataBound"
            CellPadding="4" ForeColor="#333333"
            GridLines="None" AutoGenerateColumns="False" Width="100%"
            ShowHeader="False" Font-Names="Tahoma" Font-Size="Small" EnableViewState="true">
            <RowStyle BorderColor="White" BorderWidth="0px" BackColor="#F7F6F3"
                ForeColor="#333333" />
            <Columns>
                <asp:BoundField DataField="User" HeaderText="User" />
                <asp:BoundField HeaderText="Comments" DataField="Comments" ItemStyle-VerticalAlign="Bottom" HeaderStyle-Width="90%"/>
                <asp:BoundField HeaderText="AnnotationId" DataField="AnnotationId" />
                <asp:TemplateField  ItemStyle-VerticalAlign="Bottom" HeaderStyle-Width="10%">
                    <ItemTemplate>
                        <asp:LinkButton ID="downloadBtn" runat="server" onclick="downloadBtn_Click" Text="Download" Font-Bold="true"></asp:LinkButton>
                    </ItemTemplate>
                    <HeaderStyle BackColor="White" />
                    <ItemStyle BackColor="White" />
                </asp:TemplateField>            
            </Columns>
            <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
            <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
            <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <EditRowStyle BackColor="#999999" />
            <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
        </asp:GridView>
        </div>
    </form>
</body>
</html>

------------------------------------------CODE BEHIND------------------------------------------------



using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Microsoft.Crm.Sdk;
using Microsoft.Crm.SdkTypeProxy;
using Microsoft.Crm.Sdk.Query;
using System.IO;
using System.Text;



public partial class _Default : System.Web.UI.Page
{
    //string caseId = string.Empty;
    string caseId = "74F4528F-FD61-E011-A0F7-001CC4A7FE9A";
    CrmService crmservice = GetCrmService(ConfigurationManager.AppSettings["CrmServerURL"].ToString(), ConfigurationManager.AppSettings["orgName"].ToString());
    DataTable notestable = new DataTable();


    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["caseId"] != null)
        {
            caseId = Request.QueryString["caseId"].ToString();
        }
      
        //notestable = new DataTable();

        notestable.Columns.Add("User");
        notestable.Columns.Add("Comments");
        notestable.Columns.Add("AnnotationId");
      
        if (!IsPostBack)
        {
            setNotes(caseId);
            BindData();
        }
        //if (!IsPostBack)
        //{
        //    BindData();
        //}

    }

    private void BindData()
    {
        gvNotes.DataSource = notestable;
        gvNotes.DataBind();
    }

    private void setNotes(string caseId)
    {
      
        RetrieveMultipleRequest retrieve = new RetrieveMultipleRequest();
        retrieve.ReturnDynamicEntities = true;

        QueryExpression query = new QueryExpression();
        query.ColumnSet = new AllColumns();
        query.EntityName = EntityName.annotation.ToString();

        FilterExpression filter = new FilterExpression();
        ConditionExpression ce = new ConditionExpression();
        ce.AttributeName = "objectid";
        ce.Operator = ConditionOperator.Equal;
        ce.Values = new object[] { caseId };
        filter.Conditions.Add(ce);

        OrderExpression order = new OrderExpression();
        order.AttributeName = "createdon";
        order.OrderType = OrderType.Descending;

        query.Orders.Add(order);
        query.Criteria = filter;

        retrieve.Query = query;

        try
        {
            RetrieveMultipleResponse response = (RetrieveMultipleResponse)crmservice.Execute(retrieve);
            if (response.BusinessEntityCollection != null && response.BusinessEntityCollection.BusinessEntities.Count > 0)
            {
                //txtHistory.Text = "";


                foreach (BusinessEntity be in response.BusinessEntityCollection.BusinessEntities)
                {
                    DataRow newRow = notestable.NewRow();
                    string strStatus = string.Empty;
                    string strUser = string.Empty;
                    DynamicEntity de = (DynamicEntity)be;
                    Lookup lkpUser = ((Lookup)(de.Properties["createdby"]));
                    if (lkpUser.name.ToString().ToLower().Equals("crmadmin prd"))
                    {
                        incident newincident = getCaseDetails(caseId);
                        Customer customer = new Customer();
                        customer = newincident.customerid;
                        CrmDateTime created = (CrmDateTime)(de.Properties["createdon"]);

                        strUser = strUser + customer.name + " on " + created.date + " " + created.time + ": ";                      
                    }
                    else
                    {
                        CrmDateTime created = (CrmDateTime)(de.Properties["createdon"]);
                        strUser = strUser + lkpUser.name + " on " + created.date + " " + created.time + ": ";
                    }
                    if (de.Properties.Contains("subject"))
                    {
                        strUser = strUser + de.Properties["subject"];
                    }
                    newRow["User"] = strUser;
                    newRow["Comments"] = strUser;
                    notestable.Rows.Add(newRow);
                    DataRow newsubrow = notestable.NewRow();
                  
                    if (de.Properties.Contains("notetext"))
                    {
                        strStatus = strStatus + de.Properties["notetext"].ToString() + " \n";
                        newsubrow["AnnotationId"] = string.Empty;
                    }
                  
                        if (de.Properties.Contains("filename"))
                        {
                            strStatus = strStatus + " Uploaded Document " + de.Properties["filename"] + " \n";
                            Key annotationid = (Key)(de.Properties["annotationid"]);
                            newsubrow["AnnotationId"] = annotationid.Value.ToString();
                        }
                  
                    // txtHistory.Text += strStatus;
                        newsubrow["Comments"] = strStatus;
                    notestable.Rows.Add(newsubrow);
                }
                //gvNotes.Visible = true;
            
            }
            //else
            //{
            //    gvNotes.Visible = false;
            //}

          
        }
        catch (System.Web.Services.Protocols.SoapException ex)
        {
        }
        catch (Exception ex)
        {
        }

    }

    private incident getCaseDetails(string caseId)
    {
        incident newincident = new incident();
      
        try
        {
            newincident = (incident) crmservice.Retrieve(EntityName.incident.ToString(), new Guid(caseId), new AllColumns());
        }
        catch (System.Web.Services.Protocols.SoapException ex)
        {
        }
        catch (Exception ex)
        {
        }
        return newincident;
    }
    private annotation getAnnotationDetails(string annotationId)
    {
        annotation newannotation = new annotation();
        try
        {
            newannotation = (annotation)crmservice.Retrieve(EntityName.annotation.ToString(), new Guid(annotationId), new AllColumns());
        }
        catch (System.Web.Services.Protocols.SoapException ex)
        {
        }
        catch (Exception ex)
        {
        }
        return newannotation;
    }
    protected void btnAddNotes_Click(object sender, EventArgs e)
    {
        annotation newannotation = new annotation();
        if (!FileUpload1.HasFile)
        {
            if (txtNotes.Text == "" || txtNotes.Text == string.Empty)
            {
                ClientScript.RegisterStartupScript(typeof(Page), "NoDocAlert", "<script>alert('There are no user comments or document selected. Please enter comments or select a document for adding');</script>");
                return;
            }
            newannotation.isdocument = new CrmBoolean(false);
        }
        else
        {
            newannotation.isdocument = new CrmBoolean(true);
        }
        newannotation.notetext = txtNotes.Text;
        newannotation.subject = txtTitle.Text;
        //newannotation.subject = txtSubject.Text;
        Lookup lkpCase = new Lookup();
        lkpCase.type = EntityName.incident.ToString();
        lkpCase.Value = new Guid(caseId);
        newannotation.objectid = lkpCase;
      
            EntityNameReference reference = new EntityNameReference("incident");
            newannotation.objecttypecode = reference;

            CrmService crmservice = GetCrmService(ConfigurationManager.AppSettings["CrmServerURL"].ToString(), ConfigurationManager.AppSettings["orgName"].ToString());
            CreateRequest create = new CreateRequest();
            TargetCreateAnnotation target = new TargetCreateAnnotation();
            target.Annotation = newannotation;
            create.Target = target;
            try
            {
                CreateResponse created = (CreateResponse)crmservice.Execute(create);
                Guid createdNoteId = created.id;
                if (FileUpload1.HasFile)
                {            
                    byte[] byteData = new byte[FileUpload1.FileBytes.Length];
                    byteData = FileUpload1.FileBytes;
  
                    // Encode the data using base64.
                    string encodedData = System.Convert.ToBase64String(byteData);

                    annotation updateNote = new annotation();
                    updateNote.annotationid = new Key();
                    updateNote.annotationid.Value = createdNoteId;
                    updateNote.documentbody = encodedData;
                    updateNote.filename = FileUpload1.FileName;
                    crmservice.Update(updateNote);
                }
              
            }
            catch (System.Web.Services.Protocols.SoapException ex)
            {
            }
            catch (Exception ex)
            {
            }
            clearControls();
      
    }

    private void clearControls()
    {
        txtTitle.Text = "";
        txtNotes.Text = "";
       // txtSubject.Text = "";
        notestable.Clear();
        setNotes(caseId);
        BindData();
    }

    /// <summary>
    /// Set up the CRM Service.
    /// </summary>
    /// <param name="organizationName">My Organization</param>
    /// <returns>CrmService configured with AD Authentication</returns>
    private static CrmService GetCrmService(string crmServerUrl, string organizationName)
    {
        // Get the CRM Users appointments
        // Setup the Authentication Token
        if (crmServerUrl == null || crmServerUrl == string.Empty)
        {
            crmServerUrl = ConfigurationManager.AppSettings["CrmServerURL"].ToString();
        }
        CrmService crmService = new CrmService();
        CrmAuthenticationToken token = new CrmAuthenticationToken();
        token.OrganizationName = organizationName;
        token.AuthenticationType = 0;
        if (crmServerUrl != null &&
            crmServerUrl.Length > 0)
        {
            UriBuilder builder = new UriBuilder(crmServerUrl);
            builder.Path = "//MSCRMServices//2007//CrmService.asmx";
            crmService.Url = builder.Uri.ToString();
        }

        crmService.Credentials = System.Net.CredentialCache.DefaultCredentials;
        crmService.CrmAuthenticationTokenValue = token;
        return crmService;
    }
  
    protected void downloadBtn_Click(object sender, EventArgs e)
    {
       //BindData();
        LinkButton _lnkButton = (LinkButton)sender;
        GridViewRow gvRow = (GridViewRow)((_lnkButton).Parent.Parent);
        string annotationId = gvRow.Cells[2].Text;
        annotation newannotation = getAnnotationDetails(annotationId);
      
           string[] extensions = newannotation.filename.Split('.');
           string ext = extensions[extensions.Length - 1];
          // byte[] fileContent = new UTF8Encoding(true).GetBytes(newannotation.documentbody);
           byte[] fileContent = Convert.FromBase64String(newannotation.documentbody);
                Response.ClearContent();
                Response.AddHeader("Content-Disposition", "attachment; filename=" + newannotation.filename);
                Response.AddHeader("Content-Length", newannotation.filesize.Value.ToString());
                Response.ContentType = ReturnExtension("."+ext);
                Response.BinaryWrite(fileContent);
                Response.End();

    }
    protected void gvNotes_RowDataBound(object sender, GridViewRowEventArgs e)
    {

        GridViewRow gvRow = (GridViewRow)e.Row;
        if (gvRow.Cells[0].Text != "&nbsp;")
        {
            gvRow.Cells[1].Style.Add(HtmlTextWriterStyle.FontWeight, "Bold");
        }
        //else
        //{
        //    gvRow.Cells[1].Text = "<p>" + gvRow.Cells[1].Text + "</p>";
        //}
        if (gvRow.Cells[2].Text == string.Empty || gvRow.Cells[2].Text == "&nbsp;")
        {
            gvRow.Cells[3].Style.Add("display", "none");
        }
        else
        {
        }
        gvRow.Cells[2].Style.Add("display", "none");
        gvRow.Cells[0].Style.Add("display", "none");
    
    }
    private string ReturnExtension(string fileExtension)
    {
        switch (fileExtension)
        {
            case ".htm":
            case ".html":
            case ".log":
                return "text/HTML";
            case ".txt":
                return "text/plain";
            case ".doc":
                return "application/ms-word";
            case ".tiff":
            case ".tif":
                return "image/tiff";
            case ".asf":
                return "video/x-ms-asf";
            case ".avi":
                return "video/avi";
            case ".zip":
                return "application/zip";
            case ".xls":
            case ".csv":
                return "application/vnd.ms-excel";
            case ".gif":
                return "image/gif";
            case ".jpg":
            case "jpeg":
                return "image/jpeg";
            case ".bmp":
                return "image/bmp";
            case ".wav":
                return "audio/wav";
            case ".mp3":
                return "audio/mpeg3";
            case ".mpg":
            case "mpeg":
                return "video/mpeg";
            case ".rtf":
                return "application/rtf";
            case ".asp":
                return "text/asp";
            case ".pdf":
                return "application/pdf";
            case ".fdf":
                return "application/vnd.fdf";
            case ".ppt":
                return "application/mspowerpoint";
            case ".dwg":
                return "image/vnd.dwg";
            case ".msg":
                return "application/msoutlook";
            case ".xml":
            case ".sdxl":
                return "application/xml";
            case ".xdp":
                return "application/vnd.adobe.xdp+xml";
            default:
                return "application/octet-stream";
        }
    }
}

Friday, April 1, 2011

set activityparty onload of crmform


var lookupItem1 = new Array();
lookupItem1[0] = new LookupControlItem ('303232C2-3622-E011-895A-0003FFD4167C',8,'Dr. RK Sharma')
lookupItem1[1] = new LookupControlItem ('50511D55-F422-E011-82C2-0003FFD4167C',2,'John Chen')
crmForm.all.requiredattendees.DataValue = lookupItem1 ;

Wednesday, March 2, 2011

format integer field -- value without commas


if(crmForm.all.new_test1.DataValue!=null){
crmForm.all.new_test1.value = crmForm.all.new_test1.DataValue;
}