Wednesday 5 September 2012

Writing/Reading XML

Writing to XML
            XmlTextWriter writer = new XmlTextWriter("C:/TEMP/product.xml", System.Text.Encoding.UTF8);
            writer.WriteStartDocument(true);
            writer.Formatting = Formatting.Indented;
            writer.Indentation = 2;
            writer.WriteStartElement("Properties");
            createNode("model", "modelS", writer);
            createNode("supplier", "x", writer);
            writer.WriteEndElement();
            writer.WriteEndDocument();
            writer.Close();
Helper Method
private static void createNode(string key, string value, XmlTextWriter writer)
        {
            writer.WriteStartElement(key);
            writer.WriteString(value);
            writer.WriteEndElement();
        }
Reading XML
XmlDataDocument xmldoc = new XmlDataDocument();
            XmlNodeList xmlnode;
            int i = 0;
            string str = null;
            FileStream fs = new FileStream("C:/TEMP/product.xml", FileMode.Open, FileAccess.Read);
            xmldoc.Load(fs);
            xmlnode = xmldoc.GetElementsByTagName("Properties")[0].ChildNodes;
            for (i = 0; i <= xmlnode.Count - 1; i++)
            {
                str = xmlnode[i].Name +" | "+xmlnode[i].ChildNodes.Item(0).InnerText.Trim();
                Console.WriteLine(str);
            }
XML Pattern

Monday 30 July 2012

Workaround: Calling a JavaScript Function from a HyperLinkField in a GridView or SPGridView

If you place a HyperLinkField in a GridView and link it to a JavaScript function, then it doesn't work properly. The problem is that the URL specified by the HyperLinkField'sNavigateUrl fails to render when you use a JavaScript reference (such as "Javascript:func();") rather than a standard URL.


As a workaround, we can use the RowDataBoundEvent to prepare a proper call to the JavaScript function. To make this work, while assigning the value we should give "Javascript." (with a period) instead of"Javascript:" (with a colon)


void grid_RowDataBound(object sender, GridViewRowEventArgs e)
{
//if it is not DataRow return.
if (e.Row.RowType != DataControlRowType.DataRow)
{
return;
}
//Loop thru the cells changing the "." to ":" in hyperlink navigate URLs
for (int i = 0; i < e.Row.Cells.Count; i++)
{
TableCell td = e.Row.Cells[i];
if (td.Controls.Count > 0 && td.Controls[0] is HyperLink)
{
HyperLink hyperLink = td.Controls[0] as HyperLink;
string navigateUrl = hyperLink.NavigateUrl.ToLower();
hyperLink.NavigateUrl = hyperLink.NavigateUrl.Replace(
hyperLink.NavigateUrl.Substring(
navigateUrl.IndexOf("javascript."), "javascript.".Length),
"javascript:");
}
}
}

Wednesday 4 July 2012

Get/Set Values for Managed MetaData Field

Get Terms from the Field:
TaxonomyField commodityGrpFld = (TaxonomyField)web.Fields[“FieldName”];
       // get the Term Store ID from the field
       Guid commodityGrptermStoreId = commodityGrpFld.SspId;
       // Open a taxonomysession and get the correct termstore
       TaxonomySession session = new TaxonomySession(oSite);
       TermStore termStore = session.TermStores[commodityGrptermStoreId];               
       #region get terms from commodity termset
       try
       {
           TermSet termSetCommodity = termStore.GetTermSet(commodityGrpFld.TermSetId);                   
           if (termSetCommodity != null)
           {
               TermCollection CommodityTermColl = termSetCommodity.Terms;
               ArrayList commodityList = new ArrayList();
               foreach (Term commTerm in CommodityTermColl)
               {
                   commodityList.Add(commTerm.Name);
               }
//binding to listbox
               lbCommodityGrp.DataSource = commodityList;
               lbCommodityGrp.DataBind();
            }
        }
        catch (Exception)
        { }
        #endregion
Update the Item value for Managed Metadata field:
TaxonomyField taxoField_Commodity =spfile.Item.Fields[[“FieldName”] as TaxonomyField;
        TaxonomySession taxoSession = new TaxonomySession(oSite);
        TermStore store = taxoSession.TermStores[taxoField_Commodity.SspId];
        TermSet termSet = store.GetTermSet(taxoField_Commodity.TermSetId);
        if (taxoField_Commodity.AllowMultipleValues)
        {                                           
          TermCollection terms = termSet.GetAllTerms();
          List<string> taxonomyValueList = new List<string>();
          foreach (ListItem item in lbCommodityGrp.Items)
          {
            if (item.Selected)
            {
              taxonomyValueList.Add(item.Value);
            }
          }
          TaxonomyFieldValueCollection fieldValues = new TaxonomyFieldValueCollection(taxoField_Commodity);
          foreach (Term term in terms)
          {
             if (taxonomyValueList.Contains(term.Name))
             {
                TaxonomyFieldValue fieldValue = new TaxonomyFieldValue(taxoField_Commodity);
                fieldValue.TermGuid = term.Id.ToString();
                fieldValue.Label = term.Name;
                fieldValues.Add(fieldValue);
             }
          }
          taxoField_Commodity.SetFieldValue(spfile.Item, fieldValues);
       }
Get the Item value for Managed Metadata field:
                We need to convert the item value to TaxonomyFieldValueCollection

Monday 2 July 2012

Using SharePoint 2010 Content Organizer to Route Documents

This video walks through the process of uploading, saving, and routing documents based on content type metadata values by levereging Microsoft SharePoint Server 2010 Content Organizer feature.

http://sharepointquester.com/2012/03/06/how-to-route-documents-based-on-metadata-using-the-content-organizer-feature/

Programmatically Create a ‘Send To’ Connection to Send Documents to The Records Center in SharePoint 2010

If you have multiple send to connections to create or prefer to automate the deployment tasks related to your SharePoint environment, the following bit of code will help you create them automatically using the SPOfficialFileHost collection of your current site’s web application:

using (SPSite site = new SPSite(http://sp/))
{
    SPWebApplication webapp = site.WebApplication;
    SPOfficialFileHost newhost = new SPOfficialFileHost(true);
    newhost.OfficialFileUrl = new Uri(site.Url+"/records/_vti_bin/officialfile.asmx");
    newhost.OfficialFileName = "Records Center";
    newhost.ShowOnSendToMenu = true;
    newhost.Action = SPOfficialFileAction.Move;
    webapp.OfficialFileHosts.Add(newhost); 
    webapp.Update();
}


The options for the action are the following:
1.       You can move the document from one location to another
SPOfficialFileAction.Move;
2.       You can create a copy of the document and send it to another location
SPOfficialFileAction.Copy;
3.       Or you can move the document but leave a link of its new location in its former location
SPOfficialFileAction.Link;


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.