Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Wednesday, February 25, 2015

C# is allowed in Office 365 API's Sandbox

So far in Office 365 API Sandbox we have written only javascript to call the API's and deploy the changes. It is very limited in terms of achieving the goals and against some complex requirements. So, after some additional good work from Office 365 team, there is a release of C# code support in API sandbox. This is a brilliant idea and good help for developers to quickly write code and check on the fly. I will update you more findings on it soon.

Read more details here Office 365 API Sandbox now allowing C# Code

Saturday, August 20, 2011

Customize ReportViewerWebPart in C# for all SharePoint Zones

This is one of the major milestone I have achieved recently to customize the report viewer web part for SharePoint sites. The issue I was facing: the SharePoint site which I have developed was too complex and it exposed via 3 zones. http://intranetsite, http://extranetsite, https://internetsite
  1. http://intranetsite – which is Windows based authentication site and for intranet people.
  2. http://extranetsite – Which is Windows based authentication site and for extranet people
  3. http://internetsite – Which is Forms based authentication site and for internet people.

For each sub site in our implementation it should show the SSRS dashboard report of the site we are in which will contains all information of the site through reports. But, SSRS reporting services and report viewer web part has a limitation in SharePoint integration mode:

System.Web.Services.Protocols.SoapException: The specified path refers to a SharePoint zone that is not supported. The default zone path must be used. ---> Microsoft.ReportingServices.Diagnostics.Utilities.SecurityZoneNotSupportedException: The specified path refers to a SharePoint zone that is not supported. The default zone path must be used.

Saturday, July 16, 2011

Permissions for document 'Move' operation in SharePoint

This might not be a super thing to blog but very important point to note. Through code I have tried to move a document from one document to another document by using file.MoveTo() operation. It was working very fine when I tested as I am administrator in the dev environment. But, when I have given to QA for testing it was failing. I have tried so many combinations of giving different access to them and nothing worked. When I have given them either Owners or site collection administrator access it started working. So, I was not understanding of what was the permission level do they need?
After tried different combinations of permission levels to them one matched and worked perfect. That was Contribute and Approve permission levels. So, for the logged in users who don't have both of these permission levels the code is failing for them and the  result file was not moving successful. [Another note is, I am using publishing site with auto approval of document in document library.]

Code used:
SPFile file = currentItem.File;
file.MoveTo(filePath, true);
For a document move operation the logged in user should need both Contributor and Approve permission levels for publishing web sites in SharePoint.

I am thinking it is correct according to my analysis and research. Please let me know if something is wrong in this post or any better solutions.

Thursday, May 19, 2011

Get bytes from Stream in c#

I know you may think what is the need of this post as this is very minor or simple to think and write. But, whenever I need to get bytes from a stream object, I always forgot it. This is simple but most of the times we used to Google. So, planned to write it to remember at least myself next time.
public byte[] GetBytesFromStream(Stream stream)
{
     byte[] buffer = new byte[16 * 1024];
     using (MemoryStream ms = new MemoryStream())
     {
        int read;
        while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
        {
           ms.Write(buffer, 0, read);
        }
        return ms.ToArray();
     } 
}
 

Sunday, January 16, 2011

Delete event receiver from a SharePoint list

In my previous post, we saw how we added an event receiver to a list. Now, we will see how to delete the existing event receiver on a list.
private void DeleteEventReceiverFromAList(string siteUrl)
    {
        using (SPSite site = new SPSite(siteUrl))
        {
            using(SPWeb web = site.OpenWeb())
            {
                try
                {
                    SPList list = web.Lists["myList"];
                    if (list != null)
                    {
                        string className = "EventReceiverClass";
                        string asmName = "EventReceiverAssemblyName, Version=1.0.0.0, Culture=neutral, PublicKeyToken=a865f0ecc234ea51";
                        web.AllowUnsafeUpdates = true;

                        int receivers = list.EventReceivers.Count;
                        bool isAddedReceiverExist = false;
                        bool isUpdatedReceiverExist = false;
                        for (int i = 0; i < receivers; i++)
                        {
                            SPEventReceiverDefinition eventReceiver = list.EventReceivers[i];
                            if (eventReceiver.Class == className && eventReceiver.Type == SPEventReceiverType.ItemAdded)
                            {
                                eventReceiver.Delete();
                                break;
                            }
                        }
                    }
                }
                catch { }
                finally
                {
                    web.AllowUnsafeUpdates = false;
                }
            }
        }
    }
In this code also, there is nothing to explain very detail. Please let me know if you have any questions.

Add event receiver to a SharePoint list

This is very generic and everyone knows how to add an event receiver. But, usually we attach the event receiver on a list template, site etc. This post deals with adding event receiver to a specific list.
private void AddEventReceiverToAList(string siteUrl)
{
using (SPSite site = new SPSite(siteUrl))
{
using (SPWeb web = site.OpenWeb())
{
try
{
SPList list = web.Lists["myList"];
if (list != null)
{
int receivers = list.EventReceivers.Count;
string className = "EventReceiverClass";
string asmName = "EventReceiverAssemblyName, Version=1.0.0.0, Culture=neutral, PublicKeyToken=a865f0ecc234ea51";
web.AllowUnsafeUpdates = true;
bool isAddedReceiverExist = false;
for (int i = 0; i < receivers; i++)
{
SPEventReceiverDefinition eventReceiver = list.EventReceivers[i];
if (eventReceiver.Class == className && eventReceiver.Type == SPEventReceiverType.ItemAdded)
{
isAddedReceiverExist = true;
break;
}
}
if (!isAddedReceiverExist)
list.EventReceivers.Add(SPEventReceiverType.ItemAdded, asmName, className);
}
}
catch { }
finally
{
web.AllowUnsafeUpdates = false;
}
}
}
}
This is very straight forward code and hope you got it.

Hide content types from a SharePoint library through coding

Please read the post here.

Change content type order in NEW button of a SharePoint library

This is continuation of my previous post. After you read that post you get clear understanding of how we added the content types to a library through coding. But, what if there is a requirement we need this content type order to be shown when I select the NEW button from the list tool bar or hide some content types? Then again we need some sort of code which does that for all existing lists as we cannot change manually if there are plenty of webs in a site.
private void ChangeOrHideContentTypesInALibrary(SPList list)
{
list.ContentTypesEnabled = true;

SPFolder folder = list.RootFolder;

List<SPContentType> orderedContentTypes = new List<SPContentType>();
foreach (SPContentType ct in folder.ContentTypeOrder)
{
if (ct.Name.Contains("ContentType1") || ct.Name.Contains("ContentType2"))
orderedContentTypes.Add(ct);
}

folder.UniqueContentTypeOrder = orderedContentTypes;
folder.Update();
}

If you observe the above code, then the variable orderedContentTypes is what having the content types of which we need to show in the NEW button of the list toolbar. In which order we add the content types to this variable, that order they will be added to the list and shown on the toolbar. And second thing is out of 3 content types available in the above logic we have added only two to the variable. So the third content type will be hidden from the toolbar. And the last two lines in the above function are to update the list with the latest content types order.

Hope this gives you clear idea on how to order and hide content types on a list/library.

Add content type to a SharePoint list or library through code

In one of my SharePoint projects, there is a requirement like a SharePoint site has 140+ sub sites and each web has 2 lists which I need to update. There are 2 content types which are inheriting by each list and now I have to add another through coding. It is very difficult to go through all webs and each list in each web and manually add it. So, thought of writing a simple script which will loop through them and update them. So, here is the code I came up with.
private void AddContentTypeToLibraries(string siteUrl)
{
List<SPContentType> contentTypes = new List<SPContentType>();
using (SPSite site = new SPSite(siteUrl))
{
using (SPWeb web = site.OpenWeb())
{
contentTypes.Add(web.ContentTypes["ContentType1"]);
contentTypes.Add(web.ContentTypes["ContentType2"]);
contentTypes.Add(web.ContentTypes["ContentType3"]);
}
foreach (SPWeb web in site.AllWebs)
{
try
{
web.AllowUnsafeUpdates = true;

foreach (SPList list in web.Lists)
{
if (!list.Title.Equals("MyList", StringComparison.InvariantCultureIgnoreCase))
continue;

for (int i = 0; i < contentTypes.Count; i++)
{
AddContentTypeToList(contentTypes[i], list);
}
}
}
catch { }
finally
{
web.AllowUnsafeUpdates = false;
web.Dispose();
}
}
}
}

void AddContentTypeToList(SPContentType ct, SPList list)
{
if (list.ContentTypes[ct.Name] == null)
{
list.ContentTypes.Add(ct);
list.Update();
}
}
The first method is what we are looping through all webs and go to each list and try to add a content type. And the second method is before adding a content type to a list, we are checking whether the content type is already there or not for that list. So, we are checking for that condition and if find the content type is not already attached to the list then only we are adding to the list.

Hope you understand the logic and how we need to implement it.

Monday, August 23, 2010

Check drop down list contains a value in c#

This is again a very simple post and want to share. I have seen many people write good coding, but, sometimes they don't pick efficient way to do somethings. When we do code reviews we can identify some code parts are very simple to implement but they implement it in complex way, want to correct them. A simple scenario is, how to check a drop down contains a value. Some people are looping through all items and finding the item exists or not. Some people are doing some complex logic etc. But, below is what I believe the good and simple way of finding a value is in drop down list of items.
if (ddlUserType.Items.FindByValue("someValue") != null)  
{  
   ddlUserType.SelectedValue = "someValue";  
} 
Do you think, is there any efficient way of doing this?

bind Enum to drop down list in ASP.NET

This the question asked by so many people around me and I also faced issues couple of times of my early stages of learning.This is simple but, how to get value and names as a collection and bind to drop down list is a bit difficult. Below is the simple logic to read all enums and create a list item and bind to drop down list. [There are many ways to get this done, but I believe below is the best way.]
foreach (UserType ut in Enum.GetValues(typeof(UserType)))
{
ListItem item = new ListItem(Enum.GetName(typeof(UserType), ut), ((int)ut).ToString("D"));
ddlUserType.Items.Add(item);
}
I think, you like this post. Let me know if you have any issues.

Saturday, January 16, 2010

Report viewer control authentication – Part 2 – Forms Authentication

If the reporting services configured to use forms authentication and you need to show the reports in the custom developed applications then the need of processing authentication the report viewer control through the code.
Report viewer control authentication using windows authentication is described in the part 1 here. Now, we will discuss the authenticating forms authentication through C# code.
If we are are developing windows application and want to use report viewer control, then we need to implement the below logic to authenticate.
reportViewer1.ServerReport.ReportServerCredentials.SetFormsCredentials(null, "userName", "password", "");
this.reportViewer1.RefreshReport();
Where as in forms authentication simply assigning the credentials not enough. The reasons behind are, security, code efficiency, performance, response time etc everything come into the picture. So, we need to write code which supports everything.
What are the major tasks?
  • Report viewer control excepts the credential of type IReportServerCredentials. So, we need to create an object which inherits from this interface and pass this to the report viewer control to authenticate.
  • Handling cookie. Based on the login and request is successful we will write the cookie to browser and keep that in browser for further requests processing. The advantage is if cookie is available then won’t make any request to report server for authenticating.
  • To create the cookie related information we actually need of hijack the request and response and get the cookie information and save it to browser. So, how to catch the request and response which made to report server? We will discuss this later in this article.
  • To actually communicate to the report server, we need to make the communication with it. The best way to do that is using web services. Everyone knows that reports in SSRS gets with two sites. One is report manager means report web application [/reports] and the report server means a report web service[/reportserver]. So, we will use the web service, write a proxy and implement the existing functions in it.

Sunday, December 27, 2009

How to get or access master page in user control

My requirement is I want to get the reference to the master page and access the public property of a master page in user control. As we know that master page is also inherited from the user control, I can say this is simple and we can easily get the reference.

I am using master page in my web application and all pages are using that master page. And there are user controls in the application and my requirement is how to access the master page property inside a user control. Below is the solution how I resolved the problem.

In user control ASCX file declare the below line to establish the reference to the master page.

<%@ Reference Control="~/DefaultMaster.Master" %>

IN the ASCX.CS file, we need to fill the master page object to access it's properties. For this,

  • Declare a master page class variable as the user control class variable as shown below.

DefaultMaster masterpage = null;

NOTE: Remember the DefaultMaster is the class of DefaultMaster.master class.

  • In Page_Load event of user control, fill the masterpage object as shown.

masterpage = this.Page.Master as DefaultMaster;

Now, you are all set to use master page object and access everything inside it. If you observed, everything is simple object model. I am just accessing the objects. I think, you got better idea and the way I used. Hope this helps and any comments always welcome.

How to get the current row in the grid view command event

This is what I faced a small problem when using GridView. I have a LinkButton element in the gridview and my goal is when user clicks on the button, I need to raise the grid view command event and in that event, I need to get the row values. But, the questions is how to get the current row in the grid view command event?  Below is the solution for it.

GridViewRow row = ((LinkButton)e.CommandSource).NamingContainer as GridViewRow;

Note: Remember LinkButton class I used in the above code is assuming that the command event raised when clicked on the LinkButton control. If your requirement is not linkbutton then please place the corresponding control name.

Most of the times and most of the developers never use the property available to each and every object named NamingContainer. But, there are lot of advantages with this property. Especially when we write and render controls to page dynamically then this property will help a lot. And there are many properties which will help us to solve so many problems. Use the intellisense and try to know most of the properties available for a .NET control.

Hope, this will help you and you got what you need. Please let me know what you think on this post.

C# display date time with milliseconds

By default, in c# DateTime object will display the values in the 12 hours format with AM and PM. Which don't include the milliseconds. But how to display the date and time with milliseconds? Use the below format to display it.

DateTimeObject.ToString("yyyy-MM-dd HH:mm:ss.fff")

f is for the format for printing the milliseconds. Remember when you try to convert the date time with milliseconds back to C# Date time, then just use Convert.ToDateTime().

Hope this helps.

Thursday, October 8, 2009

Set Focus to ASP.NET control

This is the question I received from developers on how to set the focus to an ASP.NET control from server side. Because once page is posted back to server or when request sent to server, from the response we need to set the focus to some x control on the page from server side.

There are requirements like this. For example, we have multiple panels on the page and when you saved the data successfully of a panel then you need to show the user the panel they submitted with some successful message instead of showing them the top section of  page always. :) Otherwise, user always needs to scroll down to the panel where he edited the changes and see whether the data saved successfully or not. An user experience problem.

Usually, the way the developers will do is, catch the control in client side either using javascript or jquery, then they will write logic to set the focus to it. But it's not needed. We can simply use the existing functions available in ASP.Net and C# and implement the behavior without any pain. See below example on how to do that.

C# language by default providing some options to set the focus to an ASP.NET control on the page. There are two ways to do that.

  • You can directly use Focus() method to set focus to a control. 
    tbName.Focus();
  • You can use the Page object function named "SetFocus" to set the focus to a control as shown below. 
    Page.SetFocus(tbName);
Note: Assuming "tbName" is the textbox control id on the page.

So, by using any of the above ways we can set the focus to a control from server side code itself. I hope this will help you. Please provide your comments on it.

NOTE: Don't try to set the focus to the control when it is in disable mode or invisible. This will give some problems in the client side.

Wednesday, October 7, 2009

Import excel data to SharePoint list

This is one of the nice and best SharePoint feature that we have implemented. By default SharePoint will provide us an option to edit in spreadsheet or download list items in spread sheet. But, it doesn't have the option to import the excel data to SharePoint list. When we have data in excel format and want to import that data to a sharepoint list, then how to do. That is why we took it as a challenge and implemented this.

And second reason is, this feature has a nice and wonderful feature of column mapping. You can manually choose column to column mapping, so that the column names not needed to be exactly same. This is one of the best option in this feature.

This feature works for both SharePoint and WSS.

The installation is simple and it is using the codeplex sharepoint installer package to install the feature. As it is developed as a SharePoint feature, you can get this feature associated with each list under the actions tab once you activated it. You can call this feature by going to specific list, under actions menu item just click on the feature name. Then it will take to a page which has a nice user interface to upload an excel, then choose specific sheet and then map the fields as you want.

You can take a look at it here on CodePlex.

http://spreadsheet2splist.codeplex.com/

I think, this will help you out to import data from excel to SharePoint list problem. Isn’t it?

Sunday, September 13, 2009

Cross page postback in ASP.NET

This is the blog post I want to present you something that you need to know. When I was new to IT industry and ASP.NET programming, I believe the ways to access the page1 variables on page2 are as follows.

  • Querystring parameters
  • Session management using session etc..

So, when I want to access the values of page1 on page2, I will store them in a session by creating session variable and will use it in the page2. And another method is, by passing values to page2 in query string parameters from page1. But this need some extra processing on server side to redirect them to that page.

After got little bit experience and when I came to the same situation where I need to pass the parameters from one page to another page, there cross page post back option helped me. So, I want to share the feature with you. This is the third way of passing values from one page to another page.

ASP.NET framework default supports it. There are some parameters to the Page object which helps us to get the logic work.

  • PreviousPage
  • IsCrossPagePostBack

When you want to call server side programming, usually we will write server side control with click event or command event which does the postback and execute server side logic for that event. But when you want to call different page in click event, then you need to use a special property called "PostBackUrl" and to it you need to set the url of the destination page. So, that post back event call that page. This is what the concept called Cross page PostBack.

In programming point of view how to implement this?

ASPX Code: [Page1.aspx]

<asp:TextBox runat="server" ID="tbCrossPageTest"></asp:TextBox>
<asp:Button runat="server" Text="Submit" PostBackUrl="~/Page2.aspx" />

C# Code: [Page2.aspx]

if (PreviousPage != null && PreviousPage.IsCrossPagePostBack)
        {
            TextBox tb = (TextBox)PreviousPage.FindControl("tbCrossPageTest");
        }

Here, we need to check for some conditions as best practice. One is for whether to know PreviousPage object is null or not and second, is current page from cross page post back. PreviousPage is the object which holds the page1 object and from it, you can find any control on the page and access the values. I know, we don’t use this in many times, but you need to know this option is available in ASP.NET. Please let me know you ideas on it and provide your feedback. Hope this will help you better in understanding the cross page post back.

Note: This cross page post back won't change any of current page properties. For example, page2.IsPostBack is false only, when cross page post back is raised on page1. So, don't confuse.

Tuesday, August 18, 2009

Get Querystring parameters in Page Webmethods ASP.NET

Today, at my work I have to find a way on how to get the query string parameters and use them in logic. I mean, I can get them in javascript side and send them as parameters, but I don’t want to implement it that way as I have everything in query string, I can get it from URL and use it in server side code. And second thing is, the query string parameters are not plain text, they are encrypted with a strong algorithm. So, below is the small function I written which work perfect.

//Get Querystring name value collection
    public static NameValueCollection GetQueryStringCollection(string url)
    {
        string keyValue = string.Empty;
        NameValueCollection collection = new NameValueCollection();
        string[] querystrings = url.Split('&');
        if (querystrings != null && querystrings.Count() > 0)
        {
            for (int i = 0; i < querystrings.Count(); i++)
            {
                string[] pair = querystrings[i].Split('=');
                collection.Add(pair[0].Trim('?'), pair[1]);
            }
        }
        return collection;
    }

So, this function is a static one because, we are calling it from a Webmethod. And this function is expecting url as the parameter. Actually, it is not complete url, it is just the complete querystring url which starts from the character '?'. Now, how to call and use this function? Find below.

NameValueCollection collection = GetQueryStringCollection(HttpContext.Current.Request.UrlReferrer.Query);
        if (collection != null && collection.Count > 0)
        {
            string id = HttpContext.Current.Server.UrlDecode (collection["id"]);
        } 

The above statement returns the querystring value which has the key "id". This way you can get any querystring value, just by passing it's key name to the collection.

HttpContext.Current.Request.UrlReferrer.Query – Which holds the complete querystring url starts from '?'. So, this way you can get the query string data and use it where ever you want in Page Webmethods.

Is this what you are looking for? Or do you have any other ways to get the querystring data? Please post your ideas on it here.

Call ASP.NET server side event in JQuery

For one of my requirement, I need to implement this functionality on how to call server side event in JQuery. There are many scenarios on why we need to implement it or what is the need for it. I have a button and when user click on it, I need to show a client side light box which exactly functioning as window confirm box. If user selects OK, then I need to do some client side validations and if everything passed, then i need to make a call to server to execute the actual server side click event. I think this is general scenario. There are many cases other than this. So, here is a simple solution on how to call server side event in JQuery. Enjoy this interesting blog post.

1. Create a protected page variable in Server side ASPX.cs file as shown below.

protected string serversideEvent = string.Empty;

2. In Page_Load event, set the serversideEvent variable to the button click event as below.

serversideEvent = Page.ClientScript.GetPostBackEventReference(btnSubmit, string.Empty);

3. In your JQuery, use this function to evaluate on specific condition as shown in below line.

eval(<%=serversideEvent %>);

"btnSubmit" is the ID of the control <asp:Button in ASPX page. and GetPostBackEventReference will get the click event of the related button and return it in the form of string.

That's it. Whenever the line mentioned in 3rd step called, it will call server side event and execute it.

How awesome it is? Very simple and nice way to do it. Isn’t a good and valuable find?