Tuesday, April 2, 2013

How to generate a PDF report from a asp.net Data Table or SharePoint List using Itext C# dll.

I am going to show you that how to generate a PDF from a given data table using Itextsharp.dll and  Itext sharp.pdfa.dll. We can download both of  them from this link. I will create a Webpart which will contain a button on which click we will be able to generate a PDF report for list data on file system.

Here are the steps :

1.) Very first we need to add these two dlls in our GAC.
   
   i)   Itextsharp.dll 
  ii)   Itextsharp.pdfa.dll 

2.)  Now we need to add a webpart. In webpart we need to add only this code :

 protected override void CreateChildControls()
        {
            Button btnExport = new Button();
            btnExport.Text = "Export";
            btnExport.Click += new System.EventHandler(this.btnExport_Click);
            Label objLabel = new Label();
            this.Controls.Add(btnExport);
            this.Controls.Add(objLabel);

        }



        protected void btnExport_Click(object sender, EventArgs e)
        {
           
                    SPWeb objSPWeb = SPContext.Current.Web;
                    SPList objSPList = objSPWeb.Lists["ListName"];
                    DataTable objDT = objSPList.Items.GetDataTable();

                    //Here you can use a Caml Query to do all types of filtering of data and columns.
                    ExportDataToPDFTable(objDT,
"Poc1" , objSPWeb);
                   
        }

        private void ExportDataToPDFTable(DataTable dt, string PDFName, SPWeb objSPWeb)
        {
            Document doc = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35);
            try
            {

                string pdfFilePath = @"D:\POCs\" +
PDFName + ".pdf";

                //Create Document class object and set its size to letter and give space left, right, Top, Bottom Margin
                PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream(pdfFilePath, FileMode.Create));

                doc.Open();//Open Document to write

                Font font8 = FontFactory.GetFont("ARIAL", 7);
                Font font9 = FontFactory.GetFont("ARIAL", 8);

                //Write some content
                Paragraph paragraph = new Paragraph("Using ITextsharp I am going to show how to create simple table in PDF document ");

                //DataTable dt = GetDataTable();

                //DataTable dt = dtStructure.Clone();
                //dt.Rows.Add(objDataRow);

              

                if (dt != null)
                {
                    PdfPTable PdfTable = new PdfPTable(dt.Columns.Count);
                    PdfPCell PdfPCell = null;
                    foreach (DataColumn item in dt.Columns)
                    {
                       
                        PdfPCell = new PdfPCell(new Phrase(new Chunk(item.ColumnName, font9)));
                        PdfTable.AddCell(PdfPCell);
                    }
                   
                    //How add the data from datatable to pdf table
                    for (int rows = 0; rows < dt.Rows.Count; rows++)
                    {
                        for (int column = 0; column < dt.Columns.Count; column++)
                        {
                            PdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Rows[rows][column].ToString(), font8)));
                            PdfTable.AddCell(PdfPCell);
                        }
                    }

                    PdfTable.SpacingBefore = 15f; // Give some space after the text or it may overlap the table

                    doc.Add(paragraph);// add paragraph to the document
                    doc.Add(PdfTable); // add pdf table to the document

                }

            }
            catch (DocumentException docEx)
            {
                //handle pdf document exception if any
            }
            catch (IOException ioEx)
            {
                // handle IO exception
            }
            catch (Exception ex)
            {
                // ahndle other exception if occurs
            }
            finally
            {
                //Close document and writer
                doc.Close();

            }
        }

Through this you will be able to generate PDF with least coding from a DataTable in C#.

Monday, March 18, 2013

Easy way to validate User againsts Active Directory in C#.

If you want to validate a user against an active directory. This is the easiest way provided by .Net framework. By using this we do not need to explicitly create a LDAP web service reference. For validating user we need to include this System.DirectoryServices.AccountManagement.dlll reference in our solution. After adding this dll our code will be very simple,  here it is :

Include this two Namespace (You can resolve it as well) :

using System.DirectoryServices;
using System.DirectoryServices.AccountManagement; 




Here I am taking value to validate a from a text box.

string Domain = string.Empty;
string UserName = string.Empty;
string strUserName = txtAdminName.Text;
 

if (!string.IsNullOrEmpty(strUserName))
 {
 string[] DomainAndUserName = strUserName.Split('\\');

                 if (DomainAndUserName != null && DomainAndUserName.Length > 0)
                       {
                            Domain = DomainAndUserName[0];
                            UserName = DomainAndUserName[1];
                        }
                    }
                    using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, Domain))
                    {
                        UserPrincipal up = UserPrincipal.FindByIdentity(pc, strUserName);
                        bool UserExists = (up != null);
                        if (UserExists)

                        {
                        // Do whatever action you want to perform, when user exists.
                        }
                        else
                       {
                        // Do whatever action you want to perform, when user does not exist.              
                        }
                     }
   }

You can place this code in a  function and then use. Hope it helps...!!

Tuesday, March 5, 2013

How to Query SharePoint List Items Using REST and ECMA script which returns as JSON.

Here is the way you can query data from a SharePoint List by using REST and then return all these items in JSON format. You need to call these two methods with all required values. Here I am going to query a list in which "Title" column contains value 'CR' :

 This method you can call in inn your any event, where you want to access data of a SP list through REST in JSON format :

function getListItems() {

var Url = "http://<servername>:<portno>/sites/<sitename>/_vti_bin/listdata.svc/<ListName>?$filter=substringof('CR',Title)";

//Create a WebRequest object
var request = new Sys.Net.WebRequest();

//Specify the verb
request.set_httpVerb("GET");

//Use the URL we already formulated
request.set_url(Url);

//Set the Accept header to ensure we get a JSON response
request.get_headers()["Accept"] = "application/json";

//Add a callback function that will execute when the request is completed
request.add_completed(onCompletedCallback);

//Run the web requests
request.invoke();
}


This function runs when the web request completes so make sure you will get response.

function onCompletedCallback(response, eventArgs) {
//Parse the JSON reponse into a set of objects by using the JavaScript eval() function

var Items= eval("(" + response.get_responseData() + ")");
alert(
Items);
//Fomulate HTML to display results
var Column1 = "
Column1 : ";
var Title = "Title : ";
alert(
Items.d.results.length);Column1 += 'Title: ' + Items.d.results[0]['Content'];
Title += 'Title: ' +
Items.d.results[0]['Title'];

//var IDs= "IDList : ";
//var Titles = "TitleList : ";

 //for (var i = 0; i < Items.d.results.length; i++) {
//Display some properties
//Titles += 'Title: ' + Items.d.results[i]Title + ";
//IDs += 'ID: ' + Items.d.results[i].Id + ";
//}


//Display the raw JSON response
var
Raw JSON response = 'Raw JSON response:' + response.get_responseData();
alert(
Column1 );
alert(Title);
}


So by using this code you can get response from a list without creating so many objects(e.g. : Web, site, list, Caml Query and many more). These three alert will show Raw JSON response, Column(which can be any) and Title. Which you can customize further for use.

* Highlight 1: Its a contain filter, you can apply any as per your need. There is a very rich set of keywords there to filter.


* Highlight2: You can un comment this code and it will give you collection of items.



 

How to pass a value across Approval Levels and Check First Approver is not same as Second Approver in OOB SharePoint Designer Approval Workflow.

Here in one of my requirement I need to pass a value which is entered in level one of approval task from to second level of approval task form. After a  lot of search I was not able to find anything. This is the way I have done it. I will also demonstrate a way to check first app rover is not same as second. These are the steps that be useful for someone looking for same :

Step 1: We need to take two workflow variable on the completion condition of level 1 approval as shown in the below screen shot :


 Through these condition we can get our required values in workflow variables.(Here ID14743  is any field you want to save in this variable  and Modified By contains name of the first app rover. )


Step 2: Now save these two values in two respective fields, in the Before a task is Assigned Status of level 2 approval (This is the key here if you will update these task fields, it will lead to execution of Workflow. So just set it as shown in below Screen Shot). It is compulsory to create two  Task fields to store these values.



No as we have these values in our Task List fields so we can use them in our Info path form(Which is our Task Form as well). Because Info path form are by default associated with Task List fields.

In the info path form in what ever field we want to show this value we need to bind that field with our  Assigned fields. So they will display data entered at first level of approval. I

Step 3: As we got these values in our Info Path form so we need to edit our second level Task Form using info path form client and use some basic info path modification techniques to get it done.
a) In the Approve button of info path we need to set a rule that current user can not be same as what value is in the FirstApprover field (which we have set in this field before a task is assigned so the first app-rover value is with us already).

 We need to set very same rule in Reassign task or any action in which we want to check that First Approver should not perform this action. Using the value of First Approver Field and with new value entered or current user. There is a very important point here to note that always save and return values in same format as Name or User ID or something.

Hope it help someone. Will attach compare Screen Shot for First/Second Approver later.

Friday, March 1, 2013

How to handle SharePoint Poup Close event and return values in Parent Page(Very Basic ).

Code to insert a Popup in any SharePoint Product, In the first page we need to add this code :

function openPopup()
{
var options = SP.UI.$create_DialogOptions();

options.width = 900;
options.height = 600;
options.resizable = 1;
options.scroll = 1;
options.url = 'pageURL';
options.dialogReturnValueCallback = Function.createDelegate(null, CloseCallback);
if(SP.UI.ModalDialog.showModalDialog(options)) {
var y = $(window).scrollTop();
        var boxBorder = $(window).height() - $(".ms-dlgContent").height();
        y = y + boxBorder / 2;
        $(".ms-dlgContent").css({ position: 'absolute', top: y });
}
}

function CloseCallback(result, target)
{
 if(result == SP.UI.DialogResult.OK) {
       alert('
Value got from POPUP on OK : ' +target);
           }
    if(result == SP.UI.DialogResult.cancel) {    

       alert('Value got from POPUP on Cancel : ' +target);
        } 

}


On the PopUp Page we need to put these two code on the events we want to Close our popup as per our need of Cancel & OK handling (Such as a button click or any event) :

 SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.OK, 'Value return to the Parent Page on OK');

 SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.Cancel, 'Value return to the Parent Page on Cancel');

Very basic and simple:)




How to set the last created item ID in SharePoint through client side coding and then get it populatd in Parent Page on PopUp Close using OOB save.

I have a new list form in which I need to submit items on 3 SharePoint Lists (No. does not matter much actually) and then populate these newly created Items ID (for current user only, as there may be so many users are accessing it on same time) on this new form. So I have done it in this way only for 1 list:

a.) Edit current list new form in Designer and then add a link on current page to open list new form. Below piece of code will open another list new form in Popup Window : :

<a href="javascript:CreateNew();" id="hypCreateNew" ><b>Create NewItem in list 2 and Populate ID</b></a>

function CreateNew()
{
var options = SP.UI.$create_DialogOptions();options.width = 900;
options.height = 600;
options.resizable = 1;
options.scroll = 1;
options.url = '/site1/Lists/List1/CustomNewForm.aspx';
options.dialogReturnValueCallback = Function.createDelegate(null, CloseCallback);
if(SP.UI.ModalDialog.showModalDialog(options)) {
var y = $(window).scrollTop();
        var boxBorder = $(window).height() - $(".ms-dlgContent").height();
        y = y + boxBorder / 2;
        $(".ms-dlgContent").css({ position: 'absolute', top: y });
}

}

Highlighted code set New Open Popup in the center of the page.

b.) Now in List2 CustomNewForm.aspx we need to comment default button and then add this code :

<input type="button" id="PopUPSave" value="Save" name="btnPopUPSave" onclick="javascript: {ddwrt:GenFireServerEvent('__commit;__redirect={/site1/SitePages/Redirect.aspx}')}" style="width: 200px" />

c.)  We need to add a new Page in Site Pages with Redirect.aspx (this can be any page I used a site page). On click of save we will redirect our page to this page and here we will place a single line of code :

<script type="text/javascript" src="/_layouts/jshelperlibs/jquery/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
if(window.frameElement!=null)
{
window.frameElement.commonModalDialogClose(1, 1);
}
});

Highlighted code will close opened Popup with OK result, will explain later.

This Redirect.aspx will give us this functionality to use OOB save functionality of list with our handling of Popup Close.

d.) Now In our List1 parent page we need to add these code :

function CloseCallback(result, target)
{
       if(result == SP.UI.DialogResult.OK) {
          
retrieveListItemsList1();
           }
    if(result == SP.UI.DialogResult.cancel) {   
        } 
}

As we supplied (1,1) in Redirect.aspx window.frameElement.commonModalDialogClose(1, 1); on popup Svae Click it will always call this method retrieveListItemsMPMIssue(); which is within if(result == SP.UI.DialogResult.OK).

e.) We will write body of this method to get item from list2 , using below code :




function retrieveListItemsList1() {
var currentUser = $().SPServices.SPGetCurrentUser({
  fieldName: "ID",
  fieldNames: {},     // Added in v0.7.2 to allow multiple columns
  debug: false
  });

    var clientContext = new SP.ClientContext.get_current();
    var oList = clientContext.get_web().get_lists().getByTitle('List2');
    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml('<View><Query><Where><And><IsNotNull><FieldRef Name=\'ID\' /></IsNotNull><Eq><FieldRef Name=\'Editor\' LookupId=\'True\'  /><Value Type=\'Lookup\'>'+currentUser+'</Value></Eq></And></Where><OrderBy><FieldRef Name=\'ID\' Ascending=\'False\' /></OrderBy></Query><RowLimit>1</RowLimit></View>');
        this.collListItem = oList.getItems(camlQuery);
       
    clientContext.load(collListItem);
       
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));       
       
}


var listItemID= '';

function onQuerySucceeded(sender, args) {

    var listItemEnumerator = collListItem.getEnumerator();
       
    while (listItemEnumerator.moveNext()) {
        var oListItem = listItemEnumerator.get_current();
       
listItemID = oListItem.get_id();    }
        $("input[title='List2 ID']").val(
listItemID);
        $("input[title='
List2 ID']").attr("disabled", "true");
}

function onQueryFailed(sender, args) {

    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}


Highlighted Block 1 : This code will give you the current user name as ID which we will use in our caml Query to get ID. It used SPServices, you can do it through COM but that will be a lot of coding.

Highlighted Block 2 : In this query we will get all item created by this user in descending order of modified (which will be same as created at the time of creation) and then get Very first ID by Row Limit. So we will get latest ID.



So above code will populate ID in needed place, here its a control with Title List2 ID.