Sunday, November 30, 2014

Storing integers in an enum

Example
  
enum DepartmentID
    {
        HumanResource = 1001,
        Marketing = 1002,
        Sales = 1003,
        Logistics = 1004,
        Operations = 1005,
        Finance = 2003,
        IT = 2002,
        Training = 2001,      
        SharedServices = 1006,
    }

On instances where you need the departmental id, you could easily retrieve the integer values of the enum by casting:

Eg:
(int)DepartmentID.Marketing


Hence, the code becomes easy to maintain.
On a side note: Comes in handy when building a query string for a sql select command.


Saturday, November 29, 2014

Formatting ListView Items

Formatting can be done either through the ASPX page or on the code behind. Below are two different instances where formatting is done.

1) Formatting the <ItemTemplate> in the Aspx page


<div class="EmployeeName">

<asp:Label ID="sampleLabel" Text='<%# String.IsNullOrEmpty(DataBinder.Eval(Container.DataItem, "employeeName").ToString()) ? "" :  DataBinder.Eval(Container.DataItem, "employeeName").ToString().PadRight(140).Substring(0,140).TrimEnd() %>'
Runat="server"/>

</div>
   
Here....I'm getting values from the database. I do, an "empty or null" check. In case the condition is true, display nothing, else display the values retrieved from the DB while restricting text  to 141 characters.                  

2) Also, you could do stuff in the code behind. Below, I limit text on item data bound.

2.1) First create a event handler

<asp:ListView ID="SearchResultsListView" runat="server" ... OnItemDataBound="employeeListView_ItemDataBound">

2.2) Then...
In the employeeListView_ItemDataBound method add the relevant code. I have added some formatting code. The FindControl() method is used to capture the label.

protected void employeeListView_ItemDataBound(object sender, ListViewItemEventArgs e)
{
            string trailer = "...";
            string tempString = string.Empty;
            Label sampleLabel;

            sampleLabel = (Label)e.Item.FindControl("sampleLabel");
            if (sampleLabel.Text.Length > 100)
            {
                tempString = sampleLabel.Text.Substring(0, 96).Trim();
                sampleLabel.Text = tempString + trailer;
            }
}


Sunday, November 23, 2014

JavaScript to Access List Item GUID in SharePoint 2010

The SharePoint 2010 client object model has provided JavaScript means to access SharePoint Lists, Libraries and items, etc.... Below is a sample where I access a SharePoint list item GUID information during a on click event on a list item. The item click is triggered at the XSLT code rendering the custom field. This is the related JavaScript.

Here the item GUID is captured.



var itemID = null;
var item = null;
var currentItemGUID = null;

//Assigned the itemID value coming from XSLT [JavaScript method call on a hyperlinks OnClick() method]

function MyTestFunction() {
    context = new SP.ClientContext.get_current();
     list = context.get_web().get_lists().getById(SP.ListOperation.Selection.getSelectedList());
     item = list.getItemById(itemID);

    context.load(item);
    context.executeQueryAsync(
        function(sender, args) {
            currentItemGUID = item.get_item('UniqueId');
        },
        function(sender, args) {
            alert('Request Failed' + args.get_message() + '\nStackTrace: ' + args.get_stackTrace());
        }, "sp.js");
    
}

Saturday, November 22, 2014

Adding a Web Part Property


1) Declare a private  variable
        private bool mySampleCheckBox = true;

2) Add the browsable web part property

        [System.Web.UI.WebControls.WebParts.WebBrowsable(true),
        System.Web.UI.WebControls.WebParts.WebDisplayName("Property Display Name on Web Part Edit"),
        System.Web.UI.WebControls.WebParts.WebDescription("Description of the property"),
        System.Web.UI.WebControls.WebParts.Personalizable(
            System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared),
        System.ComponentModel.Category("Category to include the property"),
        System.ComponentModel.DefaultValue(true)
        ]
        public bool SampleCheckBox
        {
            get { return mySampleCheckBox; }
            set { mySampleCheckBox =  value; }
       }

It would be much cleaner to use two using directives to refer System.ComponentModel and System.Web.UI.WebControls.WebParts and then, remove the repeated code above.

You could set the personalization scope to either Shared or User depending on your requirement.
     
Web part property types and their respective display controls in the web part properties pane are as below:

Property Type
Display
string
Textbox
bool
Checkbox
int
Textbox
float
Textbox
DateTime
Textbox
Enum
Dropdown

Sunday, November 16, 2014

ADO.Net - SqlDataReader

Below is a sample usage of the SqlDataReader class in ADO.Net.
reader.HasRows checks if any rows are returned.


string connectionString = "Data Source=DataBaseServerName;Initial Catalog=DataBaseName;Persist Security Info=True;User ID=UserName;Password=Password;";
string query = "select eid, name, email from dbo.Employee where status=1";

            try
            {
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    SqlCommand command = new SqlCommand(query, connection);
                    connection.Open();

                    SqlDataReader reader = command.ExecuteReader();

                    if (reader.HasRows)
                    {
                        while (reader.Read())
                        {
                            Console.WriteLine("Column1 : {0} | Column2 : {1} | Column3 : {2}", reader[0],                                          reader[1], reader[2]);
                        }
                    }
                    reader.Close();
                }
            }


Saturday, November 15, 2014

Download file from SharePoint site to the Server Drive for processing

There could be times where one might need to download a file for processing in the server before rendering. May be for a file type conversion prior to rendering or so...During such instances this can be used. The below code block needs to be run within elevated privileges.


web.AllowUnsafeUpdates = true;
SPFile file = web.GetFile(fileUrl);

using (FileStream outStream = new FileStream("Specify the file Download location in server drive"), FileMode.Create))
{
    byte[] obj = (byte[])file.OpenBinary();
    outStream.Write(obj, 0, obj.Length);
}
web.AllowUnsafeUpdates = false;


Side Note:
You can specify the download location in the web.config <AppSettings> section and retrieved via:
ConfigurationManager.AppSettings["AppSettingName"].ToString();


Sunday, November 9, 2014

Built-in functions in SQL - Part 1

There are some important built-in functions in T-SQL which are used on a daily basis. ISNULL() & DATEDIFF() are some of such

1) ISNULL()

ISNULL ( check_expression , replacement_value )
The first parameter is the expression to be checked, secondly we have the result to give out in case the expression is NULL. This can be used to null check column values.

For an instance:
ISNULL(columnName, 0) will give out zero to indicate the value of the particular column is null, so that it can be skipped

Applications:
In a select statement within the where clause ISNULL(columnName, 0)=1 could be used so that any row having null values for this particular column would be skipped.


2) DATEDIFF()

WHERE DATEDIFF(DAY, tableName.DateTimeCloumn, GETDATE()) > 7

DATEDIFF returns the time between two dates. The first parameter is the datepart (eg: day, year, month, etc). The second and third parameters are start date and end date respectively.



Saturday, November 8, 2014

Programmatically Adding User to Site - SPRoleAssignment & RoleDefinitionBindings


In this post I'm adding a domain user to a SharePoint 2010 site programmatically.
I am using a simple console application for this purpose. The code is as below:

using Microsoft.SharePoint;

namespace SPTestConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            AddUser();
        }

        static void AddUser()
        {
            string siteUrl = "http://localhost:1000/SitePages/Home.aspx";

            SPSecurity.RunWithElevatedPrivileges(delegate() {
                using (SPSite site = new SPSite(siteUrl))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPRoleDefinitionCollection collroleDefinitions = web.RoleDefinitions;
                        SPRoleAssignmentCollection colllroleAssignments = web.RoleAssignments;

                        SPRoleAssignment oRoleAssignment = new SPRoleAssignment("DOMAIN\\username","user@company.lk", "UserName","Notes");
                        SPRoleDefinitionBindingCollection collRoleDefBinding=oRoleAssignment.RoleDefinitionBindings;
                        collRoleDefBinding.Add(collroleDefinitions["Read"]);
                        colllroleAssignments.Add(oRoleAssignment);
                    }
                }
            });
        }
    }
}


Roll Assignments -> are the permissions in the site &
RoleDefinition -> are the permission levels in the site

Sunday, November 2, 2014

the name SPSecurity does not exist in the current context

In SharePoint when using SPSecurity you might come across this error "the name SPSecurity does not exist in the current context"


Probably you are using a sandbox solution. You cannot use SPSecurity in sandbox solutions. Instead, go with a Farm solution in order to run this code.







Saturday, November 1, 2014

Creating Content Source and Scope - SharePoint 2007 [Part 1]

Creating a Content Source
In the Central Admin, go to Shared Services.

1) Go to Search Administration page.


2) Select Content Sources


Any web application you create is added into the address list in the default content source which is "Local Office SharePoint Server Sites

If you need to have separate search for you web application you can have a separate content source and add a separate search scope for that. This approach can also be used if you need to target your search to retrieve data from target lists.

3) create a new content source, by clicking on the "New Content Source"


Here I have created two new content sources targeting two different search results.

To add web application URL's to the content source you need to go inside the default content source and remove the web application URL first from there, save the content source, and then come back to the newly created content source and include the URL there.