Abin Jaik Antony

its all about my work & life….

Translating Text (NOT regular files & sites) using SharePoint 2013 Machine Translation Service Application

Posted by Abin Jaik Antony on March 14, 2014

Sharepointers,

Recently I came across a very simple requirement from our customer to create a ‘Plain text translation utility Webpart’ on our SharePoint 2013 portal. Presently we have components related to document translation, which is sole purpose of SP 2013 Machine Translation Service (MTS) Application.By default, all object models functionality of MTS on SharePoint 2013 (CSOM, SOM, JSOM) has support to ‘Translate’ the documents. While searching on internet we will come across many articles or documentations explaining the document translation (one good article from MSDN is over here). But there is no straight forward API function to translate the TEXT data, which can provide functionality similar to Google or Bing Text Translation. 

Of course, we can tweak the existing API functions to achieve this functionality.  So below mentioned code explains how we can achieve this.

//Getting the Source text from input control.
            string somestring = txtSource.Text;

            //Retreiving the Service Context of the Site
            SPServiceContext sc = SPServiceContext.GetContext(new SPSite("http://server/sites/MTS/"));

            //Converting the input text to byte array
            byte[] inputByte = Encoding.ASCII.GetBytes(somestring);

            //Creating Synchronised translation job with target language as SPANISH
            SyncTranslator job = new SyncTranslator(sc, CultureInfo.GetCultureInfo("es"));

            byte[] outputByte = null; //byte array variable to get the output.

            //Translate using the "Translate" function of Sync.Job with input text's byte array.
            //Provided a dummy file extension type as "txt" - Here we are not specifying any output file path.
            TranslationItemInfo itemInfo = job.Translate(inputByte, out outputByte, "txt");

            //Converting the translated byte[] to text using UTF8 encoding.
            string result = Encoding.UTF8.GetString(outputByte);

            txtTarget.Text = result; // providing the result to the output text control.

So the trick on the above mentioned code is to use the overload for translating byte[] of the “Translate” function under Translation Sync.Job, then utilize the translated output byte[] to display the result after proper encoding.(UTF8 in this sample) to the text.

The utility webpart created using above code will look like this.

Posted in CodeProject, Sharepoint, Technical Posts | Tagged: , , | Leave a Comment »

Formatting Date, Number Data on BCS OOB Business Data List Webpart

Posted by Abin Jaik Antony on February 26, 2014

SharePointers,

Recently I came across an interesting issue/requirement with our Business Data List WebPart. The issue is “Data fetched from an External datasource via  BCS (External Content Type) need to be displayed on OOB Business DataList Webpart with proper formatting and  sorting”. Here, By formatting it means that numbers should be displayed like XXX,XXX or X,XXX and date should display in MM/DD/YYYY format without time part.

From the first look of it, we can easily acheive this by doing  a formatting from Database side. Means for a date data it can be done like

SELECT CONVERT(varchar(10),GETDATE(),3) + ' ' + CONVERT(varchar(10),GETDATE(),8)

and for numbers it can be done like

CONVERT(varchar(50), CAST(1112 AS money), 1)

Both the above approaches will work perfectly to solve the “formatting” requirement but fails for “sorting”. Because in both cases data is converted to type “string” so sorting will fails to work.

The same issue will occur if we try to solve it in any middle tier like WCF or .NET BCS Provider

In the above scenario, to accomplish the requirement of sorting & formatting we dont require to “CONVERT” the data from its base type to “string”. Let the data (date or number) come to SharePoint in its base type(DateTime or INT, DECIMAL etc). From the place where it display we can change its formatting even if it is an Out-Of-Box Business Data List Webpart”.

Yes. We can do it with the help normal “XSLT” functions WITHOUT opening the SharePoint Designer”

Follow the below mentioned steps to crack it out

  • Configure the OOB Business Data List Webpart with our External Content Type(ECT) and View. This is a regular step to display External Data. After this step we can see the data listing without the formatting.
  • In this step we need to take the existing XSL styles of the data listing webpart. For this we need to do the “Edit Webpart” and from the Webpart properties toolbox find the “XSL Editor” button. Click on it, it will pop up the XSL style. Copy the whole XSL and paste it to a Visual Studio instance(or any other good editor).
  • Find the XSL parameter which we need to format. Assume its a number which need to formatted like “#,###”. So here we need apply the XSLT function, “format-number“.

<xsl:value-of select="format-number(@AmountUSD, '#,###')" />

For the date formatting we can use like this

 <xsl:value-of select="ddwrt:FormatDateTime(@ActivityDate, 1033, 'MM/dd/yyyy')" />

  • Take the edited XSL & paste it back to the XSL Editor box on the Webpart properties toolbox. Save the XSL and Press OK on the webpart toolbox. You can see the formatted data

Note :  By  this approach it will perfectly format listing data on the BCS Out of the box Business Data list web part without doing any custom scripts or code, But the data on the filter drop downs will not get formatted.

Posted in CodeProject, Sharepoint, Technical Posts | Leave a Comment »

Organization/Hierarchy Chart on SharePoint (using jquery, Javascipt-CSOM)

Posted by Abin Jaik Antony on August 14, 2013

Hi developers,

This time I have a very interesting stuff for you guys. Few days back I got a tricky requirement from one of my customers , its about populating their organizational structure dynamically on their  SharePoint Intranet site without any server side components /Code. Means – there will be a SharePoint list from where data will  be pulled and on a Webpart(CEWP or OOB WP) the hierarchy need to be displayed. Fortunately within few hours I was able to integrate 2-3 things with some javascript / jquery code to accomplish this requirement.  Things require to cook out are

  • jQuery
  • jQuery OrgChart PlugIn  – Kindly read the technical artifacts of jQuery OrgChart from this location.
  • Content Editor WebPart
  • SharePoint Javascript CSOM
  • a SharePoint list
  • jQuery Balloon Plug In – If need to show any additional data

The scenario, I am going to demonstrate here is  to create a corporate organizational structure. For example, CEO on the top then COO, CFO, CTO  then Excutive VPs, AVPs then comes Directors,Managers  after that core execution team.

So, Here we start.

1. Create a custom SharePoint list having  columns like Title, Manager, Designation .Enter some logical details as mentioned below.

List data for populating Org Chart

 

 

 

 

 

 

 

 

 

2. Download and place Jquery & jQuery OrgChart plug-in files into the hive’s _layouts folder(see image below).Note : When we  are going through a solution deployment approach we need to place these files inside SP Project to package it to a WSP file.  Here we are directly copying files to _layouts folder just for the sake of demo. If needed you can place the jQuery Balloon file too.

jqueryPlugInFiles

 

 

 

 

 

 

3.Creating the Content Editor WebPart / Script editor WP – Script source file. Save the below mentioned code to a txt file and upload it to the SiteAssets Library. Give the path of the file to CEWP  like  “/SiteAssets/ScriptstxtFile.txt” or directly use this script to your client component.

<link rel="stylesheet" href="_layouts/jquery.orgchart.css" /></pre>
<link rel="stylesheet" href="_layouts/jquery-ui-1.10.3.custom.css" />

<script src="_layouts/jquery-1.9.1.js"></script>
<script src="_layouts/jquery-ui-1.10.3.custom.js"></script>
<script src="_layouts/jquery.orgchart.js"></script>
<script src="_layouts/jquery.balloon.js"></script>

<!--This div will be populated with the <ul><li> structure from the SCOM returned objects-->
<div id="left">
</div>
<style>
 div.node.bladerunner {
 background-color: #a4a0d9 !important;
 }

div.node.replicant {
 background-color: #d9ada0 !important;
 }

div.node.deceased {
 background-color: #d9d2a0 !important;
 text-decoration: line-through;
 }

div.node.retired {
 background-color: #d9c0a0 !important;
 text-decoration: line-through;
 }
</style>

<!--Main Org Structure will pupulate under this DIV-->
<div id="content">
 <div id="main">
 </div>
</div>

<script type="text/javascript">

//loading SharePoint Javascript SCOM
 ExecuteOrDelayUntilScriptLoaded(loadStructure, "sp.js");

//calling the executing function
 function loadStructure() {

//Querying SP using SCOM
 var context = new SP.ClientContext.get_current();
 var web = context.get_web();
 var list = web.get_lists().getByTitle("Employee"); //Employee is SP List containing heirarchy data of the Orgnization
 var viewXml = '<View><RowLimit>1200</RowLimit></View>';
 var query = new SP.CamlQuery();
 query.set_viewXml(viewXml);
 this.items = list.getItems(query);
 context.load(items, 'Include(Title, Manager,Designation)');
 context.add_requestSucceeded(onLoaded);
 context.add_requestFailed(onFailure);
 context.executeQueryAsync();

function onLoaded() {
 //Adding SCOM return objects to an array
 var tasksEntries = [];
 var itemsCount = items.get_count();
 for (i = 0; i < itemsCount; i++) {
 var item = items.itemAt(i);
 var taskEntry = item.get_fieldValues();
 tasksEntries.push(taskEntry);
 }
 //array's filter function wont work in IE8. Hence GetChildArrayObjects
 //var topHead = tasksEntries.filter(function (item) { return (item.Manager == null) });
 var topHead = GetChildArrayObjects(tasksEntries, null);

/////Logic to create <ul><li>....</li></ul> for jQuery orgChart -- ####Starts Here
 var headName = topHead[0].Title;

var title = topHead[0].Designation + ", Manager :" + topHead[0].Manager;

var listString = "<ul id='organisation'><li class='hide' title='" + headName + "'>" + headName;

//Calling the recursive function.getChildNodes
 var childliststring = getChildNodes(tasksEntries, headName, listString);

listString = childliststring + "</li></ul>";

var divForList = document.getElementById('left');
 divForList.innerHTML = listString;
 /////Logic to create <ul><li>....</li></ul> for jQuery orgChart -- ####Ends Here

//Populating OrgChart using Jquery OrgChart Plug in - Basically it reads Created <ul><li> list named 'organisation' and writes a TABLE - DIV structure.
 $("#organisation").orgChart({ container: $("#main"), nodeClicked: onChartNodeClicked });

//enabling balloon for each orgchart block
 for (var i = 0; i < tasksEntries.length; i++) {

$("div[title=\"" + tasksEntries[i].Title + "\"]").balloon({
 contents: '<img src ="/Images1/_t/images_jpg.jpg"/></br><ul><li> Designation :' + tasksEntries[i].Designation + '</li><li>Phone# : 123-234-1233</li></ul>'

});

}

}
 //Handled event for node clicked.
 function onChartNodeClicked(node) {
 //If we need to do anything specific when clicking a node.
 }
 function onFailure() {
 alert('script failed');
 }
 }

 //Recursive function to create <ul><li> organization structure.
 function getChildNodes(tasksEntries, headName, liststring) {

//var childs = tasksEntries.filter(function (item) { return (item.Manager == headName) });
 var childs = GetChildArrayObjects(tasksEntries, headName);

if (childs.length > 0) {

liststring = liststring + "<ul>";
 for (var cnt = 0; cnt < childs.length; cnt++) {
 var head = childs[cnt].Title;
 var title = childs[cnt].Designation + ", Manager :" + childs[cnt].Manager;
 liststring = liststring + "<li class='bladerunner' title='" + head + "'>" + head;
 liststring = getChildNodes(tasksEntries, head, liststring);
 liststring = liststring + "</li>";
 }

liststring = liststring + "</ul>";
 }

return liststring;
 }

//Alternative function for .filter function to query child objects for a parent in an array
 function GetChildArrayObjects(items, manager) {

var newArray = [];
 for (var i = 0; i < items.length; i++) {
 var item = items[i];
 if (item.Manager == manager) {
 newArray.push(item);
 }
 }

return newArray;
 }

</script>

JQuery OrgChart basically needs a <ul><li> (unordered list) format for populating the Org-Chart. So I am querying the SP List using the SCOM(javascript) and using a recursive function (getChildNodes) the <ul><li> structure is created. After loading this <ul><li> structure I call the jquery orgchart function to populate the hierarchy on the other <div>

The main checkpoints on the above script are :

  • loadStructure() – JS Function uses SharePoint JS SCOM to Query the list to get the Parent-Child Hierarchy.
  • GetChildArrayObjects() – its an alternative to .filter JS function since this is not supported on IE8.
  • getChildNodes – Recursive function mentioned above – Which basically structures the unordered list.(see the <ul> mentioned on image below)
  • $(“#organisation”).orgChart({ container: $(“#main”), nodeClicked: onChartNodeClicked });   – This line of  jQuery code in the above script actually reads the <ul><oli> and generate the OrgChart.  While you skim the above code, you will be able to see a <ul> with ID as ‘organisation’ created which is read and org chart is populated to a <DIV> ‘main’
  • After creating the orgChart, I am iterating through the <DIV> of the OrgChart block according to its ID to enable the ballon

//enabling balloon for each orgchart block
for (var i = 0; i < tasksEntries.length; i++) {

$("div[title=\"" + tasksEntries[i].Title + "\"]").balloon({
contents: '<img src ="/Images1/_t/images_jpg.jpg"/></br><ul><li> Designation :' + tasksEntries[i].Designation + '</li><li>Phone# : 123-234-1233</li></ul>'

});

Finally the OrgChart is populated as displayed below.  You can see a <ul><li> list on the top, which can made to visible=false to the <DIV> with ID ‘left’ on the above mentioned script, displayed only for testing purpose.

orgChart

Hope you have enjoyed this article, Kindly let me know if  there is any issues .


			

Posted in CodeProject, Sharepoint, Technical Posts | Tagged: , , , , | 14 Comments »

Custom XML mapping of content control in a SharePoint Document Library Template

Posted by Abin Jaik Antony on May 3, 2012

Hi Developers,

After a long time ( was in a busy schedule of establishing family after my marriage :) ) I thought I will post this article for setting the XML mapping  of content control  in a Word document template  for SharePoint Document Library. To be frank, in most of the cases we are / will be  using QuickParts Add-in to add the content controls  which are already mapped with SharePoint ContentType fields. But in this article I will be explaining how to set up a document template for a document library without touching the QuickParts Add- in. Sometimes this will be helpful to the developers who are programmatic-ally/dynamically  creating  document templates or content controls to document templates.  To make this article in one line, its about setting XPath, Prefix Mapping for content controls using SetMapping function of XMLMapping property of content control, like contentControl.XMLMapping.SetMapping(Xpath,PrefixMapping).

These are things that  you should have handy with you before starting this exercise.

  1. A  Document Content Type with some site columns referred inside – Say, we will name it as “ExpenseContentType” that have  2 site columns (SC_ExpenseName, SC_ExpenseCount )
  2. A Document Library created which have content type that is mentioned on the above step( Step 1) – Say , ExpenseDocumentLibrary.
  3. Word Content Control Tool Kit – Download this tool kit.  This is just for the analysis purpose of the template or to understand what is happening behind the scene.
  4. Visual Studio – Just in case if  you need to code the logic for XML mapping. (Code is embedded on the bottom of the post)

So, Lets start from the document library (ExpenseDocumentLibrary)

Step 1 . Go the document library setting –> ContentType (ExpenseContentType) –> Advanced Settings

Here on the Advanced setting page of the Document library Content Type, Click on the Edit Template link(see image below) . This will open a blank document template on the MS Word . Save this locally on your machine with any user friendly name , Say ExpenseTemplate.docx

Edit Template from the Document ContentType of the document library

Step 2. For analysis, open the locally saved blank template using the Word Content Control toolkit. We can see the content type fields on the custom XML parts of the document. This means the ContentType related data like Fields etc are there in this document in XML(XSD) format.  Since its a blank document , there is no matter in the Content Controls section.

Blank document

Step 3. Let us add some content controls to this document template. For that, Open the word document using MS Word and from Developer tab add 1 or 2 plain text content controls to the document as if  it resemble a template. (See image below). Name the content controls exactly as the Site Columns name in ContentType. Means, name Expense Name content control as “SC_ExpenseName”.

Save this document after the adding the controls.

Step 4 . Re-Open the document in the Word Content Control Tool Kit. Now we can observe that on the content controls section it showing the control entries without having its XPath set with ContentType Fields inside the file. (See the Image below). Basically XPath and Prefix mapping of the Custom XML parts shown on the right pane for the each field need to be mapped with content control.

Step 5. In this step we will set the mapping between the content controls and ContentType fields. Actually we can set mapping using Word Content Control Tool kit itself , but it will become a manual process. Better we will do it “programmatic-ally”  :) .

For doing this, I am creating  a Word Add-In project  in Visual Studio . So open a Visual Studio Instance –> New Project –> Word Add – In (see image below).

Give any user friendly name to the project.  After that , Add a “Ribbon” into this  Add- in project (Right Click on Project –> Add –>  New Item –> Ribbon (see image below))

Again, give a user friendly name to the ribbon. On the visual designer of the ribbon add a button(label it as “Set Mapping”) and on the click event of  button , we will write some code as shown below .

      ///
<summary> /// Click event of the Set Mapping button
 /// </summary>
        ///
        ///
        private void button1_Click(object sender, RibbonControlEventArgs e)
        {
            //Accessing the active document
            Document document = Globals.ThisAddIn.Application.ActiveDocument;
            string nsURI = string.Empty;

            //retreving the content control collection of the active document.
            ContentControls contentControls = document.ContentControls;

            //Looping through the content Control collection.
            foreach (ContentControl cntntCtrl in contentControls)
            {

                var ctrlTitle = cntntCtrl.Title;
                //Setting the XPath for each control. this is under a condition that name of the Content type site column /field
                // and content control name & tag is exactly same.
                string xpath = "/ns0:properties[1]/documentManagement[1]/ns1:" + ctrlTitle + "[1]";

                //Private function to get the NameSpace URI of the content type field
                nsURI = GetXSDNameSpaceURI(document, cntntCtrl);

                //Mapping the content control.
                bool isMapped = cntntCtrl.XMLMapping.SetMapping("/ns0:properties[1]/documentManagement[1]/ns1:" + ctrlTitle + "[1]", "xmlns:ns0='http://schemas.microsoft.com/office/2006/metadata/properties' xmlns:ns1='" + nsURI + "'", null);

                if (isMapped == true)
                { MessageBox.Show("Mapping successfully done...!"); }
                else
                { MessageBox.Show("Error in XML Mapping"); }

            }

        }

        ///
<summary> /// private function to get the namespace URI of the content type.
 /// </summary>
        ///
        ///
        ///
        private string GetXSDNameSpaceURI(Document document, ContentControl control)
        {
            string nsURI = string.Empty;
            CustomXMLParts xmlParts = document.CustomXMLParts.SelectByNamespace("http://schemas.microsoft.com/office/2006/metadata/properties");
            foreach (CustomXMLPart xmlPart in xmlParts)
            {
                XmlDocument XDoc = new XmlDocument();
                XDoc.LoadXml(xmlPart.XML);
                XmlNodeList result = XDoc.GetElementsByTagName(control.Title);
                nsURI = result[0].NamespaceURI;
                break;
            }

            return nsURI;
        }

Build the project and press F5. This will open a default word document. Close that document and open our document library template where we have add content control. Find the ribbon that we have created on the opened document and press the button “Set mapping”. This will set the XPath mapping for each content control and throw a message box saying “Mapping successfully done…!”.(see image below)

Now I will explain what actually the above code does. Basically it iterates through the content controls collection and by using each content control’s title its creating an “XPath” string and “Prefix mapping” using the content type namespace URI . The key player is SetMapping Function of the content control’s XMLMapping property. This function is used to set the mapping for the content control. The SetMapping function can be called on the event after the control adding to make it more clean. But since this is a POC we will use iteration logic. The entire article is based on the SetMapping function to make link between content control and content type.

Now just open the document in the Word Content Control toolkit and see the XPath set against each content control. (see image below)

This is the time to upload this document template back into Sharepoint. Go to the Advanced settings of the Document library content type and upload the template using “upload a new document template”. After the uploading is over try adding document files which have data inserted. You can see content control data getting binded with content type columns within the document library.

I hope you enjoyed/ understood this article. Thanks for readings. Comments are invited.

Posted in CodeProject, Sharepoint, Technical Posts | Tagged: , , , , , | 6 Comments »

When or How to Use Run With Elevated Privileges (RWEP) in SharePoint

Posted by Abin Jaik Antony on August 7, 2011

The scope of this article is to explain the usage of RunWithElevatedPrivileges() [RWEP] – a method for security elevation for custom SharePoint components.

“The RWEP method enables you to supply a delegate that runs a subset of code in the context of an account with higher privileges than the current user”, this is the definition from Microsoft MSDN. Basically the code executed inside this method has “System Account” privileges in addition to the current user privileges or in a better way – we can tell that this method runs under the Application Pool identity, which has site collection administrator privileges on all site collections hosted by that application pool.

For a detailed explanation please go through my article published on www.mssharepoints.com or Click here

Posted in CodeProject, Sharepoint, Technical Posts | Tagged: , , , | Leave a Comment »

Multiple listing controls with a single datasource – InfoPath

Posted by Abin Jaik Antony on June 8, 2011

The scope of this article is to explain how to populate multiple InfoPath listing controls like a Drop-Down List and a List Box with only one datasource. The scenario can be like this:

Assume we have 2 to 3 SharePoint lists with data on our SharePoint site and we have some listing controls on our InfoPath form. The aim is to populate all these listing controls using only a single InfoPath datasource.

Solution

By default we do have four “Receive Data” options for InfoPath datasource like an XML document, DataBase,Web Service, and SharePoint Lists & Libraries. As mentioned in the “Problem”, our aim is to populate data from different SharePoint lists to different listing controls on an InfoPath form. Usually, everyone will create different datasources from SharePoint lists for each listing control, but we can utilize the “Web service” option for populating many listing controls with a single datasource. Click here for the entire article that i have published on www.mssharepointtips.com

Posted in CodeProject, Sharepoint, Technical Posts | 1 Comment »

Html Editor Control for SharePoint Web parts

Posted by Abin Jaik Antony on October 10, 2010

Hello SharePoint Developers,

This time i have a simple stuff on SharePoint , it is regarding the rich text editor control on SharePoint.  During our custom webpart developement if we want a HTML Editor/rich text editor on our webpart, we can utilize InputFormTextBox Class of the SharePoint Object Model.

Please read my article regarding InputFormTextBox on the MSSHAREPOINTTIPS.COM

Posted in CodeProject, Sharepoint, Technical Posts | Tagged: , | Leave a Comment »

HTML5 <video> tag and my concept of Video mailing.

Posted by Abin Jaik Antony on July 30, 2010

For the last couple of weeks I am surfing a lot for HTML5 features and whatever new features it have is really amazing. You can also find many articles on web related to the HTML5. I found this article as the best describer , html5demos. When you check new elements that added on this new HTML version , you can find the tag “video” .

The purpose of this media element/tag is to play videos or movies. Currently we use third party plug ins of Quick Time, Flash , Real Player etc to view videos on our web page.
But now with HTML5 we can directly embed videos on the web page using . This element do have “src” attribute just as in <img> tag where we can give url of the video. Currently only web browsers such as Fire Fox 3.5+ , Chrome, Safari 3+ , Opera supports the video tag. For IE users its not currently available, but soon it will get supported from IE9 .

Here, the idea that I want to express is something related to Video Mailing. This means that every email provider can give video messaging service too , when HTML5 become popular. My idea can be more elaborated like this , there will be a “Create a video mail” link on our email account page . When clicking on this link, cam and mic on the client machine will get activated[same as in the FaceBook's “Create Video” option.] .The video will be saved on the server and intimation will be send to the receiver’s inbox after clicking on the send button. When receiver clicks on the video message, it will start rendering as the video on the page. The purpose is to convey the messages with emotions , gestures, actions etc. I feel there are some advantages and disadvantages for this approach.

  Advantages

  • Conveying messages with expressions, emotions etc
  • Authentication of the sender can be 100% assured, since it is a video email.
  • No need to go for big big email drafting to convey a small message.
  • Clarity of message will be more in Video Mail.

  Disadvantages

  • More server space will be utilized than the regular text messages
  • Instant messaging need hardwares like camera ,mic on the sender’s machine.
  • More bandwidth is required for receiving video mail than the text emails 

Kindly comment on my idea of Video mailing and lets have discussion on the same . Thanks

Posted in HTML /HTML5, Technical Posts | Tagged: , , , | Leave a Comment »

Lets move to C# 4.0

Posted by Abin Jaik Antony on June 29, 2010

Some features like Dynamic programming,Optional arguments,Named arguments

Dynamic Programming :

This is the major feature of C# 4.0. In the first look it looks something like our previous “var” type of C#3.0 or regular object type that we have with C#,root Type of .NET . But its not like that. Actually when you assigns a variable of Type “dynamic” and use its properties/methods ,compiler doesn’t mind it at compile time. Means, no method/property resolution takes part in compile time and it will take care all of those things at run time. By these words dont think “dynamic” is dynamic type ,its a static type only.

The below mentioned code is a small example for the dynamic programming.

using System;
using System.Text;

namespace DynamicType
{
	class Program
	{
		static void Main(string[] args)
		{

			Mathematics objmathematics = new Mathematics();
			dynamic objdynamic = objmathematics;

			
			double resAdd= objdynamic.add(3,2);
			Console.WriteLine(resAdd.ToString());

			//The method "subtract" is not present in the Class Mathematics.
			double resSub = objdynamic.subtract(3, 2);
			Console.WriteLine(resSub.ToString());

			Console.ReadLine();
		}
	}

	class Mathematics
	{ 
	
		public Mathematics()	{}


		public double add(double a, double b)
		{
			return a + b;		
		}
	}
}

On compiling the above code, the build will succeed with a smile. But at run time it will break at code line number 18. Because the function “subtract” that is trying to resolve is not present in the Mathematics Class and method “add” will pass through because it is available.

The DLR, Dynamic Language Runtime is responsible for this dynamic programming capability . Basically its built on the top of the CLR to make the dynamic languages such as IronPython, IronRuby etc to get supported. To know more about DLR please go to this link

The main use of this dynamic programming is to support the compilation during interfacing of our managed code with COM , Javascript DOM or any dynamic languages.


Optional and Named arguments:

Now we can have optional values for the C# methods . We can set default values for the arguments and can pass the values during the method call according to our need.Also we can call each parameter by its name , not by its position as earlier. This is called Named argument

It will be like this :

public double GetPNRValue(double a=1,double b=0,double c=1)
		{
			return (a * b / c);
		}

And when we call this method, we can pass arguments like this

double resPNR = objdynamic.GetPNRValue(2,c:0);			

It says that “a” is 2, “b” can be the optional argument and “c” be zero . Here “c” is the Named argument.

Posted in C# 4.0, Technical Posts | Tagged: , , , , , | 2 Comments »

Cascading dropdowns in InfoPath from SharePoint.

Posted by Abin Jaik Antony on May 26, 2010

It is very common for every developer to have a situation to  develop cascading dropdowns during their development life. It can be Category –Product scenario, Country-State scenario etc.  Here the case is something different; cascading is not on regular ASP.NET Page or not a simple web part. But it’s on a InfoPath form…..!  You will ask, what makes the difference?  I say, if the InfoPath is browser enabled, the filter option of the InfoPath won’t work or it won’t support.  Any how we developers have to accomplish this cascading task. Below, i have a scenario and its solution step by step.

Scenario:  I have two SharePoint lists “Categories “and “Products”. “Categories” SharePoint list have a column named “Category” and “Product” SharePoint list have 2 columns – Product and Category, out of which Category is a look up column from “Categories” SharePoint List. Now we have to develop a InfoPath form with 2 dropdowns, Categories and Products and we need to make it work in a cascading style. Means when the user selects a particular category on the Categories dropdown, related set of products should be populated on the Products dropdown. This is the scenario.

Solution: Follow the simple steps to accomplish this task.

  1. Open Microsoft InfoPath 2007 from Start à All Programs à Microsoft Office.
  2. Create a blank InfoPath form template using the option “Design a Form Template”. Don’t forget to check the option “Enable Browser Compatible Features” while creating the blank template.
  3. Now we have a blank InfoPath form in front of us. Drag and Drop two dropdowns from the toolbox and name them as Categories and Products.
  4. After step 3 , we need to populate the dropdowns with data. For that we need to create data connections with in the InfoPath form. “Categories” dropdown can be populated directly from the “Categories” SharePoint list. But Products dropdown can’t be populated from products SharePoint list, because its need to populated according to the selected category. In the next 2 steps we will create data connections for the dropdowns.
  5. In this step we will create data connection for the Categories dropdown. Select “Dataconnections… ” option from the “Tools” menu [menu available on the top portion] of the InfoPath form. From the “Dataconnections” window click add and on the DataConnection wizard select “Create new dataconnection” option with “Receive Data” Selection. On the “select the source of your data” step ,  go with the option “Sharepoint Library or List”. The coming steps of the wizard are self informative and proceed with selection of our Categories SharePoint List. Once we finish with the DataConnection wizard steps, Bind the created Categories dataconnection  with “Categories” Dropdown by right clicking on the control and from “Dropdown  list properties”  , select “Look up values from the external datasources” option. Now there will be a selection  with available dataconnections. Select our categories dataconnection and select category field  for  “Entries” option. Check on the InfoPath preview, whether data is populated correctly or not. So population of the  Categories dropdown is over.
  1. In this step we will create dataconnection for the Products dropdown. Here  we have to do some more work to create Products dataconnection. This is the portion we have to look on. Before going to create dataconnection for Products, we have to create a webservice that have function which return set  of  products according to the category passed. So, Create a WSPBuilder project and  add a Webservice item to the project  from WSPBuilder project templates or you can go with other webservice creation techniques and deploy it to the sharepoint site. Usually I create SharePoint components with the WSPBuilder . If it is with WSPBuilder, packaging and deployment is quite easy.

Give a user-friendly name to the webservice and in the code behind of the Webservice file add the following piece of code.

[WebMethod]
        public DataSet GetProducts(string Category)
        {

            DataSet dsProducts = new DataSet();
            DataTable dtProducts = new DataTable();
            DataColumn dcCategory = new DataColumn("Category");
            DataColumn dcProduct = new DataColumn("Product");
            dtProducts.Columns.Add(dcCategory);
            dtProducts.Columns.Add(dcProduct);

            SPSite site = SPContext.Current.Site;
            SPList list = site.OpenWeb().Lists["Products"];
            SPQuery query = new SPQuery();
            query.Query = @"<Where>
      <Eq>
         <FieldRef Name='Category' />
         <Value Type='Lookup'>"+ Category  +@"</Value>
      </Eq>
   </Where>";
            SPListItemCollection itemCol = list.GetItems(query);

            DataRow drCategory;
            foreach (SPListItem item in itemCol)
            {
                drCategory = dtProducts.NewRow();
                drCategory[dcCategory] = Convert.ToString(item["Category"]);
                drCategory[dcProduct] = Convert.ToString(item["Product"]);
                dtProducts.Rows.Add(drCategory);
            }

            dsProducts.Tables.Add(dtProducts);
            return dsProducts;
  }

This webservice method will return set of products for the given category. Build this project, build the WSP and deploy to the sharepoint site. After the deployment of the WSP , we can find the webservice in the _layouts virtual directory of the sharepoint site on the IIS. It will look like this http://localhost:5050/_layouts/CascadingDDLService.asmx .   Browse that .asmx  file and check whether  the “GetProducts” webservice method  is working on invoking. If it is working, we can proceed with it during the creation of “Products” dataconnection.

Now we can start creating dataconnection for Products. Follow the procedures mentioned on the step 5,till you reach “select the source of your data” step on the dataconnection wizard. On this step you have to select “Web service” option rather than “Sharepoint Library or List” option that we have taken on the step 5. After selecting  “Web Service” option , on this next step it will ask us to provide the webservice URL. Provide our webservice url that we have deployed before, it will give set of web- methods in the web service, in our case it will be only method ,“GetProducts”. Click next , it will ask for the  default parameter values and go on with the steps with clicking Next. But on the last step we have to consider one important thing , uncheck the option “Automatically retreive data when form is opened.” and click Finish to end dataconnection wizard.Now the Products dataconnection is created and we can bind this dataconnection to the Product dropdown list. Follow the same procedures mentioned on the step 5 to bind the dataconnection on the dropdown.

  1. Next step is to create the “Rules” for the Categories Dropdown. This step is very important for the cascading to work.
    • Right click on the Categories dropdown, select “Rules” option. From the rules window, click “Add” button to add a rule for the categories dropdown.
    • On the click of the “Add” button, you will see a window like this

Name the rule with a user-friendly name. Click on the “Set Condition” button and set a condition as per the below mentioned image.


We need to set the condition that Rule need to shoot when Categories is not blank.

    • After setting the Condition we can set the “Actions” for that rule.Here we need to set 3 actions. Click on the “Add Action” button to set an action.
    • In first action we will set the Products Field previously set value to Null. Select “Set a field’s value” from the action’s dropdown.For that select Products Field from main datasource and click OK without setting the value.

    • On the second action we need to set the Category parameter for the “GetProducts”  dataconnection, which is a secondary datasource. Select “Set a field’s value” from the action’s dropdown. In the Field section select Category parameter

and set its value to the Main datasource Category Field.

    • In the third action we will populate the “GetProducts” datasource . For that Select “Query using a dataconnection” from action’s dropdown and select “GetProducts” dataconnection from Data connection’s dropdown.

Finally the Rule window will be like this

Now save InfoPath Form and publish to any SharePoint site. Browse the InfoPath form from any of your browser, cascading of dropdown will work with charm…. :)

Posted in CodeProject, Sharepoint | Tagged: , , , , , , | 1 Comment »

 
Follow

Get every new post delivered to your Inbox.

Join 83 other followers