Upload image to sharepoint library using FileReader

I am pretty much tired to get solution for uploading image to picture library. But finally achieved it.

I hope it will be useful to someone.

Idea behind implementation

  1. Your browser should support FileReader API.
  2.  Read the contents are buffer by using “readAsArrayBuffer” function which is belongs to “FileReader”.
  3. On load of file (image), just pass the file input control result to your REST query.

Upload image with in sharepoint site (not in app)


function uploadFileUsingRest() {
var fileInput = document.getElementById('myFile');
var reader = new FileReader();
reader.onload = function (e) {
performUploadAction(fileInput.files[0].name, e.target.result);
}
reader.readAsArrayBuffer(fileInput.files[0]);
}
function PerformUploadAction(filename, fileData) {
$.ajax({
url: _spPageContextInfo.webAbsoluteUr + "/_api/web/getfolderbyserverrelativeurl('ImagesLibrary')/files/add(url='" + filename + "', overwrite=true)",
method: "POST",
binaryStringRequestBody: true,
data:fileData,
contentLength:fileData.length,
headers: {
"accept": "application/json; odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"content-type":"application/json; odata=verbose"
},
async:true,
processData:false,
success: function (data) {
console.log("Success! Your Picture was uploaded to SharePoint.");
},
error: function onQueryErrorAQ(xhr, ajaxOptions, thrownError) {
console.log('Error:\n' + xhr.status + '\n' + thrownError + '\n' + xhr.responseText);
}
});
}
  • Don’t forget to add processData:false in your ajax parameters.
  • This code will not work in sharepoint apps (sharepoint hosted app).

Upload image using sharepoint app


function uploadFileUsingRest() {
var reader = new FileReader();
reader.onload = function (result) {
var fileData = '';
var byteArray = new Uint8Array(result.target.result);
for (var i = 0; i < byteArray.byteLength; i++) {
fileData = fileData + String.fromCharCode(byteArray[i]);
}
PerformUploadAction(fileInput.files[0].name, fileData, uploadToFolder);
}
reader.readAsArrayBuffer(fileInput.files[0]);
}
function PerformUploadAction(filename, fileData, uploadToFolder) {
executor = new SP.RequestExecutor(appweburl);
var targetUrl = appweburl + "/_api/SP.AppContextSite(@target)/web/lists/getByTitle('" + libraryToSearch + "')/RootFolder/folders(@TargetFolderName)/Files/add(url=@TargetFileName,overwrite='true')?@target='" + mysiteUrl + "'&@TargetFileName='" + filename + "'&@TargetFolderName='" + uploadToFolder + "'";
executor.executeAsync({
url: targetUrl,
headers: { Accept: "application/json;odata=verbose", "content-type": "application/json;odata=verbose" },
method: "POST",
contentType: "application/json;odata=verbose",
binaryStringRequestBody: true,
body: fileData,
async: false,
success: function(){
console.log('Success');
},
error: function(){
console.log('Error');
}
});
}

Happy coding…🙂

Log exception in sharepoint using Windows event Log

When ever any exception occurs in sharepoint it will be logged in Logs directory of sharepoint. But when ever we are writing the coding solutions it is better to log our exceptions in some place. So, today I want to show, how to log the entry in the windows event viewer.

We will create with an EventLog class. Following is the solution.


public static void LogException(Exception ex)
 {
  try
  {
       SPSecurity.RunWithElevatedPrivileges(delegate()
       {
         if (!EventLog.SourceExists("MySPSource"))
               EventLog.CreateEventSource("MySPSource", "Application");

         EventLog eventLog = new EventLog();
         eventLog.Source = "MySPSource";
         string message = string.Format("Exception Detail: {0}{1}Stack Trace: Exception occurred {2}", ex.Message.Trim(), Environment.NewLine, ex.StackTrace.Trim());
         eventLog.WriteEntry(message, EventLogEntryType.Error);
       });
  }
   catch (Exception)
   {

   }
 }

 

Deploy Infopath with backend code in sharepoint 2010

I was so much struggled to deploy a infopath form into a sharepoint 2010 which is having backend code to connect database. Finally got the solution. I want to share this because it will definitely helpful to you.

Objective: 

Deploy a Infopath 2010 form which connecting to the Database into sharepoint server.

Requirements:

1. Infopath 2010.

2. Sql server 2008 with northwind database (what ever you required).

3. Sharepoint server 2010. (it should be server only)

Steps:

1. Create infopath form and write backend code in code editor.

2. Complie the solution. Get the dll.

3.  Publish the infopath form with administrator approved.

4. Create a feature with and deploy into shareoint server.

5. Activating  feature in  site collection.

Procedure

1. Create infopath form with backend code:

Open the infopath blank form and click on design. It will open a new form. Insert any design template what you needed. Drag and drop the textboxes and button into the form layout.

infopathdesign1

Change the control ids of text boxes and buttons if needed. Double Click on the button. In the ribbon you will see the Properties tab under Control Tools section is in visible state. If not visible select manually in ribbon. Click on custom code.

We want to connect to database. But here the opened visual studio kind tool doesn’t have a reference of  System.Data. To enable this add a reference to System.Data by right click on reference add reference. Now add the following code in your code editor.  Before pasting this code into your code editor please make sure the names/control ids of buttons and text boxes.


using Microsoft.Office.InfoPath;
using System;
using System.Xml;
using System.Xml.XPath;
using System.Web;
using System.Data;
using System.Data.SqlClient;

namespace NWInfopath
{
 public partial class FormCode
 {
 public void InternalStartup()
 {
 ((ButtonEvent)EventManager.ControlEvents["CTRL6_5"]).Clicked += new ClickedEventHandler(CTRL6_5_Clicked);
 ((ButtonEvent)EventManager.ControlEvents["CTRL7_5"]).Clicked += new ClickedEventHandler(CTRL7_5_Clicked);
 }

public void CTRL6_5_Clicked(object sender, ClickedEventArgs e)
 {
 SqlConnection sqlconn = null;
 SqlCommand sqlcmd = null;
 SqlDataReader rdr;
 XPathNavigator empid = this.MainDataSource.CreateNavigator().SelectSingleNode("/my:myFields/my:txtEmpid", this.NamespaceManager);
 XPathNavigator empLastName = this.MainDataSource.CreateNavigator().SelectSingleNode("/my:myFields/my:txtLastName", this.NamespaceManager);
 XPathNavigator empFirstName = this.MainDataSource.CreateNavigator().SelectSingleNode("/my:myFields/my:txtFirstName", this.NamespaceManager);
 XPathNavigator empTitle = this.MainDataSource.CreateNavigator().SelectSingleNode("/my:myFields/my:txtTitle", this.NamespaceManager);
 XPathNavigator empCity = this.MainDataSource.CreateNavigator().SelectSingleNode("/my:myFields/my:txtCity", this.NamespaceManager);
 int intEmpID = Convert.ToInt32(empid.Value);
 XPathNavigator resultBox = this.MainDataSource.CreateNavigator().SelectSingleNode("/my:myFields/my:result", this.NamespaceManager);
 try
 {
 using (sqlconn = new SqlConnection())
 {
 sqlconn.ConnectionString = "Data Source=locat;Initial Catalog=Northwind;Integrated Security=true";
 string executeQuery = "Select [LastName],[FirstName],[Title],[City] from MYEmployees where [EmployeeID]=" + intEmpID;
 sqlcmd = new SqlCommand(executeQuery, sqlconn);
 sqlconn.Open();
 rdr = sqlcmd.ExecuteReader();
 while (rdr.Read())
 {
 empLastName.SetValue(rdr["LastName"].ToString());
 empFirstName.SetValue(rdr["FirstName"].ToString());
 empTitle.SetValue(rdr["Title"].ToString());
 empCity.SetValue(rdr["City"].ToString());
 }
 sqlconn.Close();
 }
 }
 catch (Exception ex)
 {
 resultBox.SetValue("Exception occurred" + ex.Message);
 }
 }

public void CTRL7_5_Clicked(object sender, ClickedEventArgs e)
 {
 SqlConnection sqlconn = null;
 SqlCommand sqlcmd = null;
 SqlDataReader rdr;
 XPathNavigator empid = this.MainDataSource.CreateNavigator().SelectSingleNode("/my:myFields/my:txtEmpid", this.NamespaceManager);
 XPathNavigator empLastName = this.MainDataSource.CreateNavigator().SelectSingleNode("/my:myFields/my:txtLastName", this.NamespaceManager);
 XPathNavigator empFirstName = this.MainDataSource.CreateNavigator().SelectSingleNode("/my:myFields/my:txtFirstName", this.NamespaceManager);
 XPathNavigator empTitle = this.MainDataSource.CreateNavigator().SelectSingleNode("/my:myFields/my:txtTitle", this.NamespaceManager);
 XPathNavigator empCity = this.MainDataSource.CreateNavigator().SelectSingleNode("/my:myFields/my:txtCity", this.NamespaceManager);
 XPathNavigator resultBox = this.MainDataSource.CreateNavigator().SelectSingleNode("/my:myFields/my:result", this.NamespaceManager);

 try
 {
 using (sqlconn = new SqlConnection())
 {
 sqlconn.ConnectionString = "Data Source=local;Initial Catalog=Northwind;Integrated Security=true";
 string executeQuery = "insert into MYEmployees(EmployeeID,LastName,FirstName,Title,City) values("+empid.Value+",'" + empLastName.Value.ToString() + "','" + empFirstName.Value.ToString() + "','" + empTitle.Value.ToString() + "','" + empCity.Value.ToString() + "')";
 sqlcmd = new SqlCommand(executeQuery, sqlconn);
 sqlconn.Open();
 int result = sqlcmd.ExecuteNonQuery();
 if (result > 0)
 {
 resultBox.SetValue("Record inserted successfully.");
 empid.SetValue("");
 empLastName.SetValue("");
 empFirstName.SetValue("");
 empTitle.SetValue("");
 empCity.SetValue("");
 }
 sqlconn.Close();
 }
 }
 catch (Exception ex)
 {
 resultBox.SetValue("Exception occured" + ex.Message);
 }
 }
 }
}

Now your code is ready. Just test it whether it is working fine or not. To test this one save the project and close the editor. Now goto infopath form and click on preview option or click F5. Now test it. If it is not working fine then open the code editor and put a debug points and press F5 and find out where mistake was happened.  Lets hope every thing is working fine.

Build the project and get .dll file:

Now we need to collect the .dll file. To copy the dll open once the code editor and click on the root node in the solution explorer. in the properties pane the path where the project was saved will appear. Copy that path and paste in the windows explorer. From there got BIN –>Release copy the .dll file. and paste in any other folder from where you want to deploy your solution package.

Publish  .xsn form with as administrator approved:

Its time to approve our form with administrator privilege.  Why administrator privilege? Any reason? Yes! Because we are deploy this one as a farm solution. So administrator only can do. Thats why we are publishing with administrator approved.  To do this click on file menu in infopath designer and click on farm options and select the following values and click on ok.

Programming : C# (because i given code in c#).

Compatability : Webbrowser form

Security and trust : Full trust.

Now select the publish option in the file menu select sharepoint server. Now one window will come there you enter the site collection to where your form should deploy. Click next –> Next –> Give the location where you want to store your published form. Next –>Next. The screens will appear like this.

publishstep1 publishstep2 publishstep3

Now your form was published. You have published form and .dll file.

Create Feature to deploy into sharepoint server:

you have to take care at this step.  Now i am showing to create feature manually. We can also do with visual studio. But Manual deployment will give you the good practice in writing scripts for deployment.

Now create a folder any where and in that folder create a 14 hive structure for features as below.

Your_folder_Name\14\Template\Features\Your_Folder_Name (here feature name need not be the same. But if you give same name it is safe side).

Paste the published xsn file and .dll file in the last folder.

In the last folder create two xml files with names element.xml , feature.xml. Elements.xml should contain following code.


<?xml version="1.0" encoding="utf-8" ?>
 <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
<Module Name="XSN" Url="FormServerTemplates" RootWebOnly="TRUE">
 <File Url="<span style="color: #ff6600;">myxsnname.xsn"</span> Name="<span style="color: #ff6600;">myxsnname.xsn</span>" Type="GhostableInLibrary" />
 </Module>
 </Elements>

feature.xml should contain following code.


<?xml version="1.0" encoding="utf-8" ?>
<Feature xmlns="http://schemas.microsoft.com/sharepoint/"
 Id="<span style="color: #ff6600;">68B4013A-DD8D-48DB-ADA2-D6561A8E7E54</span>"
 Title="TitleOfYourFeature"
 Description="This feature deploys the browser enabled Expenses Workflow InfoPath Form."
 Version="14.0.0.1"
 Scope="Site"
 DefaultResourceFile="ipfscore"
 ReceiverClass="Microsoft.Office.InfoPath.Server.Administration.XsnFeatureReceiver"
 ReceiverAssembly="Microsoft.Office.InfoPath.Server, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" >
 <ActivationDependencies>
 <ActivationDependency FeatureId="C88C4FF1-DBF5-4649-AD9F-C6C426EBCBF5"/>
 </ActivationDependencies>
 <ElementManifests>
 <ElementManifest Location="element.xml"/>
 <ElementFile Location="myxsnname.xsn"/>
 <ElementFile Location="dllname.dll"/>
 </ElementManifests>
</Feature>

Here .dll name will generate by the code editor it self. so just copy that name and paste it here. Make sure all the valueswere give correctly or not. I marked in red color where you want to take care about it.

Now come back to root folder. Now you have to create two batch files. One is to create the .wsp file and another one is to deploy into sharepoint server. Lets name the two files as Createwsp.bat InfopathInstall.bat.

Createwsp.bat


@ECHO OFF
echo Running WSP Builder
"C:\WSPBuilder\Buildx86\Buildx86\WSPBuilder.exe" -wspname NWInfopath_Approved.wsp -Buildcas false -solutionId 336BF7D6-E848-4ABD-98B1-EA96B7779DEC
pause

Every time you are using this change the solution id to new GUID.

InfopathInstall.bat


@ECHO OFF
SET STSADM="C:\Program Files\Common Files\Microsoft Shared\web server extensions\14\BIN\STSADM"

@ECHO OFF
ECHO ======================================

ECHO Retract Solution
%STSADM% -o retractsolution -n NWInfopath_Approved.wsp -immediate
ECHO ======
%STSADM% -o execadmsvcjobs
ECHO Remove Solution
%STSADM% -o deletesolution -n NWInfopath_Approved.wsp -override
ECHO ======
%STSADM% -o execadmsvcjobs
ECHO Adding Solution
%STSADM% -o addsolution -f NWInfopath_Approved.wsp
ECHO ======
%STSADM% -o execadmsvcjobs
ECHO Deploying Solution
%STSADM% -o deploysolution -n NWInfopath_Approved.wsp -immediate -allowgacdeployment -force
ECHO ======
%STSADM% -o execadmsvcjobs

pause

ECHO Installation Completed

first run the createwsp.bat file. You can see the wsp created in your folder. Now run the infopathinstall.bat now the solution will deploy into sharpeoint sever.

Activating  feature in  site collection :

Now goto your site collection and see in the site collection features. under the site collection features you can see your feature name. Now activate it.

Now it was activated. We have to use this as a content type in the document library.

If you know how to add content types to a document library its fine. Otherwise I will show how to use this infopath form to use as a content type for a document library in my next post.

Happy coding.

Make automatic Logout when user is inactive for “X “minutes

1. We can do session management in sharepoint applications or sites. When ever we prepare Public facing websites we have to enable this session management. For example banking applications are the good examples for the session management applications. If we are inactive for 10 mins (more or less), it will automatically signed out after performing any actions.
2. This session management can do for the users who are created through forms based authentication. By default if you login through windows authentication, the session expiration time is 10hrs.
3. First you have to enable the site with Forms based authentication functionality. If you don’t know how to do it, follow my previous post which is documented nicely.
4. After you done with the above step, just need to enable the session with the powershell script.

$sts = Get-SPSecurityTokenServiceConfig 
$sts.UseSessionCookies = $true 
$sts.FormsTokenLifetime = (New-Timespan –Minutes 10)
$sts.LogonTokenCacheExpirationWindow = (New-Timespan –Minutes 10)
$sts.Update() 
iisreset

Note
In above script make sure that you should provide a space between “New-TimeSpan” and “-Minutes 10” terms. Other wise it should throw an error as object not found.
5. Now login with forms based authentication user and check. For testing purpose it is better to give time as 1 or 2mins. If it works fine for you then increase the time and execute the script again.

Good luck.

Creating custom master page in visual studio and deploy it to the sharepoint site

To achieve this task, we have to perform following tasks.
1. Open the sharepoint designer and open any site. Goto master pages section in the designer and take a copy of existing master page and paste into the same gallery. Do some customization. After customization my site is appearing as below.

2. Now open the visual studio and create a New project–> Empty Sharepoint project (select the .net framework 3.5) and give the project name. Give the url in the coming screen into which you want to deploy your master page.

3. Now right click on the solution in the visual studio, Add–> New Item–>Module.

4. Rename the Sample.txt into Sample.master. Open the Sample.master page and remove the existing content. Now paste the content form the master page you already customized earlier. Open the Elements.xml file and enter the following code.

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Module Name="CustomMaster" Url="_catalogs/masterpage">
    <File Path="CustomMaster\Sample.Master" Url="CustomMaster/Sample.Master" Type="GhostableInLibrary" IgnoreIfAlreadyExists="TRUE" />
  </Module>
</Elements>

Now deploy the solution.

Now the solution was deployed into your site. We have to enable the necessary features and map our master page to our site. For this follow the below steps.
1. Goto the site in which you deployed your solution and goto Site Settings and activate the following features at site collection level(Site Settings –> Site Collection Administration –>Site collection features ) and site level (Site Settings –> Site Actions –> Manage Site features) respectively.
a. SharePoint Server Publishing Infrastructure
b. SharePoint Server Publishing

2. After activating come back to the site settings page and goto Look and Feel section –> Master page. Now select our required master page from the drop down and click on ok.

In the above image I just only applied our master page to the site. If you want to use the same master page to System pages also, the select our master page in the below section also and click ok.

3. Now goto home page and check whether our master page applied or not. After applying the changes my final page looks like this.

4. upto now every thing is fine. But some times while opening the popups like adding a new item, we came across a situation like our custom menu may appear int the popup like below.

If you found like this, don’t worry we have a solution.
Goto visual studio solution once and open our Sample.master page and search for the area what coming in the popup. In my case, my custom menu is appearing in the popup. I went to that custom menu area in the master page and applied the class s4-notdlg.

<div class="navigationarea s4-notdlg">

Now deploy the solution again and refresh the page and open the popup once and see the magic.

Hope this post is helpful to you.

Thanks.

Create delegate control in sharepoint

Hello,
Today I am going to explain about creating delegate controls in sharepoint.
If you want to see any delegate controls you can visit in the master page. For publishing site there is nightandday.master page which is default master page for the home page of the site.
You can find the following delegate controls in the nightandday.master page.

<SharePoint:DelegateControl runat="server" ControlId="AdditionalPageHead" AllowMultipleControls="true"/>
<SharePoint:DelegateControl ControlId="GlobalSiteLink3-mini" Scope="Farm" runat="server"/>

Before moving to how to create a delegate control, first we look at what is the importance of delegate control.

Importance:

  • Using the delegate control a developer can customize the SharePoint site controls without editing or even touching the master page.
  • Suppose we created a control for displaying the advertisements in the master page. If we want to keep this control in the master page we need to edit that master page and add all the controls over here. At any time if any mistake happen then whole master page will disturb. To avoid this we have delegate controls.
  • Mapping the delegate control to master page
    After creating the delegate control now we want to add it to the master page. To do this we have one tag that is

    <SharePoint:DelegateControl runat="server" ControlId="" AllowMultipleControls=""/>

    ControlId –> is the Id of the control which we given in the elements.xml file while deploying the file. (Don’t worry at this time. We will cover in how to create delegate control in Visual Studio section)
    This is the main element for delegate control.

    Creating delegate control in Visual Studio
    Now I am creating a small control to enable a link for registering the new user in home page.
    To do this, you have to enable the forms based authentication. If you are not familiar to how to setup forms based authentication for sharepoint 2010 site then visit previous post.

  • After setting up the forms based authentication, open the visual studio and create an empty project.
  • Now add the control templates mapped folder, visual webpart, empty element like below image.
  • Now add the following code to the designer surface of the visual webpart
  • <div id="RegisterUserDiv" runat="server">
     <a href="#">Sample Delegate Control</a>
    </div>
    
  • In elements.xml file under the empty element you added, add the following code.
  • <?xml version="1.0" encoding="utf-8"?>
    <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
      <Control Id="RegisterHereControl" Sequence="1000" ControlSrc="~/_controltemplates/RegisterUser.ascx" />
    </Elements>
    
  • Save the changes and deploy into the site.
  • Upto now we created a delegate control and deployed. Now we want to add it to our site. Now add the following code to our master page.
  • <SharePoint:DelegateControl ControlId="RegisterHereControl" AllowMultipleControls="true" runat="server"></SharePoint:DelegateControl>
    
  • It will look like this.