Thursday, December 30, 2010

Assign roles to users using Code

There are times when we need to assign roles promatically may plugin or else threu any applications suing the sdk.
here is the code to assign the role.
make sure u have the suer GUID and the roles GUIDs u wan to assign.
and keep it in mind that the higher role previlege will apply for that user.

private static void assignRole(Guid userGUID, Guid[] rolesGUID)
{
// Set up the CRM service.
CrmAuthenticationToken token = new CrmAuthenticationToken();
// You can use enums.cs from the SDK\Helpers folder to get the enumeration for Active Directory authentication.
token.AuthenticationType = 0;
token.OrganizationName = "Default";

CrmService service = new CrmService();
service.Url = "http://<server>:<port>/mscrmservices/2007/crmservice.asmx";
service.CrmAuthenticationTokenValue = token;
service.Credentials = System.Net.CredentialCache.DefaultCredentials;

// Create the request object.
AssignUserRolesRoleRequest assign = new AssignUserRolesRoleRequest();

// Set the properties of the request object.
assign.UserId = userGUID;
// Set the ID of a role that is in the same business unit as the user.
assign.RoleIds = rolesGUID;

// Execute the request.
AssignUserRolesRoleResponse assigned = (AssignUserRolesRoleResponse)service.Execute(assign);
}

Sudhanshu

Tuesday, December 21, 2010

Use Custom View in the in form MS CRM 4.0

There is some times a requirement like people want to use custom views in MS CRM form instead of the available views also with some filtering criterias.
This is how it will work.

The followings are the things need to be taken care
1. collect the entity details
2. create an IFRAME
3. make sure the columns you want to put are present in CRM and searchable(imp)
4. this is just a sample, change it as per your requirements
5. this is just showing the record which you have selected, by taking the guid

so check the code,against most of the lines we have comments which will make it easy

//the main function which will do the majic

function EmbedAdvancedFindView (iFrameId, entityName, fetchXml, layoutXml, sortCol, sortDescend, defaultAdvFindViewId, entityTypeId) {
// Initialize our important variables
var httpObj = new ActiveXObject("Msxml2.XMLHTTP");
var url = SERVER_URL + "/AdvancedFind/fetchData.aspx";
var iFrame = document.getElementById(iFrameId);
var win = iFrame.contentWindow;
var doc = iFrame.contentWindow.document;

// Provide a global function within the parent scope to avoid XSS limitations
// in updating the iFrame with the results from our HTTP request
PushResponseContents = function (iFrame, httpObj, entityTypeId) {
var win = iFrame.contentWindow;
var doc = iFrame.contentWindow.document;
var m_iFrameShowModalDialogFunc = null;
var m_windowAutoFunc = null;

// Write the contents of the response to the Iframe
doc.open();
doc.write(httpObj.responseText);
doc.close();

// Set some style elements of the Advanced Find window
// to mesh cleanly with the parent record's form
doc.body.style.padding = "0px";
doc.body.scroll="no";

// Should we overwrite the functionality of the "New" button?
if ((typeof(entityTypeId) != "undefined") && (entityTypeId != null)) {
var buttonId = "_MBopenObj" + entityTypeId;
var newButton = doc.getElementById(buttonId);

eval("newButton.action = 'locAddRelatedToNonForm(" + entityTypeId + ", " + crmForm.ObjectTypeCode + ", \"" + crmForm.ObjectId + "\",\"\");'");
}

// Swap the showModalDialog function of the iFrame
if (m_iFrameShowModalDialogFunc == null) {
m_iFrameShowModalDialogFunc = win.showModalDialog;
win.showModalDialog = OnIframeShowModalDialog;
}

if (m_windowAutoFunc == null) {
m_windowAutoFunc = win.auto;
win.auto = OnWindowAuto;
}

// Configure the automatic refresh functionality for dialogs
function OnIframeShowModalDialog(sUrl, vArguments, sFeatures) {
m_iFrameShowModalDialogFunc(sUrl, vArguments, sFeatures);
doc.all.crmGrid.Refresh();
}

function OnWindowAuto(otc) {
doc.all.crmGrid.Refresh();

m_windowAutoFunc(otc);
}
}

// Without a null src, switching tabs in the form reloads the src
iFrame.src = null;

// Preload the iFrame with some HTML that presents a Loading image
var loadingHtml = ""
+ "<table height='100%' width='100%' style='cursor:wait'>"
+ " <tr>"
+ " <td valign='middle' align='center'>"
+ " <img alt='' src='/_imgs/AdvFind/progress.gif' />"
+ " <div /><i>Loading View...</i>"
+ " </td>"
+ " </tr>"
+ "</table>";

doc.open();
doc.write(loadingHtml);
doc.close();

// Compile the FetchXML, LayoutXML, sortCol, sortDescend, defaultAdvFindViewId, and viewId into
// a list of params to be submitted to the Advanced Find form
var params = "FetchXML=" + fetchXml
+ "&LayoutXML=" + layoutXml
+ "&EntityName=" + entityName
+ "&DefaultAdvFindViewId=" + defaultAdvFindViewId
+ "&ViewType=1039" // According to Michael Hohne over at Stunnware, this is static
+ "&SortCol=" + sortCol
+ "&SortDescend=" + sortDescend;

// Establish an async connection to the Advanced Find form
httpObj.open("POST", url, true);

// Send the proper header information along with the request
httpObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
httpObj.setRequestHeader("Content-length", params.length);

// Function to write the contents of the http response into the iFrame
httpObj.onreadystatechange = function () {
if (httpObj.readyState == 4 && httpObj.status == 200) {
parent.PushResponseContents(iFrame, httpObj, entityTypeId);
}
}
//alert(params);
// Set it, and forget it! and enjoy :)
httpObj.send(params);
}

///*********************************************
//Create the objects

//get the current record's GUID
var IFRAME_Name = "IFRAME_Accounts";
var entityName = "new_residencestatus";

var currentGUID = crmForm.ObjectId.toString();


// Embed an AF window
fetchXml = ""
+ "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>"
+ " <entity name='new_residencestatus'>" //the enityname for whoch u want to create the view
+ " <attribute name='new_residencestatusid'/>" //columns u want to fetch
+ " <attribute name='new_name'/>" //same as above
+ " <order attribute='new_name' descending='false'/>" //for which column u want to order
+ " <filter type='and'>"
+ " <condition attribute='new_residencestatusid' operator='eq' value='" //pass your conditional value
+ currentGUID
+"'/>"
+ " </filter>"
+ " </entity>"
+ "</fetch>";

layoutXml = ""
+ "<grid name='resultset'>"
+ " <row name='result' id='new_residencestatusid'>" //be careful for this is , it should be same as the primarykey
+ " <cell name='new_name' width='150' />" //columns you want to show and fetched in the column list
+ " </row>"
+ "</grid>";

var sortColumnName = "new_name";
var sortDescend = "false";
var associatedViewGUID = "{93A408E0-A6E5-4149-9510-4EF333C0FC43}";
var objectTypeCode = crmForm.ObjectTypeCode.toString();

//call the master and majic method :)

EmbedAdvancedFindView(IFRAME_Name, entityName, fetchXml, layoutXml, sortColumnName, sortDescend, associatedViewGUID, objectTypeCode);

//hide the unnecessary menu bar from the grid

function hideViewMenu(){
var formview = document.all.IFRAME_Accounts;
if( formview.readyState != 'complete' )
return;

formview.contentWindow.document.getElementById("gridMenuBar").style.display = "none";
formview.contentWindow.document.getElementById("mnuBar1").parentNode.style.display = "none";
}
//hide the menubar from the view
var Form = crmForm.all.IFRAME_Accounts;
Form.attachEvent("onreadystatechange",hideViewMenu);
Sudhanshu

Monday, December 20, 2010

DateTime to CrmDateTime conversion

We all know that DateTime in C# is different than CrmDateTime.
In CrmDateTime we also have two things 1. UserTime and 2. UniversalTime.
To convert from normal DateTime to CrmDateTime follow the follwoing code.

public static CrmDateTime ConvertToCRMDateTime(DateTime dateTime)
{
CrmDateTime crmDateTime = new CrmDateTime();
crmDateTime.date = dateTime.ToShortDateString(); //assign the date
crmDateTime.time = dateTime.ToShortTimeString();//assign the time
//now create the offset from the timezone
TimeSpan offset = TimeZone.CurrentTimeZone.GetUtcOffset(dateTime);
string sOffset = string.Empty;
if (offset.Hours < 0)
{
sOffset = "-" + (offset.Hours * -1).ToString().PadLeft(2, '0') + ":";
}
else
{
sOffset = "+" + offset.Hours.ToString().PadLeft(2, '0') + ":";//":" is more inmportant
}
sOffset += offset.Minutes.ToString().PadLeft(2, '0');
crmDateTime.Value = dateTime.ToString(string.Format("yyyy/MM/ddTHH:mm:ss{0}", sOffset));
return crmDateTime; //finally return the CrmDateTime format
}

Sunday, December 19, 2010

Create a header with the form information in ms crm

Some times we need to show a header informations in ms crm 4.0.(but its available OTB in 5.0). as in pic.

just follw the followings and change ur attributes as per your requirements.

var elem = document.getElementById("leftNavBreadcrumbText");

var fullName = (crmForm.all.name.DataValue != null) ? crmForm.all.name.DataValue : "";
var NRIC = (crmForm.all.new_nric.DataValue != null) ? crmForm.all.new_nric.DataValue : "";
var handPhone= (crmForm.all.new_handphone.DataValue != null) ? crmForm.all.new_handphone.DataValue : "";

if (elem != null) {
var actualHTML = elem.innerHTML;
actualHTML += '
actualHTML
';
elem.innerHTML = actualHTML ;
}

Sudhanshu

Put a View in a form and on select of that record load the same to the Form in another Iframe

Its very frequent requirement.
like i want to put a view to the forma and on select(double click) it should load also to the same form(another iframe).

So just follow the following steps.
make sure the IFRAME names. change as per yours.

//*********************************************************************************
//put the two iframes and load the record on double cick of the record from one Iframe
//*********************************************************************************

//get the server url with port (if anything else 80) u can not really rely ;)
function getServerUrlWithPort()
{
return window.location.protocol + "//" + window.location.host ;
}

//this is for the
function OnGridViewReady()
{

var gridview = document.all.IFRAME_Grid;
if( gridview.readyState != 'complete' )
return;
gridview.contentWindow.document.getElementById('crmGrid_JumpBar').parentNode.parentNode.style.display = 'none';
gridview.contentWindow.document.getElementById("quickFindContainer").parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.style.display = "none";

gridview.contentWindow.document.getElementById("crmMenuBar").parentNode.parentNode.style.display = 'none';

var gridviewDocument = gridview.document.frames["IFRAME_Grid"].document;
var gridviewWindow = gridviewDocument.parentWindow;
gridviewWindow.open = OnWindowOpen;
gridviewDocument.body.scroll = "no";
}

//this will bind the url to the 2nd IFrame instead of opening it as new window
function OnWindowOpen( url )
{
var formview = document.all.IFRAME_Form;
//alert("aaaa"+url+"#######"+formview );
formview.src = getServerUrlWithPort() + url;

if (url != "/" + this.parent.ORG_UNIQUE_NAME + "/sfa/accts/edit.aspx")
return false;
}

//this will be fired when the form will be loaded to the 2nd IFrame
//hide the left nav area and other menu items also
function OnFormViewReady()
{
var formview = document.all.IFRAME_Form;

if( formview.readyState != 'complete' )
return;

formview.document.frames['IFRAME_Form'].document.body.style.border = "1px solid #6893cf";

if (formview.contentWindow.document.getElementById('leftNavBreadcrumbImg') == null)
return;
formview.contentWindow.document.getElementById('leftNavBreadcrumbImg').parentNode.parentNode.parentNode.parentNode.parentNode.style.display = 'none';
formview.contentWindow.document.getElementById('leftNavBreadcrumbImg').parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.height = '45';

formview.contentWindow.document.getElementById('crmMenuBar').parentNode.parentNode.style.display = 'none';
formview.contentWindow.document.getElementById('crmNavBar').parentNode.style.display = 'none';
formview.contentWindow.document.getElementById('tdAreas').colSpan = 2;
formview.contentWindow.document.getElementById('crmRenderStatus').parentNode.parentNode.style.display = 'none';
formview.contentWindow.document.getElementById('help').parentNode.parentNode.parentNode.parentNode.parentNode.style.display = 'none';

}

var Grid = crmForm.all.IFRAME_Grid;
var Form = crmForm.all.IFRAME_Form;
Grid.attachEvent("onreadystatechange",OnGridViewReady);
Form.attachEvent("onreadystatechange",OnFormViewReady);


//hide tab
crmForm.all.tab1Tab.style.display="none";

document.getElementById('help').style.display = "none";
document.getElementById('mnuDown').style.display = "none";
if(document.getElementById('navAsyncOperations') !=null)
{
document.getElementById('navAsyncOperations').style.display="none";
}

Sudhanshu