Sunday, 26 July 2015

Get current user using javascript - SharePoint client object model

Hi All,

  In this post we will see about, getting the loggedin Username using Javascript only.
In Client object model , to get the value of the loggedin User, mostly everyone will go for $().SPServices.SPGetCurrentUser. SP Services ibrary has tons of uses and is very easier.
But we can do this without referencing a third party library, if your requirement is like so.

Below given is the code for it.

function getCurrentUser()
{
var context = new SP.ClientContext.get_current();
this.website = context.get_web();
this.currentUser = website.get_currentUser();
context.load(currentUser);
context.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}



function onQuerySucceeded(sender, args)
 {
 alert(currentUser.get_loginName());
 }



function onQueryFailed(sender, args)
{
alert('request failed ' + args.get_message() + '\n'+ args.get_stackTrace());
}

Hope this helps somewhere. Happy coding..

Wednesday, 15 July 2015

Programmatically getting the values from a SharePoint list view

Hi,
 Today I will share the code for getting the values of the items in a particular view through Client Side Object Model.
For this we have to make 2 requests. First request is to get to know which view & view query and second would be for getting the values from that view.

$(document).ready(function () {
    SP.SOD.executeFunc('sp.js', 'SP.ClientContext', getItemsFromView);
});

// First request
function getItemsFromView()
{
    var context = new SP.ClientContext.get_current();
    var list = context.get_web().get_lists().getByTitle('List Name');
    var view = list.get_views().getByTitle('View Name');
    context.load(view);
    context.executeQueryAsync(
        function (sender, args) { getItemsFromList('List Name', "<View><Query>" + view.get_viewQuery() + "</Query></View>") },
        function(sender, args) {alert("error: " + args.get_message());}
    );
}
//Second Request
function getItemsFromList(listTitle, queryText) {
    var context = new SP.ClientContext.get_current();
    var list = context.get_web().get_lists().getByTitle(listTitle);
    var query = new SP.CamlQuery();
    query.set_viewXml(queryText);
    var items = list.getItems(query);
    context.load(items);
    context.executeQueryAsync(
        function () {
            var listItemInfo = '';
            var listEnumerator = items.getEnumerator();
            var i = 0;
            while (listEnumerator.moveNext())
            {
                i++;
            }
            alert("items retrieved: " + i);
         
        },
     
function (sender, args) { alert("error in inner request: " + args.get_message()); }
   );
}

Hope this helps. Happy Coding :)

Sunday, 12 July 2015

Programmatically Send E-Mail using System.Net.Mail - SharePoint

Hi,
 There are some limitations while sending mails through SPUtility.SendEmail method as I have stated here.

1.   No attachment allowed
2.   Message body size cannot exceed 2048 characters.
3.   The from address will be the “Outbound Sender Address” configured in the central admin.


To Overcome these we are going to follow the below approach.

Using SmtpClient from System.Net.Mail namespace.

Namespaces required:

using System.Net.Mail;
using Microsoft.SharePoint.Administration;


Below is the code for sending Email:

SmtpClient smtpServer = new SmtpClient(webApp.OutboundMailServiceInstance.Server.Address);

MailMessage mail = new MailMessage();
mail.From = new MailAddress("fromEmail@abc.com");
mail.To.Add("toEmail@abc.com");
mail.Subject = "subject";
mail.Body = "body";
mail.BodyFormat = System.Web.Mail.MailFormat.Html;
System.Web.Mail.MailAttachment attachObj = new System.Web.Mail.MailAttachment("path of the attachment in SharePoint");
mail.Attachments.Add(attachObj);

smtpServer.UseDefaultCredentials = true;
smtpsmtpServer.Send(mail);


By Following this we can overcome the limitations faced in SPUtility.SendEmail method.

Have a good Day :)
Happy Coding :)

Programmatically Send E-Mail using SPUtility.SendEmail - SharePoint

Hi All,
 Today we will see about Email in SharePoint (programmatical approach)

If you want to Send E-mail through SharePoint, We can use the capabilities already provided by SharePoint. (i.e) SPUtility.SendEmail. This is basically SharePoint's native functionality for email delivery.

First you will need to be sure that outgoing mail settings are configured for SharePoint. After that you can easily send email from your custom SharePoint application using SharePoint’s native mail capabilities. You can do this in Central Administration.
Open Central Admin --> System Settings --> Configure Outgoing Email

Before attempting to send an email from your application, you can easily check to be sure that the outgoing email settings are configured.

bool blnIsEmailServerSet = SPUtility.IsEmailServerSet(web);

If this returns false, you should not bother trying to send the email. Instead, show an error message or notify the SharePoint administrator, to check the settings of the server. If it returns true, you are good to go:

To use this method we will require namespaces:

using Microsoft.SharePoint.Utilities;
using System.Collections.Specialized;

Code:

 Below given is the code.

            using (SPSite oSite = new SPSite("Site collection URL"))  //Site collection URL
            {
                using (SPWeb oSPWeb = oSite.OpenWeb("Subsite URL"))  //Subsite URL
                {
                    StringDictionary headers = new StringDictionary();

                    headers.Add("from", "senderEmail@domain.com");
                    headers.Add("to", "receiverEmail@domain.com");
                    headers..add("bcc","HiddenuserEmail@domain.com");
                    headers.Add("subject", "Send Email using SP Utility");
                    headers.Add("fAppendHtmlTag","True"); //To enable HTML format

                    System.Text.StringBuilder strMessage = new System.Text.StringBuilder();
                    strMessage.Append("body of the message that can include html tags also");
                 
                    strMessage.Append("<span style='color:red;'> HTML </span>");
                    SPUtility.SendEmail(oWeb, headers, strMessage.ToString());

                }
            }


Some Limitations for this method are :

1.   No attachment allowed
2.   Message body size cannot exceed 2048 characters.
3.   The from address will be the “Outbound Sender Address” configured in the central admin.

To overcome the limitations, use the System.Net.Mail class methods to send E-mail.
I have given details here.

Happy Coding :)

Monday, 6 July 2015

Programmatically Diasable List Throttling for a specific List in SharePoint - Powershell

Hi All,

 Today we will see about "How to Diasable List Throttling for a specific List".

SP2010 introduces list throttling settings that allow us to specify how many items a user can query before the throttle kicks in and aborts the query. This applies to both the queries that retrieve through SharePoint UI and from custom code. Default limit is 5000 items per list. While exceeding this limit results in display of an error message. We can override it by calling RequestThrottleOverride on the SPQuery object. This will allow us to execute large unsafe queries.

SharePoint 2010 provides Administrators to control a limit of how many items to be retrieved from the lists at a time using User Interface or Object Model.

SharePoint by default set some limitation to your web application to make sure that performance is good even when data increasing. These limitations has been tested and carefully chosen by SharePoint Team and Microsoft does not recommend changing these value.


List Throttiling feature is webapplication level.
If we want to change the limits for the whole web app,
From Central Administration
1. Go to SharePoint 2010 Central Administration
2. Under Application Management, click "Manage Web Application"
3. Choose the web application that you want to change. On the ribbon click "General Settings" and then "Resource Throttling"
4. Change throttling settings and click OK.

To override the default throttling settings. just execute the below powershell to add list items more than the threshold limits.

web = Get-SPWeb -Identity http://mysite
$web.AllowUnsafeUpdates = $True
$list = $web.Lists["ListName"]
$list.EnableThrottling = $False
$list.Update()
$web.AllowUnsafeUpdates = $False
$web.Update()
$web.Dispose()

Thanks for your time.. Happy SharePointing..

Wednesday, 1 July 2015

Everyone and Everyone except external users SharePoint Online - Boundaries and Limitations.

 Hi All,

Today we will see about SharePoint Online. Let's say you have been asked to share a content (file or site or anything). Now these two words come into picture "everyone" and "everyone except external users".

Want to get more details about "External Users" - Check here

When a user is added to Office 365, the user automatically becomes a member of Everyone except external users. The important thing we have to note is that, By default, the Everyone except external users group is added to the Members group on the SharePoint Team Site. It is automatically assigned a permission level of Contribute. This means all users who are added to Office 365 can view, add, update, and delete items from lists and libraries.

If you want to change the permission levels for this group, you can remove it from the Members group and then add it to a group that uses different permissions. For example, you might add the Everyone except external users to the SharePoint Visitors group. This automatically assigns a Read permission level to all users in the Everyone except external users group.


And there is a difference between "everyone" and "everyone except external users".

Everyone:

All users no matter whether they are authenticated to access the SharePoint Online. For example, you share a document with everyone, and then all users can anonymously access the document as if they have the document URL.

Everyone except external users:

All internal user accounts which can be recognized by SharePoint Online.

And we have some limitations while using these groups.


  • While sharing some content with either of these groups, you can't send invitation mail for them.


  • You can't remove a user from either of these groups. Say, you want to share a document with all the persons except some few people. You can't go and delete those specific users. For this situation you have to create a new SharePoint group and add all the users you want in that.

Share me your feedback :)
Have a good day :)