Posts by Inspired-by-tech

How to Embedding a PDF Object in a SharePoint 2010 Web part using C#

How to Embedding a PDF Object in a SharePoint 2010 Web part using C#

Recently I was assigned the task of displaying a PDF in a SharePoint Web part. I figured it’d be easy enough to display it in an <iframe> or simply embed it on the page, but unfortunately my assumption couldn’t have been further from the truth.

Attempting to load the PDF in an <iframe>

Quite simply, and by default, SharePoint does not allow users to automatically open documents within a browser window. There is a setting on the web application called Browser File Handling, which if set to Permissive is supposed to allow documents to open within the browser. Alas, this setting does not afford the ability to view PDFs within the browser window. Also, within the Document Library, there’s a setting called Opening Documents in the Browser, which defaults to opening files within the browser anyway… So SharePoint is working against us.

Using the <embed /> tag

The <embed /> tag was deprecated for XHTML in favor of the <object> tag, so it’s not “supported” in Visual Studio. There is however a way around this; create a Literal control in C# and then write it to your page at run-time to avoid any compile errors. Upon assigning the src attribute, this strategy proves fruitful as it simply embeds the PDF in the window as desired. This is great, except for the fact that this strategy is completely invalid. I wanted to do one better.

Using the <object> tag

The <object> tag is a not only a valid XHTML control; it’s also supported in Visual Studio. Unfortunately, it requires a Class, ClassID, or ProgID attribute. I wasted hours scouring the web for this specific ClassID, and in the end, I could not locate it. This drove me to create a new strategy; a hybrid of the <embed /> and <object> strategies. This way I can ensure maximum browser support while doing my best to implement valid code.

//Create your URL to the pdf file, including path and URL variables
string url = web.Url + “/” + “DocumentLibrary” + “/” + CurrentMonday.ToString(“MM-dd-yyyy”) + “.pdf” +
“#scrollbar=0&statusbar=0&navpanes=0&toolbar=1&zoom=75″;
//Establish Literal control
Literal l1 = new Literal();
//Write the Object code to the Literal
l1.Text = “<object id=’AcrobatFrame’ type=’application/pdf’ classid=’clsid:CA8A9780-280D-11CF-A24D-444553540000′ width=’711′ height=’956′><param name=’src’ value=’” + url + “‘ /><a href=’” + url + “‘>Click here to download “ + CurrentMonday.ToString(“MM-dd-yyyy”) + “.pdf</a></object>”;
//Add the Literal to the Page
Panel.Controls.Add(l1);

Acrobat URL variables

In the code above you can see that I am passing URL variables to define what application components are visible and the zoom of the pdf. This way I can set a static height and width for the object because I know the size of the document will always be the same. See a list of all URL variables.

 

Read More

How to Customize the background of a UITabBarController

How to Customize the background of a UITabBarController

Customizing the background of a UITabBarController

Here is a common question I get and I see this question a lot on the forums “how do I change the background of a UITabBarController?”. Well, it’s really quite easy, and it can make a big difference on how your iPhone application is presented.

Step 1

In order to achieve the above you are going to need to create a custom UITabBarController class. In XCode, choose ‘New File’ and then select ‘Cocoa Touch Class/Objective-C Class (subclass NSObject)’. Call the class ‘CustomUITabBarController’.

Open up CustomUITabBarController.h and ensure the code looks like the following:

#import <UIKit/UIKit.h>

@interface CustomUITabBarController: UITabBarController {
IBOutlet UITabBar *tabBar1;
}

@property(nonatomic, retain) UITabBar *tabBar1;
@end

Open up CustomUITabBarController.m and ensure the code looks like the following:

#import “CustomUITabBarController.h”
@implementation CustomUITabBarController
@synthesize tabBar1;

– (void)viewDidLoad {
[super viewDidLoad];
tabBar1.backgroundColor = [UIColor clearColor];
CGRect frame = CGRectMake(0, 0, 480, 49);
UIView *v = [[UIView alloc] initWithFrame:frame];
UIImage *i = [UIImage imageNamed:@”grad.png”];
UIColor *c = [[UIColor alloc] initWithPatternImage:i];
v.backgroundColor = c;
[c release];
[[self tabBar] insertSubview:v atIndex:0];
[v release];
}

@end

Step 2

Open up the ‘MainWindow.xib’ and choose the Tab Bar Controller. Now look at the property inspector and change the class to your custom class, then associate the tabBar1 outlet to the Tab Bar Controller.

You may have noticed from the code that it references a file called ‘grad.png’. This is the new background image for your tab bar. In my example the image is 320px x 49px, however you may want to double this for the retina display.

You should now have a custom UITabBarController background! What do you think?

Read More

Using SP.UI.ModalDialog in SharePoint 2010

Using SP.UI.ModalDialog in SharePoint 2010

If you are looking for primarily ‘client side’ functionality, you can use the SP.UI.ModalDialog class. I find this class very useful when creating visual webparts in SharePoint 2010 that require some sort of administrative feature or user feedback. In fact, if you look at the SharePoint 2010 architecture, you’ll notice that Microsoft have tried to avoid moving you to different pages in favor of the modal view. The SP.UI.ModalDialog class is accessible through the SharePoint JavaScript file called SP.UI.Dialog.js which is located in the layouts directory. Here is an example of how you can quickly get the SP.UI.ModalDialog class working in your code:

First we create the JavaScript function that will open up the new modal view. Notice I’m passing variables to the function for the file path, width and height. I did this so I can reuse the function for a variety of modal view calls for different purposes.

functionModalDialog(FormPath, FormWidth, FormHeight) {
varoptions = SP.UI.$create_DialogOptions();
options.url = FormPath;
options.width = FormWidth;
options.height = FormHeight;
options.allowMaximize = false;
options.dialogReturnValueCallback = Function.createDelegate(null, CloseCallback);
SP.UI.ModalDialog.showModalDialog(options);
}

We now need to create our call back method called ‘CloseCallback’ as mentioned in the above function. This method will be used to capture the results of the modal and perform some sort of confirmation action.

functionCloseCallback(result, returnValue) {
alert(‘dialogResult’ + result + ‘\nreturnValue’+ returnValue);

if(result == SP.UI.DialogResult.OK)
{
SP.UI.Notify.addNotification(‘You chose the OK button’);
document.title = returnValue;
}

if(result == SP.UI.DialogResult.cancel)
SP.UI.Notify.addNotification(‘You chose the Cancel button’);
}

You’ll see from the above method that we provide an alert with the full feedback of the modal and then utilize the SP.UI.Notify class to provide additional methods of feedback.

Now all we need to do is add an onClick of onClientClick event to an object in your code.

onclick=”ModalDialog(‘/_layouts/TestPage.aspx’,’420′,’300′)”

This is a quick introduction, but it should be enough to get you going with the SP.UI.ModalDialog class.

Read More

Customizing the SharePoint 2010 Welcome Menu (PersonalActions)

Customizing the SharePoint 2010 Welcome Menu (PersonalActions)

I support a SharePoint 2010 environment at my company and was recently asked to add an extra item to the welcome dropdown box (also know as the Personal Actions Menu) usually located at the top right of your SharePoint pages. This item was a feedback feature where users at any given location on the site could provide feedback, report a bug or add a general enhancement request.

I decided to store the data in a simple SharePoint list and implement a CustomAction Element using Visual Studio. I could have used a list view to manage the capture of the data, however I didn’t need all of the bells and whistles that came with one of those views and ultimatley created a custom application page with a form.

Creating a CustomAction is pretty easy, you just need to identify the GroupId and Location of the menu you wish to modify and then you’re good to go. You even have a simple function called a URLAction where you can direct people to a page when they click on your custom action. What isn’t so obvious is if you actually wanted your application page to popup in a modal view. Here is the code I used to get this done.

The CustomAction

Create a new blank SharePoint project in Visual Studio and then add a new ‘Empty Element’ to your project (I called mine CustomActions). Open up the CustomActions file and you should see something like this:

<?xml version=”1.0” encoding=“utf-8“?>
<Elements xmlns=“http://schemas.microsoft.com/sharepoint/“>
</Elements>

Add the following so that your file now looks like this:

<?xml version=“1.0” encoding=“utf-8“?>
<Elements xmlns=“http://schemas.microsoft.com/sharepoint/“>
<CustomAction Id=“CustomGlobalLinks”
ImageUrl=“/Assets/FeatureLogo.png”
Description=“Provide feedback or Submit an Enhancement Request”
Location=“Microsoft.SharePoint.StandardMenu”
GroupId=“PersonalActions”
Sequence=“1001”
Title=“Feedback“>
<UrlAction Url=“javascript:(function () { var o = { url:’/_layouts/CustomGlobalLinks/Feedback.aspx’, title: ‘Feedback’, allowMaximize: false, showClose: true, width: 480, height: 280 }; SP.UI.ModalDialog.showModalDialog(o); }) ();“/>
</CustomAction>
</Elements>

Let’s break this down. The ImageUrl will give you a logo to the left of your Action on the menu; this is optional. The location refers to where you want to put your action and the GroupId refers to which group on the menu you want to add it too. I’ve used the PersonActions group.

I added some custom JavaScript to the URLAction which executes SP.UI.ModalDialog.showModalDialog and displays your application page in a modal. I actually found this script on another blog, however I can’t find it any more to give credit. I’ll certainly add the credit when I find it again.

The Application Page

Add a new Application Page to your project (I called mine Feedback). Add your controls (e.g. drop downs, text boxes etc.) and then hook them up to your feedback list (already created in your SharePoint environment).

On the submission of your form, you can close your modal by calling ‘window.frameElement.commitPopup();’ Here is some quick code on pulling content from your SPList to popluate a dropdown and how to write back:

Categories Dropdown

SPList FeedbackList;
SPSite site = SPContext.Current.Site;
…………………………………………………………………

FeedbackType.Items.Add(“– SELECT –”);
SPFieldChoice cf = (SPFieldChoice)FeedbackList.Fields[“Category”];
foreach (string type in cf.Choices)
{
FeedbackType.Items.Add(type);
}
FeedbackType.DataBind();

Write back to the SPList

SPWeb web = site.RootWeb;
SPListItemCollection ItemCollection = FeedbackList.Items;
SPListItem ListItem = ItemCollection.Add();
ListItem[“Category”] = FeedbackType.SelectedItem.Text;
ListItem[“Feedback”] = FeedbackText.Text;
ListItem.Update();
successfulSubmit();

Read More

Export Gridview to CSV in a SharePoint 2010 Webpart

Export Gridview to CSV in a SharePoint 2010 Webpart

I was recently tasked with creating a Gridview in a SharePoint 2010 Webpart. In addition to assigning data to the Gridview, I also needed to create a way to export the data. Typically you would go down the route of exporting to Excel so I looked at some code from another blogger http://mattberseth.com/blog/2007/04/export_gridview_to_excel_1.html.

This worked, however Excel did not recognize the file format as the document is basically a text file. As a result the user would get an ugly prompt saying something like “cannot verify the file format, would you still like to open”. This was not acceptable. So I tried using the code from the blog mentioned above to create a CSV file, which opened with no error, although the document was not formatted with data correctly because a CSV is a comma delimited text file.

So I now know that I can overcome the Excel document open error with a CSV, I just need to create the code to do the export and here it is:

Convert the contents of the GridView Cells from controls to text

private string getGridCellText(TableCell tc)
{
string cellText = “”;
if (tc.HasControls())
{
foreach (Control c in tc.Controls)
{
if (c.GetType() == typeof(LinkButton))
{
LinkButton lb = c as LinkButton;
cellText = lb.Text;
}
else if (c.GetType() == typeof(HyperLink))
{
HyperLink h1 = c as HyperLink;
cellText = h1.Text;
}
}
}
else
{
cellText = tc.Text;
}
return cellText;
}

Process the export request

public void exporttoExcel(GridView grv)
{
StringBuilder sb = new StringBuilder();
GridViewRow grHeader = grv.HeaderRow;
int counter = 0;

foreach (TableCell tc in grHeader.Cells)
{
sb.Append(“\”” + grv.Columns[counter].HeaderText + “\”,”);
counter++;
}
sb.AppendLine();

foreach (GridViewRow gr in grv.Rows)
{
foreach (TableCell tc in gr.Cells)
{
sb.Append(“\”” + getGridCellText(tc) + “\”,”);
}
sb.AppendLine();
}

Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.AddHeader(“content-disposition”, “attachment; filename=Export.csv”);
Response.ContentType = “text/csv”;
Response.AddHeader(“Pragma”, “public”);
Response.Write(sb.ToString());
Response.End();
}

Button click event

public void export(object sender, EventArgs e)
{
exporttoExcel();
}

You now have the code to do your export and it should all work, however something went wrong! It only works once, and everything else on the page seems to be disabled.

Apparantly, SharePoint updates some kind of timestamp hash on the form before it is actually submitted to the server. This is done in order to prevent the form from being submit more than once if the user clicks before the Postback is completed, which is a good thing – except when trying to do what we are trying to do here. To get past this you will need to also add the following JavaScript to the onClientClick event for your button:

function postExport() {

window.WebForm_OnSubmit = function ()
{ return true; };
}

OnClientClick=”postExport()”

Read More