Thursday, 17 May 2012

Problem Sorting With Multiple SPGridViews

I have experienced a funny behavior by having two SPGridviews along with ObjectDataSource on the same page. Both the SPGirdViews are enabled with sorting, filtering and pagination. Filtering and Pagination worked perfectly without any issues. If it comes to sorting point of view, whenever you try to sort the lower SPGridView it gets applied to upper SPGridView.

The Hack for this issue:
              protected override void OnPreRender(EventArgs e)
        {           
            if (SPGridView1.HeaderRow != null)
            {
                foreach (WebControl control in this.SPGridView1.HeaderRow.Controls)
                {
                    UpdateTemplateClientID(control, SPGridView1.ClientID);
                }
            }
            if (SPGridView2.HeaderRow != null)
            {
                foreach (WebControl control in this.SPGridView2.HeaderRow.Controls)
                {
                    UpdateTemplateClientID(control, SPGridView2.ClientID);
                }
            }
            base.OnPreRender(e);
        }

        private void UpdateTemplateClientID(Control control, string clientID)
        {
            if (control is Microsoft.SharePoint.WebControls.Menu)
            {
                Microsoft.SharePoint.WebControls.Menu menuControl = control as Microsoft.SharePoint.WebControls.Menu;
                string jsFunctionCall = menuControl.ClientOnClickPreMenuOpen;
                menuControl.ClientOnClickPreMenuOpen = jsFunctionCall.Replace("%TEMPLATECLIENTID%", clientID + "_SPGridViewFilterMenuTemplate");
            }
            else if (control.HasControls())
            {
                foreach (WebControl c in control.Controls)
                {
                    UpdateTemplateClientID(c, clientID);
                }
            }
        }

Tuesday, 15 May 2012

Sample Examples of ShowModalDialog

For showing the div:
<script type="text/javascript">
function showDialog() {
var _html = document.createElement('div');
_html.innerHTML = document.getElementById('WfHistory').innerHTML;
var _options = { html: _html , title: "View History",
allowMaximize: false,
showClose: true,
autoSize: true};
SP.UI.ModalDialog.showModalDialog(_options);}
</script>
<asp:LinkButton id="hlViewHistory" runat="server" OnClientClick="showDialog();return false;" Text="Show Full History" />
<div id="WfHistory" style="display:none" >
....
</div>

For showing the aspx page:
<script type="text/javascript">
function showDialog() {
var list = document.getElementById("<%= hdnParamList.ClientID %>").value;
var _options = { title: "View History",
allowMaximize: false,
showClose: true,
autoSize: true,
url: "ViewHistory.aspx?List=" + list };
SP.UI.ModalDialog.showModalDialog(_options);}
</script>
<asp:LinkButton id="lbViewHistory" runat="server" OnClientClick="showDialog();return false;" Text="Show Full History" />script>div id="WfHistory" style="display:none" >

Close Popup inside CodeBehind:
StringBuilder sbScript1 = new StringBuilder();
sbScript1.Append("<script language='javascript'>");
sbScript1.Append("window.frameElement.commitPopup();<");
sbScript1.Append("/script>");
ScriptManager.RegisterClientScriptBlock(this.Page, this.Page.GetType(), "closepopup", sbScript1.ToString(), false);

Thursday, 3 May 2012

Reusable Code Snippet to disable EventFiring

For disabling the events inside the extended class of SPItemEventReceiver  then we will have a property named EventFiringEnabled. But if our class doesn’t extend SPItemEventReceiver  then we can use the object of below class.

public class SPItemEventReceiverHandling : SPItemEventReceiver, IDisposable
    {
        public SPItemEventReceiverHandling(bool disableImmediately)
        {
            EventFiringEnabled = !disableImmediately;
        }       

        public void Dispose()
        {
            EventFiringEnabled = true;
        }
    }

Example: item represents SPListItem

using (var eventReceiverManager = new SPItemEventReceiverHandling(true))
{
     item.Update();
}

Note:
If the version of MOSS is 2007 then use EnableEventFiring and DisableEventFiring methods instead of EventFiringEnabled property.

Monday, 30 April 2012

JavaScript error using date picker inside an update panel?

Just include the datepicker.js file explicitly on the page
 <script type="text/javascript" src="/_layouts/datepicker.js"></script>

Wednesday, 28 March 2012

Upload Files into sharepoint library using FileUpload control

string documentlibraryname = ConfigurationManager.AppSettings["DocumentLibraryName"];
string folderpath = ConfigurationManager.AppSettings["TempFolderLocation"];

try
{
HttpFileCollection hfc = Request.Files;

for (int i = 0; i < hfc.Count; i++)
{
HttpPostedFile hpf = hfc[i];
if (hpf.ContentLength > 0)
{
//folderpath +
//Get proper file name
string strFileName = hpf.FileName;
strFileName = Path.GetFileName(strFileName);

string TempFileName = folderpath + strFileName;
hpf.SaveAs(TempFileName);
String fileToUpload = TempFileName;
String sharePointSite = SPContext.Current.Web.Url;
using (SPSite oSite = new SPSite(sharePointSite))
{
using (SPWeb oWeb = oSite.OpenWeb())
{
oWeb.AllowUnsafeUpdates = true;
if (!System.IO.File.Exists(fileToUpload))
throw new FileNotFoundException("File not found.", fileToUpload);
string[] folders = folderName.Split(';');
String url = oWeb.Lists[documentlibraryname].RootFolder.ServerRelativeUrl.ToString();
foreach (string subFolder in folders)
{
url += "/" + subFolder.Trim();
}
Boolean replaceExistingFiles = true;
String fileName = System.IO.Path.GetFileName(fileToUpload);
FileStream fileStream = File.OpenRead(fileToUpload);
SPFile spfile = oWeb.GetFolder(url).Files.Add(fileName, fileStream, replaceExistingFiles);
spfile.Item["Name"] = fileName;
spfile.Item["Created By"] = SPContext.Current.Web.CurrentUser;
spfile.Item["Modified By"] = SPContext.Current.Web.CurrentUser;
spfile.Item.Update();
fileStream.Flush();
fileStream.Close();
fileStream.Dispose();
oWeb.AllowUnsafeUpdates = false;
}
}
}
}
}

catch (Exception ex)
{
lblMessage.Text = ex.ToString();
}
HttpFileCollection hfc1 = Request.Files;
if(hfc1.Count==0)
lblMessage.Text = "Please select at least one file to upload";

Download Files from Web[c#]

Download Files from Web [C#]

This example shows how to download files from any website to local disk. The simply way how to download file is to use WebClient class and its method DownloadFile. This method has two parameters, first is the url of the file you want to download and the second parameter is path to local disk to which you want to save the file.

Download File Synchronously

The following code shows how to download file synchronously. This method blocks the main thread until the file is downloaded or an error occur (in this case the WebException is thrown).
[C#]
using System.Net;

WebClient webClient = new WebClient();
webClient.DownloadFile("http://mysite.com/myfile.txt", @"c:\myfile.txt");

Download File Asynchronously

To download file without blocking the main thread use asynchronous method DownloadFileA­sync. You can also set event handlers to show progress and to detect that the file is downloaded.
[C#]
private void btnDownload_Click(object sender, EventArgs e)
{
  WebClient webClient = new WebClient();
  webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
  webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
  webClient.DownloadFileAsync(new Uri("http://mysite.com/myfile.txt"), @"c:\myfile.txt");
}

private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
  progressBar.Value = e.ProgressPercentage;
}

private void Completed(object sender, AsyncCompletedEventArgs e)
{
  MessageBox.Show("Download completed!");
}

Note: Although you use asynchronous method, it can block the main thread for a while. It's because before the async download itself, it checks the DNS name (in this case „mysite.com“) and this check is done internally by blocking function. If you use directly IP instead of domain name, the DownloadFileAsync method will be fully asynchronous.

Wednesday, 1 June 2011

Adding New Discussion and replying to the Discussion Item using Object Model

New Discussion:
SPListItem oListItem =SPUtility.CreateNewDiscussion(oList.Items, TitleField.Text);
oListItem[SPBuiltInFieldId.Body] = MessageBox.Text;
         oListItem.Update();
 Discussion reply:
SPListItem parent = list.GetItemById(parentId);
         SPListItem reply = SPUtility.CreateNewDiscussionReply(parent);
reply[SPBuiltInFieldId.Body] = body;
                  reply.Update();