: +91-265-2775555
 : +1-714-786-6270
 : +45-4052-3137

 ‭(Hidden)‬ Admin Links

There are currently no favorite links to display.

 Blog image

 Tag Cloud

 Archives

There are currently no favorite links to display.

Telerik MVC Upload Control

Download Telerik library from

http://www.telerik.com/products/aspnet-mvc.aspx

To see demo of uplod control, visit

http://demos.telerik.com/aspnet-mvc/upload

Reason to write this Blog:

Many times we require to get some status message after saving files e.g. FileId from database.

In this case when we pass non empty string from action, telerik considers it as error. Here in this blog i had mentioned steps to overcome this error.

Telerik Upload control provides multiple files upload simultaneously sync/async.

 @(Html.Telerik().Upload()

        .Multiple(true)

        .Name("UploadFile")

        .ClientEvents(t => t.OnError("UploadFile.error").OnUpload("UploadFile.Upload"))

        .Async(t => t.AutoUpload(false)

  .Remove("Remove", "UploadFiles")

         .Save("Save", "UploadFiles")))

 

When we pass message from save(), it throws alert box with message "Error! Upload failed. Unexpected server response - see console." To override it:

1:  Get Object

Get the object of uploading control and override its existing method which generates error message.

var r = $("#UploadFile").data("tUpload");

r._alert = function (ee) { };

$("#UploadFile").data("tUpload", r);

 

_alert() is the function which generates error message when response from save() is non empty.

2:   Get response text from Save()

As we return status, it will fire UploadFile.error().

UploadFile.error = function (e) {

    UploadFile.filename = e.files[e.files.length - 1].name;

    UploadFile.statusMsg = e.XMLHttpRequest.responseText;

    if (e.XMLHttpRequest.responseText.indexOf("Success") < 0) {

        UploadFile.Status = "error";

    }

    else {

        UploadFile.Status = "success";

    }

};

 

XMLHttpRequest.responseText is the value of status sent from Save() by which you can distinguish with actual uploading error or the successful status message.

 

3: Change Classes to get correct output

Here, file is uploaded success fully. Though it shows with red mark as error.

 

Error File

We need to work on Jquery to get correct output:

Success File

$(".t-file .t-fail").removeClass("t-fail").addClass("t-success");

$(".t-file .t-success").html("uploaded");

$(".t-file .t-success").parent().find('.t-retry').removeClass("t-retry").addClass("t-delete");

$(".t-file .t-success").parent().find(".t-delete").parent().html("<span class='t-icon t-delete'></span>delete”);

 

4: Override function _removeFileEntry()  to get more functionality

When you click on delete button it will just remove the file list from div, and call Remove() of controller. But if you want to handle some features from Jquery, like remove FileId from list of FileId stored in hidden field, override _removeFileEntry() of telerik uploader as:

 

var r = $("#UploadFile").data("tUpload");

r._removeFileEntry = function (v) {};

$("#UploadFile").data("tUpload", r);

 

Thanks,

Posted By: Priyanka Shah

SharePoint site first load is very slow.

The sharepoint site is very slow when we access it first time. After that the response time is good. The reason is compilation and caching which takes time after application pool is recycle. To handle this we need to warm up the server whenever recycle happens. Here is a good link that explains about server warm up: http://blogs.msdn.com/b/joelo/archive/2006/08/13/697044.aspx So the idea is to schedule a job that pings the server whenever reset occurs.

You need to be a site collection administrator to set this property.

Sometimes you may receive error "You need to be a site collection administrator to set this property." even if you are a site collection administrator.
 
Resolution:
 
The site collection was locked. You need to unlock it via central admin. Go to central admin and unlock it (_admin/sitequota.aspx) by selecting the option "Not Locked".

E-signature using  Docusign

Docusign provides e-signature to documents. We can send document to as many recipients and get their signs using Docusign. This functionality can be accessible through its Member console. If you want to integrate Docusign with your application, you can use its API.

 

Here in the blog I had used its demo service. You can get API from:

https://demo.docusign.net/api/3.0/api.asmx

 

When we send a document to Docusign for sign, it creates an envelope. This Envelope contains document, recipients who will review or sign the document, Tabs with where to put signature, or Custom tab.

 

Now let’s start the process of sending documents and sign them through API.

Add the above link to service reference of the project. (Here, service reference name is “DocuSignWeb”)

How to send document:

CreateAndSendEnvelope  function of API Service is used to send the document to Docusign. To use this function follow steps.

Step 1:  Create Recipients

Docusing creates two types of Users: Embedded and Remote

Embedded user requires authentication while retrieving document, where remote user is not allowed to get the document. Whole process is handled through email in remote user.

 

DocuSignWeb.Recipient r = new DocuSignWeb.Recipient();

r.Email = email;

r.UserName = firstName + " " + lastName;

r.Type = DocuSignWeb.RecipientTypeCode.Signer;

r.RequireIDLookup = false;

r.ID=1.ToString(System.Globalization.CultureInfo.InvariantCulture);

 

If you are creating embedded user then it will require CaptiveInfo:

 

r.CaptiveInfo = new DocuSignWeb.RecipientCaptiveInfo();

r.CaptiveInfo.ClientUserId = clientUserId;

r.SignatureInfo = new DocuSignWeb.RecipientSignatureInfo();

r.SignatureInfo.SignatureInitials = (firstName.Length > 0 ? firstName.Substring(0, 1) : "") + (lastName.Length > 0 ? lastName.Substring(0, 1) : "");

r.SignatureInfo.FontStyle = DocuSignWeb.FontStyleCode.BradleyHandITC;

r.SignatureInfo.SignatureName = firstName + " " + lastName;

 

CaptiveInfo.ClientUserId is unique for each envelope. (E.g. SessionId). It is used for authentication when we retrieve this document.

 

Step 2: Add Document

DocuSignWeb.Document doc= new Document();

doc.ID = 1.ToString(CultureInfo.InvariantCulture);

doc.Name = documentName;

using (System.IO.FileStream streamReader = new System.IO.FileStream(fullFileName, System.IO.FileMode.Open, System.IO.FileAccess.Read))

{

      byte[] pdfBytes = new byte[streamReader.Length];

      streamReader.Read(pdfBytes, 0, (int)streamReader.Length);

      doc.PDFBytes = pdfBytes;

}

 

Step 3: Create Tabs

DocuSignWeb.Tab tab=new DocuSignWeb.Tab();

tab.DocumentID= doc.ID;

tab. RecipientID = recipient.ID;

tab.Name = name;

tab.TabLabel = name;

tab.PageNumber = pageNumber;

tab.XPosition = XPosition;

tab.YPosition = YPosition;

tab.Type = DocuSignWeb.TabTypeCode.SignHere

 

If Tab is Custom Type then,

 

tab.Type = DocuSignWeb.TabTypeCode.Custom;

tab.SharedTab = true;

tab.Value = value;           

 

If SharedTab property is true, that means all recipients can change the value of that tab.

Step 4: Create Credential

DocuSignWeb.APIServiceSoapClient apiService = new DocuSignWeb.APIServiceSoapClient("APIServiceSoap", "https://demo.docusign.net/api/3.0/api.asmx");

apiService.ClientCredentials.UserName.UserName = "[" + IntegratorsKey + "]";

apiService.ClientCredentials.UserName.UserName += APIUserEmail;

apiService.ClientCredentials.UserName.Password = Password;

 

This credentials you can get from your Member console of Docusign site.

Step 5:  Create Envelope

DocuSignWeb.Envelope envelope = new DocuSignWeb.Envelope();

envelope.Subject = "DocuSign Test Document.";

envelope.EmailBlurb = "Hello!  This was submitted from a sample application";

envelope.Recipients = lstofRecipients;

envelope.AccountId = AccountId;

envelope.AllowMarkup = true;

// assign the document array

envelope.Documents = new DocuSignWeb.Document[lstofdoc.Length];

for (int i = 0; i < documents.Length; ++i)

{

            envelope.Documents[i] = lstofdoc[i].Document;

       }

 

// assign the tabs to the envelope

envelope.Tabs = lstoftabs.ToArray();

 

envelope.CustomFields = fields;

envelope.EnvelopeAttachment = attachments;

 

DocuSignWeb.EnvelopeStatus envStatus = apiService.CreateAndSendEnvelope(envelope);

 

With this document is sent to Docusign.

How to sign document:

RequestRecipientToken function is used to retrieve URL of the document stored in Docusign. We can pass this URL to iframe in our aspx page. To use this function follow steps.

Step 6: Create RequestRecipientTokenAuthenticationAssertion

public DocuSignWeb.RequestRecipientTokenAuthenticationAssertion MakeRecipientTokenAuthAssert(string assertionId)

        {

            DocuSignWeb.RequestRecipientTokenAuthenticationAssertion assert = new DocuSignWeb.RequestRecipientTokenAuthenticationAssertion();

            assert.AssertionID = assertionId;

            assert.AuthenticationInstant = DateTime.Now;

            assert.AuthenticationMethod = DocuSignWeb.RequestRecipientTokenAuthenticationAssertionAuthenticationMethod.Password;

            assert.SecurityDomain = "Loan Demo";

 

            return assert;

        }

 

AssertionId value is informational for you to refer to the recipient. It can be ApplicaionId.

 

Step 7: Create RequestRecipientTokenClientURLs

public DocuSignWeb.RequestRecipientTokenClientURLs StandardUrls(System.Uri urlBase, string userName)

        {

            DocuSignWeb.RequestRecipientTokenClientURLs urls = new DocuSignWeb.RequestRecipientTokenClientURLs();

            urls.OnSigningComplete = urlBase + "?event=SignComplete&uname=" + userName;

            urls.OnViewingComplete = urlBase + "?event=ViewComplete&uname=" + userName;

            urls.OnCancel = urlBase + "?event=Cancel&uname=" + userName;

            urls.OnDecline = urlBase + "?event=Decline&uname=" + userName;

            urls.OnSessionTimeout = urlBase + "?event=Timeout&uname=" + userName;

            urls.OnTTLExpired = urlBase + "?event=TTLExpired&uname=" + userName;

            urls.OnIdCheckFailed = urlBase + "?event=IDCheck&uname=" + userName;

            urls.OnAccessCodeFailed = urlBase + "?event=AccessCode&uname=" + userName;

            urls.OnException = urlBase + "?event=Exception&uname=" + userName;

            return urls;

        }

 

From here you could specify a different redirect target for each status event - signing completed, cancelled, error, etc. We just use one page with different Querystring params to indicate the event.

Step 8: Get Recipient object who is requesting for document

Follow Step 1

Step 9:  Request for document

Get DocuSignWeb.APIServiceSoap as Step 4.

And call:          

apiService.RequestRecipientToken(_envelopeId, recipient.CaptiveInfo.ClientUserId,  recipient.UserName, recipient.Email, assert, clientURLs);

 

This function will return URL for the document to be signed. From here recipient can sign document, decline to sign, sign later.           

 

Thanks,

Posted By: Priyanka Shah

 

Error occurred in deployment step 'Add Solution': Property 'SiteUrl' contains an invalid URL

While deploying custom BDC from visual studio, we may receive error "Error occurred in deployment step 'Add Solution': Property 'SiteUrl' contains an invalid URL".
Workaround
1. Edit feature template file say Feature1.Template.xml
2. add following property under <properties> element <Property Key='SiteUrl' Value='http://your_site_url'/>

Performing CRUD operations in one go (using OPENXML)

Let’s take a simple table (Employee) to perform this task.

 

Employee Table

 

Now for performing the CRUD operation on this table we need to pass input data in XML format as given below in sample code. Note that we already have one record in the table (i.e. Bhavin Patel) & we are intended to add new employee (i.e. Carlos Gozlez); initially we don’t have its EmployeeId, so we can pass 0 (zero) as EmployeeId in the XML string. For updating just need to pass the updated XML data with EmployeeId. For deletion just need to remove employee’s XML string from the below given sample code.

 

Sample data:

 

<ROOT>

<Employee>

   <EmployeeId>2</EmployeeId>

   <FirstName>Bhavin</FirstName>

   <LastName>Patel</LastName>

   <Designation>Sr. Software Engineer</Designation>

</Employee>

<Employee>  

   <EmployeeId>0</EmployeeId>

   <FirstName>Carlos</FirstName>

   <LastName>Gonzlez</LastName>

   <Designation>Team Leader</Designation>

</Employee>

</ROOT>

 

 

 

 

Now let’s see the actual code which performs the CRUD operation in one go

 

 

DECLARE @docHandle INT,

@employeeXml VARCHAR(MAX),

@LastModifiedBy VARCHAR(MAX),

@LastModifiedOn SMALLDATETIME

 

SET @LastModifiedBy = 'Bhavin'

SET @LastModifiedOn = '03/16/2011 3:30 PM'

 

SET @employeeXml = N'

<ROOT>

<Employee>

   <EmployeeId>2</EmployeeId>

   <FirstName>Bhavin</FirstName>

   <LastName>Patel</LastName>

   <Designation>Sr. Software Engineer</Designation>

</Employee>

<Employee>  

   <EmployeeId>3</EmployeeId>

   <FirstName>Carlos</FirstName>

   <LastName>Gonzlez</LastName>

   <Designation>Team Leader</Designation>

</Employee>

</ROOT>'

 

-- Begin the transaction for CRUD operations

BEGIN TRANSACTION

 

-- Create an internal representation of the XML document.

EXEC sp_xml_preparedocument @docHandle OUTPUT, @employeeXml

 

-- Insert new Employee if Not Exist

INSERT INTO Employee(FirstName,LastName,Designation,Deleted,LastModifiedBy,LastModifiedOn)

SELECT DISTINCT A.FirstName, A.LastName, A.Designation, 0, @LastModifiedBy, @LastModifiedOn

FROM OPENXML(@docHandle, 'ROOT/Employee', 2)

WITH (EmployeeId  INT, FirstName VARCHAR(50), LastName VARCHAR(50), Designation VARCHAR(50)) AS A

LEFT OUTER JOIN Employee B ON A.EmployeeId=B.EmployeeId

WHERE B.EmployeeId IS NULL AND ISNULL(B.Deleted,0)=0

 

-- Update Existing Employee Data

UPDATE Employee

SET FirstName=A.FirstName, LastName=A.LastName, Designation=A.Designation,

Employee.LastModifiedBy=@LastModifiedBy, Employee.LastModifiedOn=@LastModifiedOn

FROM OPENXML(@docHandle, 'ROOT/Employee', 2)

WITH (EmployeeId  INT, FirstName VARCHAR(50), LastName VARCHAR(50), Designation VARCHAR(50)) AS A

RIGHT OUTER JOIN Employee B ON A.EmployeeId=B.EmployeeId

WHERE A.EmployeeId IS NOT NULL AND ISNULL(B.Deleted,0)=0

 

-- Delete Employee Data

UPDATE Employee

SET Employee.Deleted=1, Employee.LastModifiedBy=@LastModifiedBy, Employee.LastModifiedOn=@LastModifiedOn

SELECT *

FROM OPENXML(@docHandle, 'ROOT/Employee', 2)

WITH (EmployeeId  INT, FirstName VARCHAR(50), LastName VARCHAR(50), Designation VARCHAR(50)) AS A

RIGHT OUTER JOIN Employee B ON A.EmployeeId=B.EmployeeId

WHERE A.EmployeeId IS NULL AND ISNULL(B.Deleted,0)=0

 

-- Removes the internal representation of the XML document specified by the document handle and invalidates the document handle                 

EXEC sp_xml_removedocument @docHandle

 

IF(@@ERROR=0)

            COMMIT TRANSACTION

      ELSE

            ROLLBACK TRANSACTION

 

 

 

 

 

 

 

Let’s see some more on OPENXML

 

Syntax:

 

OPENXML(idoc int [in],rowpattern nvarchar[in],[flags byte[in]])

[WITH (SchemaDeclaration | TableName)]

 

-- idoc is handler to the xmldoc which contains raw converted xml data in tabular form.

-- rowpattern (/ROOT/Employee) identifies the <Employee> nodes to process.

-- flags (1 = attribute centric, 2 = element centric, 3 = both element & attribute centric)

-- (in case of flag = 3, the attribute-centric mapping is applied first, and then element-centric mapping is applied)

-- SchemaDeclaration | TableName is declaration of temporary table which carries the data from XML string.

 

 

DECLARE @docHandle INT,

@employeeXml VARCHAR(MAX)

 

SET @employeeXml = N'

<ROOT>

<Employee EmployeeId="2" FirstName="Bhavin" LastName="Patel" Designation="Sr. Software Engineer" >

      <Order OrderId="1" EmployeeId="2" OrderDate="03/16/2011 05:45 AM">

            <OrderItem ItemId="1" OrderId="1" Name="Item 1" Price="12.00" />

            <OrderItem ItemId="2" OrderId="1" Name="Item 2" Price="19.00" />

      </Order>

      <Order OrderId="2" EmployeeId="2" OrderDate="03/10/2011 05:45 AM">

            <OrderItem ItemId="3" OrderId="2" Name="Item 3" Price="11.00" />

            <OrderItem ItemId="4" OrderId="2" Name="Item 4" Price="15.00" />

      </Order>

</Employee>

<Employee EmployeeId="3" FirstName="Carlos" LastName="Gonzlez" Designation="Team Leader" >

      <Order OrderId="3" EmployeeId="3" OrderDate="03/03/2011 01:40 AM">

            <OrderItem ItemId="1" OrderId="1" Name="Item 1" Price="12.00" />

      </Order>

</Employee>

</ROOT>'

 

EXEC sp_xml_preparedocument @docHandle OUTPUT, @employeeXml

 

 

-- Attribute Specific --

 

SELECT DISTINCT EmployeeId, FirstName, LastName

FROM OPENXML (@docHandle, '/ROOT/Employee',1)

WITH (EmployeeId INT, FirstName VARCHAR(MAX), LastName VARCHAR(MAX))

 

 

Attribute Specific Result

 

 

SELECT DISTINCT ItemId, Name, Price

FROM OPENXML (@docHandle, '/ROOT/Employee/Order/OrderItem',1)

WITH (ItemId INT, Name VARCHAR(MAX), Price MONEY)

 

Attribute Specific Result with XPath

 

 

-- Element Specific with Attribute Mapping --

 

SELECT *

FROM OPENXML (@docHandle, '/ROOT/Employee/Order/OrderItem',2)

WITH (OrderId INT '../@OrderId', EmployeeId VARCHAR(10) '../@EmployeeId', EmployeeFName VARCHAR(10) '../../@FirstName',

OrderDate DATETIME '../@OrderDate', ItemId INT '@ItemId', Name VARCHAR(MAX) '@Name')

 

 

Element Specific Result With Attribute Mapping

 

 

-- Element Specific --

 

SET @employeeXml = N'

<ROOT>

<Employee>

   <EmployeeId>2</EmployeeId>

   <FirstName>Bhavin</FirstName>

   <LastName>Patel</LastName>

   <Designation>Sr. Software Engineer</Designation>

</Employee>

<Employee>  

   <EmployeeId>3</EmployeeId>

   <FirstName>Carlos</FirstName>

   <LastName>Gonzlez</LastName>

   <Designation>Team Leader</Designation>

</Employee>

</ROOT>'

 

EXEC sp_xml_preparedocument @docHandle OUTPUT, @employeeXml

 

SELECT *

FROM OPENXML (@docHandle, '/ROOT/Employee',2)

WITH (EmployeeId VARCHAR(50), FirstName VARCHAR(50), LastName VARCHAR(50))

 

 

Element Specific Result

 

 

-- Element & Attribute Specific --

 

SET @employeeXml = N'

<ROOT>

<Employee EmployeeId="2" FirstName="Bhavin" LastName="Patel" Designation="Sr. Software Engineer" >

   <FullName>Bhavin Patel</FullName>

   <Order OrderId="1" EmployeeId="2" OrderDate="03/16/2011 05:45 AM">

            <OrderItem ItemId="1" OrderId="1" Name="Item 1" Price="12.00" />

            <OrderItem ItemId="2" OrderId="1" Name="Item 2" Price="19.00" />

      </Order>

      <Order OrderId="2" EmployeeId="2" OrderDate="03/10/2011 05:45 AM">

            <OrderItem ItemId="3" OrderId="2" Name="Item 3" Price="11.00" />

            <OrderItem ItemId="4" OrderId="2" Name="Item 4" Price="15.00" />

      </Order>

</Employee>

<Employee EmployeeId="3" FirstName="Carlos" LastName="Gonzlez" Designation="Team Leader" >

   <FullName>Carlos Gonzlez</FullName>

   <Order OrderId="3" EmployeeId="3" OrderDate="03/03/2011 01:40 AM">

            <OrderItem ItemId="1" OrderId="1" Name="Item 1" Price="12.00" />

      </Order>

</Employee>

</ROOT>'

 

EXEC sp_xml_preparedocument @docHandle OUTPUT, @employeeXml

 

SELECT *

FROM OPENXML (@docHandle, '/ROOT/Employee',3)

WITH (EmployeeId INT, FullName VARCHAR(150))

 

EXEC sp_xml_removedocument @docHandle

 

Element & Attribute Specific Result

SharePoint chart using excel services

Sometimes there is a need to display chart embedded in excel sheet. SharePoint provides REST API for this. Here are the steps to display excel chart.

 

1.      Upload your excel file into the document library say “Shared Documents”.

2.      Add a content editor web part to the page where you want to display the chart.

3.      Now edit the HTML source of content editor web part and put below content

 

<img src="/_vti_bin/ExcelRest.aspx/Shared Documents/Book1.xlsx/Model/Charts('Chart 1')" alt=""/>​

 

Note: please verify the service by typing the url in browser something like

http://<your server>/_vti_bin/ExcelRest.aspx/Shared Documents/Book1.xlsx/Model/Charts('Chart 1')

 

“Chart 1” is the name of chart. You can set the name of the chart as follows:

a.       Open excel sheet.

b.      Click on the chart.

c.       Go to Layout menu. You will see the Chart Name box at the top right ribbon.

 

4.      Save the content editor web part. This should render your chart. For details about the REST API please follow Sample URI For Excel Services REST API

Sharepoint workflow created from sharepoint designer failed on start when list item added from asp.net code via object model

I recently got stuck with one of the strange trouble with a developer. He reported that if he adds a workflow on a list created from sharepoint designer to run automatically when the item is added on list he can not use his code written in one of his asp.net user control to add item into that list. The issue happens is that workflow ends up with message "Failed on start"
 
First instance i suspected security trouble and tried running entire code with elevated permissions but no luck.
 
After looking at the log sharepoint was logging "The root activity type is invalid".
 
The solution found for this trouble is really simple. Adding following configuration in web.config of our asp.net solution resolved the problem.
 

 <configSections>

    <sectionGroup name="System.Workflow.ComponentModel.WorkflowCompiler" type="System.Workflow.ComponentModel.Compiler.WorkflowCompilerConfigurationSectionGroup, System.Workflow.ComponentModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">

      <section name="authorizedTypes" type="System.Workflow.ComponentModel.Compiler.AuthorizedTypesSectionHandler, System.Workflow.ComponentModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />

    </sectionGroup>

  </configSections>

  <System.Workflow.ComponentModel.WorkflowCompiler>

    <authorizedTypes>

      <authorizedType Assembly="System.Workflow.Activities, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" Namespace="System.Workflow.*" TypeName="*" Authorized="True" />

      <authorizedType Assembly="System.Workflow.ComponentModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" Namespace="System.Workflow.*" TypeName="*" Authorized="True" />

      <authorizedType Assembly="System.Workflow.Runtime, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" Namespace="System.Workflow.*" TypeName="*" Authorized="True" />

      <authorizedType Assembly="System.Transactions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" Namespace="System*" TypeName="*" Authorized="True" />

      <authorizedType Assembly="mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" Namespace="System*" TypeName="*" Authorized="True" />

      <authorizedType Assembly="System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" Namespace="System*" TypeName="*" Authorized="True" />

      <authorizedType Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" Namespace="Microsoft.SharePoint.Workflow" TypeName="SPWorkflowActivationProperties" Authorized="True" />

      <authorizedType Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" Namespace="Microsoft.SharePoint.Workflow" TypeName="SPWorkflowTaskProperties" Authorized="True" />

      <authorizedType Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" Namespace="Microsoft.SharePoint.Workflow" TypeName="SPWorkflowHistoryEventType" Authorized="True" />

      <authorizedType Assembly="Microsoft.SharePoint.WorkflowActions, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" Namespace="Microsoft.SharePoint.WorkflowActions" TypeName="*" Authorized="True" />

    </authorizedTypes>

  </System.Workflow.ComponentModel.WorkflowCompiler>

 
 

How to Open Large (>2GB) XML files without Loading the xml Files

Problem: Open large xml files without loading the xml file (more than 2 GB)

Resolution: -

When we think of working with any XML file, we normally think of using XMLDocument (DOM) or DataSet.LoadXML(). Some programmers also use XPathDocument to load the xml file. When we use the above objects, we are loading the files into the system memory. The problem is that, if the size of the xml file is for e.g. 5 GB to 7 GB, we have to load the complete file in System’s Memory. This will cost us systems memory and will throw “System out of Memory Exception”.

The best approach to process such large files is to avoid loading the files into the memory. Microsoft has provided with XmlTextReader class.  XmlTextReader helps us to process the xml file line by line. In this way we are not loading the complete xml file into the memory but processing the file line by line, node by node. The line provides indicates the type, whether it is a StartElement, EndElement, etc… WE can get the complete child nodes and its collection for the parent node using oXmlTextReader.ReadOuterXML().

Below is an example of how to use XMLTextReader class: -

XmlTextReader AgencyTextReader = new XmlTextReader(filename);

AgencyTextReader.WhitespaceHandling = WhitespaceHandling.None;

 

while (AgencyTextReader.Read())

{

if (AgencyTextReader.NodeType == XmlNodeType.Element &&

AgencyTextReader.LocalName == "award" &&

AgencyTextReader.IsStartElement() == true)

            {

                  ProcessAwardNode(AgencyTextReader);

                  AgencyTextReader.Skip();

}

 }

private void ProcessAwardNode(XmlTextReader AwardReader)

{

XmlDocument AwardXmlDoc = new XmlDocument();

AwardXmlDoc.LoadXml(AwardReader.ReadOuterXml());

// we can use xpath as below

agencyID =AwardXmlDoc.SelectSingleNode("award/agencyID").InnerText;

}

Evaluate expression using Reflection

Using Reflection we can evaluate an expression where value of the variables in the expression and even expression too are not known, in fact are generated dynamically at runtime. For e.g. I have an expression that can be sum of value of X and Y for one row and product of value of X and Y for the second row. So here my expression is also dynamic and values are also dynamic. I can use reflection to evaluate resultant for such processes.

Reflection basically is used when you don’t know what your code will return at the runtime (i.e. X + Y or X * Y) but it generates assemblies at runtime and also calls them at runtime and gives you the resultant.

First of all we need to add the reference to reflection in our declaration section.

using System.Reflection;

Now we create an object of c# code provider class, which has the method “CreateCompiler” to create compiler at runtime returning an object of “ICodeCompiler”.

 

Microsoft.CSharp.CSharpCodeProvider cp

= new Microsoft.CSharp.CSharpCodeProvider();

System.CodeDom.Compiler.ICodeCompiler ic = cp.CreateCompiler();

 

 

Now we will create an object of CompilerParameters, which provides us the functionality to add referenced assemblies at runtime.

 

System.CodeDom.Compiler.CompilerParameters cpar =

new System.CodeDom.Compiler.CompilerParameters();

cpar.GenerateInMemory = true;

cpar.GenerateExecutable = false;

cpar.ReferencedAssemblies.Add("system.dll");

 

Define the code to evaluate your expression in a string as shown below. The “strExpression” is the expression you can pass to this method which can be (X + Y) or (X * Y)

 

string src = "using System;" +

 "class myclass" +

             "{" +

             "public myclass(){}" +

             "public double eval(double X, double Y)" +

             "{" +

             "return " + textBox1.Text + ";" +

             "}" +

             "}";

 

Create an object of CompilterResults and call the method “CompileAssemblyFromSource” of ICodeCompiler which takes CompilerParameters and the string of your assembly (which is generated at runtime) as arguments.

 

System.CodeDom.Compiler.CompilerResults cr = ic.CompileAssemblyFromSource(cpar, src);

 

Now you can go through the loop of CompilerError object of CompilerResults to fetch errors, if any present in the resultant of the assembly you executed at runtime. Display the error in message box.

 

foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)

{

MessageBox.Show(ce.ErrorText);

      return;

}

 

If there are no error in the CompilerResults object then we can fetch the Type of newly created assembly (which is created at runtime). Fetch the MethodInfo object using “GetMethod” method of Type object. We can fetch the resultant value by creating the instance of Type object using Invoke method.

 

if (cr.Errors.Count == 0 && cr.CompiledAssembly != null)

{

Type ObjType = cr.CompiledAssembly.GetType("myclass");

      MethodInfo info = ObjType.GetMethod("eval");

      object value = info.Invoke(Activator.CreateInstance(ObjType),

new object[] { Convert.ToDouble(txtX.Text),

               Convert.ToDouble(txtY.Text) });

      MessageBox.Show(value.ToString());

}

 

Thus to fetch a expression value at runtime where expression values and operators are dynamic can be achieved using reflection.

 

The only drawback of using reflection it degrades the performance by 400% compared to early binding. So we should use runtime assemblies only when we do not have the possibility of early binding in the process.

 

1 - 10 Next