Skip to main content

Posts

Showing posts from 2013

Create a mailto htm with no character limit.

The HTML standard for the mailto link is 256 characters. You can get around this by loading the JavaScript redirect instead. var  body = escape(window.document.title + String.fromCharCode(13) + window.location.href + " actully  a Your long text here..." ); body = body.replace( /\//g ,  "%2F" ); body = body.replace( /\?/g ,  "%3F" ); body = body.replace( /=/g ,  "%3D" ); body = body.replace( /&/g ,  "%26" ); body = body.replace( /@/g ,  "%40" ); var  subject =  "Take a look at this!" ; window.location.href =  "mailto:?body="  + body +  "&subject="  + subject;

Get Sum of Columns in a SharePoint list (Threshold edition)

It is a known fact that once the treshold limit is reached in SP, everything seems frozen.  At this point you have some options. Increase the limit using powershell or from the Central Admin OR Index the columns that you will like to operate on and create views based on those. However programmatically if you want to sum a list that has reached its threshold.  You can do so in batches as hown below:          protected   void  GetSummary( out   long  ideas,  out   long  votes,  out   long  comments,  out   long  transform)         {              long  ideasum = 0;              long columntoSum = 0;              long  commentS...

Get the latest ID from a SharePoint list

  public   int MaximumID()         {              SPQuery  query =  new   SPQuery ();             query.Query =  " " ;             query.RowLimit = 1;              SPListItemCollection  items =  SPContext .Current.Site.RootWeb.Lists[ "ListName" ].GetItems(query);              int  maxId =  Convert .ToInt32(items[0][ "ID" ]);              return  maxId;         }

Create a jQuery alert programmatically

From the code behind:   Assuming you have jquery on your page already.   StringBuilder  strScriptFeatured =  new   StringBuilder (); strScriptFeatured.Append( "$(document).ready(function(){" ); strScriptFeatured.Append( "alert('Your alert here!');" ); strScriptFeatured.Append( "});" ); Page.ClientScript.RegisterStartupScript( this .GetType(),  "Script" , strScriptFeatured.ToString(),  true );   QED  

Create a random item in a list

To create a random item in a SharePoint list:     private   static   SPListItem  GetRandomItem( SPListItemCollection  list) { var  theIDs =  new   List < int >(); foreach  ( SPListItem  item  in  list) { theIDs.Add(item.ID); } theIDs.Shuffle(); Int32 val = theIDs.FirstOrDefault(); SPListItem  randomItem = list.GetItemById(val); return  randomItem; }   The randomization is done here:           public   static   void  Shuffle ( this   IList  list)         {              var  randomNumber =  new   Random (DateTime.Now.Millisecond);              var  n = list.Count;   ...

Remove chrome on a web part

The web part properties are many and one of the OOB property is the chrome that displays the title.  To remove the chrome programmatically. You can on instantiation or page load do this. this .ChromeType =  PartChromeType .None;    QED

Page Redirect in a sandbox

To redirect in a SharePoint sandbox is a nightmare. But don't panic, there is a way out. Create a literal control in your html as shown below:   < asp : Literal   ID = "litRedirect"   runat = "server"   /> and  in the codebehind do this:   litRedirect.Text =    string .Format( " " ,  string .Format( "{0}?k={1}" , thesearchresult, txtSearch.Value.Trim()));

Set Search Text Box Default

Ways to set search text box default is given below:   txtSearch.Value  =  "Search keywords" ;   txtSearch.Attributes.Add( "onfocus" ,  "if (this.value == 'Search keywords') this.value = '';" );   txtSearch.Attributes.Add( "onBlur" ,  "if (this.value == '') this.value = 'Search keywords';" );   this .Page.Form.DefaultButton = imgSearch.UniqueID;   Alternatively, you could wrap a panel control around your tags and set the default control on  that Panel.     < asp : Panel   ID = "pnlsearch"   runat = "server"   DefaultButton = "imgSearch" >                      < div   id = "search-drop" >                   ...

Elapsed Time Generator

     public   class   ElapsedTimeGenerator     {          public   string  Generate(DateTime dateTime)         {             TimeSpan elapsedTime = DateTime.Now.Subtract(dateTime);              if  (elapsedTime.Days > 730)             {                  double  years = elapsedTime.Days / 365;                  return   String .Format( "More than {0} years ago" ,  Math .Floor(years).ToString());      ...

ADD VOICE

You can add speech capabilities to your site easily by following this simple process: 1. Add reference to a COM dll called Microsoft Speech Object Library(Interop.SpeechLib.dll). 2. Add a textbox to your web project where you can place the content to be converted to speech. 3. In your codebehind, declare the namespace - using SpeechLib; 4. Add a button that will handle the speech process as given below: protected void btnVoice_Click(object sender, EventArgs e) { SpVoice voice = new SpVoice(); try { voice.Speak(spText.Text, SpeechVoiceSpeakFlags.SVSFDefault); } catch (Exception ex) { throw ex; } } 4. That is it! Remember to switch your speaker on and give it some volume.

Determine if a file is valid based on a default list

public static bool GetValidFile(FileUpload fu) { bool result = false; try { List fileType = new List (); fileType.Add("DOC"); fileType.Add("TXT"); fileType.Add("XLS"); fileType.Add("PPT"); fileType.Add("PDF"); fileType.Add("DOCX"); fileType.Add("WMV"); fileType.Add("XLSX"); fileType.Add("PPTX"); fileType.Add("WMA"); fileType.Add("MP4"); fileType.Add("3GP"); fileType.Add("M4A"); fileType.Add("MP4V"); fileType.Add("M4P"); fileType.Add("M4B"); fileType.Add("3GPP"); fileType.Add("3GP2"); fileType.Add("MOV"); fileType.Add("RTF"); fileType.Add("CSV"); fileType.Add("RTF"); if (fu.HasFile) { string fileExt; fileExt = fu.FileName.Substring(fu.FileName.LastIndexOf('.') + 1).ToUpper(); if (fileType.Contains(fileExt)) { result = true; } ...

Loop through selected nodes of a treeview control

foreach (TreeNode node in tvBusinessUnit.CheckedNodes) { lblSelectedBusinessUnit.Visible = true; if (tvBusinessUnit.CheckedNodes.Count > 1) { lblSelectedBusinessUnit.InnerText += string.Format(" {0}, ", node.Text); } else { lblSelectedBusinessUnit.InnerText = string.Format(" {0}", node.Text); } if (node.Depth == 2) { string nodeVal = node.Text; numselect = numselect + 1; } }

Send Email

SmtpClient SmtpMail = new SmtpClient(); MailMessage MessageMail = new MailMessage(mailFrom, mailTo); MessageMail.Subject = subject; MessageMail.IsBodyHtml = true; MessageMail.BodyEncoding = System.Text.Encoding.UTF8; MessageMail.Body = content; SmtpMail.Send(MessageMail);

Determine a valid image

public static bool GetValidUImage(FileUpload fuImage) { bool result = false; try { Dictionary imageHeader = new Dictonary (); imageHeader.Add("JPG", new byte[] { 0xFF, 0xD8, 0xFF, 0xE0 }); imageHeader.Add("JPEG", new byte[] { 0xFF, 0xD8, 0xFF, 0xE0 }); imageHeader.Add("PNG", new byte[] { 0x89, 0x50, 0x4E, 0x47 }); imageHeader.Add("TIF", new byte[] { 0x49, 0x49, 0x2A, 0x00 }); imageHeader.Add("TIFF", new byte[] { 0x49, 0x49, 0x2A, 0x00 }); imageHeader.Add("GIF", new byte[] { 0x47, 0x49, 0x46, 0x38 }); imageHeader.Add("BMP", new byte[] { 0x42, 0x4D }); imageHeader.Add("ICO", new byte[] { 0x00, 0x00, 0x01, 0x00 }); byte[] header; if (fuImage.HasFile) { string fileExt; fileExt = fuImage.FileName.Substring(fuImage.FileName.LastIndexOf('.') + 1).ToUpper(); byte[] tmp = imageHeader[fileExt]; header = new byte[tmp.Length]; fuImage.FileContent.Read(header, 0, header.Length); if (Compar...

Get Image Url from Picture Library Item

public string GetDummyImageUrl(object theItem, string pictureLibrary) { StringBuilder url = new StringBuilder(); SPWeb web = SPContext.Current.Site.RootWeb; DummyIdeaPictures = string.IsNullOrEmpty(DummyIdeaPictures) ? "DummyIdeaPictures" : DummyIdeaPictures; SPListItem listItem = web.Lists[DummyIdeaPictures].GetItemById(Convert.ToInt32(theItem)); url.Append(SPEncode.UrlEncodeAsUrl(listItem.Web.Url)); url.Append('/'); url.Append(SPEncode.UrlEncodeAsUrl(listItem.ParentList.RootFolder.Url)); url.Append('/'); string filename = listItem.File.Name; ImageSize imageSize = ImageSize.Full; if (imageSize == ImageSize.Full) { url.Append(SPEncode.UrlEncodeAsUrl(filename)); } else { string basefilename = Path.GetFileNameWithoutExtension(filename); string extension = Path.GetExtension(filename); string dir = (imageSize == ImageSize.Thumbnail) ? "_t/" : "_w/"; url.Append(dir); url.Append(SPEncode.UrlEncodeAsUrl(basefilename)); url.A...

Add single/double click to gridview

protected void grdClickDoubleClick_RowDataBound(object sender, GridViewRowEventArgs e) { try { GridViewRow row = e.Row; if (row.RowType == DataControlRowType.DataRow) { ImageButton _singleClickButton = row.FindControl("lnkBtnClk") as ImageButton; string _jsSingleClick = Page.ClientScript.GetPostBackClientHyperlink(_singleClickButton, ""); e.Row.Attributes.Add("onclick", _jsSingleClick); ImageButton _dblClickButton = row.FindControl("lnkBtnClk") as ImageButton; string _jsDoubleClick = Page.ClientScript.GetPostBackClientHyperlink(_dblClickButton, ""); e.Row.Attributes.Add("ondblclick", _jsDoubleClick); } } catch (Exception ex) { } }

Add Client Script to codebehind c# ASP.NET

To register a js file in the codebehind - just use the "ClientScript.RegisterClientScriptInclude" Page.ClientScript.RegisterClientScriptInclude("blockui", string.Format("{0}/{1}", SPContext.Current.Site.RootWeb.Url.ToString(), "Style%20Library/PitchIn/Scripts/jquery.blockUI.js")); To add script tags, then build the string and pass the value: string loadingimage = @" "; Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "loadingimg", loadingimage, false);

Combine complex CAML queries

SPSite site = SPContext.Current.Site; SPWeb oWebsiteRoot = site.RootWeb; SPQuery query = new SPQuery(); List conditions = new List (); foreach (string word in filterval) { conditions.Add(string.Format(" {0} ", word)); } string merged = MergeCAMLConditions(conditions, MergeType.Or); .............................................................   private static string MergeCAMLConditions(List conditions, MergeType type) { try { if (conditions.Count == 0) return ""; string typeStart = (type == MergeType.And ? " " : " "); string typeEnd = (type == MergeType.And ? " " : ""); // Build hierarchical structure while (conditions.Count >= 2) { List complexConditions = new List (); for (int i = 0; i < conditions.Count; i += 2) { if (conditions.Count == i + 1) // Only one condition left complexConditions.Add(conditions[i]); else // Two condotions - merge complexConditions.Add(typeStart + conditions...

Loop through List Item attachments

Int32 itemID = Convert.ToInt32(item["ID"]); SPListItem theItem = site.RootWeb.Lists[ListName].GetItemById(itemID); if (null != theItem.Attachments) { if (theItem.Attachments.Count > 0) { foreach (string fileName in theItem.Attachments) { SPFile file = SPContext.Current.Site.RootWeb.GetFile(theItem.Attachments.UrlPrefix + fileName); if (theItem.Attachments.Count > 1) { sb.AppendFormat(" {1} , ", string.Format("{0}", SPUtility.ConcatUrls(SPContext.Current.Site.RootWeb.Url, file.Url)), file.Name); } else { sb.AppendFormat(" {1} ", string.Format("{0}", SPUtility.ConcatUrls(SPContext.Current.Site.RootWeb.Url, file.Url)), file.Name); lblAttachments.Text = string.Format("Attachment: {0}", sb.ToString().Trim()); } } if (theItem.Attachments.Count > 1) { lblAttachments.Text = string.Format("Attachments: {0}", sb.ToString() .TrimEnd( ' ' ).TrimEnd( ',' )); } } }

Which of these is yours?

I saw this on a site and it was interesting to me. To which of these collection do you belong? A compilation of programmers A unit of testers A click of QA engineers A spec of program managers A package of builders A deployment of SysOps -or- A distribution of SysOps A bundle of network engineers A row of DBAs An interface of UX designers A lab of usability testers A snarl of IT admins A triage of Helpdesk engineers A pixel of graphic artists -or- A sketch of graphic artists A meeting of managers A retreat of general managers A scribble of writers -or- A sheaf of writers A revue of editors (haha) -or- A scrabble of editors A project of interns An oversight of auditors A tweet of tech evangelists A quarrel of patent lawyers

Sandbox ImageValueField Publishing

SPListItem theitem = SPContext .Current.Site.RootWeb.Lists[ "listname" ].GetItemById(1); string theImg = theitem .GetFormattedValue("ChallengeImage"); string theImgUrl =""; if(!string.IsNullOrEmpty(theImg)) {       theImgUrl  = XElement.Parse(ImgTag + "").Attribute("src").Value; }

Microsoft.Web.Infrastructure fix

Just as a reminder. To fix an error similar to this Could not load file or assembly 'Microsoft.Web.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified. Try the solution below: Run the following command in the Package Manager Console. From Visual Studio - Open  Tools > Library Package Manager > Package Manager Console     PM> Install-Package Microsoft.Web.Infrastructure     You will see the following messages if it is successfully installed.     Successfully installed 'Microsoft.Web.Infrastructure 1.0.0.0'.     Successfully added 'Microsoft.Web.Infrastructure 1.0.0.0' to Web.  This should add the Microsoft.Web.Infrastructure.dll has now been added as a reference.