Tuesday 25 September 2012

JQuery To get textbox value through title


<script type="text/javascript" src="../../Scripts/jquery-1.7.2.min.js" ></script>
<script type="text/javascript"  >
        $(document).ready(function() {
       
            if($('input[title="FieldName"]').val()=="abcd")
            {
                     $('input[title="Client Name"]').val('');  
            }
           
     });

    </script>

Friday 21 September 2012

Security Trimmed Controls in SharePoint


Let’s say you have a control on your page that you want only a certain group of users to see. Fortunately, SharePoint has a built-in control that lets you hide controls to which users do not have the necessary permissions.  This control is the SPSecurityTrimmedControl.
<Sharepoint:SPSecurityTrimmedControl runat=”server” Permissions=”ManageLists”>
Place your control(s) here</SharePoint:SPSecurityTrimmedControl>
All you have to do is wrap your control with this security control and set the correct permissions in the Permissions attribute. The Permissions attribute, when used in Visual Studio or Designer, will have intellisense and will be filled with the following properties obtained fromhttp://msdn2.microsoft.com/en-us/library/microsoft.sharepoint.spbasepermissions.aspx.  Whatever permissions you specify will be required by the user in order to view the control(s) inside of the SPSecurityTrimmedControl:
AddAndCustomizePages
AddDelPrivateWebParts
AddListItems
ApplyStyleSheets
ApplyThemeAndBorder
ApproveItems
BrowseDirectories
BrowseUserInfo
CancelCheckout
CreateAlerts
CreateGroups
CreateSSCSite
DeleteListItems
DeleteVersions
EditListItems
EditMyUserInfo
EmptyMask
EnumeratePermissions
FullMask
ManageAlerts
ManageLists
ManagePermissions
ManagePersonalViews
ManageSubwebs
ManageWeb
Open
OpenItems
UpdatePersonalWebParts
UseClientIntegration
UseRemoteAPIs
ViewFormPages
ViewListItems
ViewPages
ViewUsageData
ViewVersions
** You can also use the PermissionsString property to use a comma seperated list.

Get query string in a Sharepoint 2010 page through SP Services




<script src="../../JQuery/jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="../../JQuery/jquery.SPServices-0.5.4.js" type="text/javascript"></script>




<script type="text/javascript">
$(document).ready(function(){

    var queryStringValues = $().SPServices.SPGetQueryString();
    var id = queryStringValues["ID"];
    var source= queryStringValues["Source"];
    alert(id);
    alert(source);
});


</script>

Thursday 20 September 2012

SharePoint Data View Conditional Formatting based on user permissions


SharePoint Data View Conditional Formatting based on user permissions (IfHasRights)

19OCT

Below are the values for conditional formatting
example usage : <xsl:if test=”ddwrt:IfHasRights(“REPLACE THIS WITH BELOW VALUE”)”><img alt=”" border=”0″ src=”../../PublishingImages/btn_AddActionItem.jpg” width=”191″ height=”37″ /></xsl:if>
ViewListItems – 1
AddListItems – 2
EditListItems – 4
DeleteListItems – 8
ApproveItems – 16
OpenItems – 32
ViewVersions – 64
DeleteVersions – 128
CancelCheckout – 256
PersonalViews – 512
ManageLists – 2048
ViewFormPages – 4096
Open – 65536
ViewPages – 131072
AddAndCustomizePages – 262144
ApplyThemeAndBorder – 524288
ApplyStyleSheets – 1048576
ViewUsageData – 2097152
CreateSSCSite – 4194314
ManageSubwebs – 8388608
CreateGroups – 16777216
ManagePermissions – 33554432
BrowseDirectories – 67108864
BrowseUserInfo – 134217728
AddDelPrivateWebParts – 268435456
UpdatePersonalWebParts – 536870912
ManageWeb – 1073741824
UseRemoteAPIs – 137438953472
ManageAlerts – 274877906944
CreateAlerts – 549755813888
EditMyUserInfo – 1099511627776
EnumeratePermissions – 4611686018427387904
FullMask – 9223372036854775807
To ensure that users only see the edit button if they are the author of the posting, or a site owner we added the following conditional formatting:
test=”ddwrt:IfHasRights(2048) or contains(@Author,$Userid)”


Reffered from   Here

Cascading dropdown upto 3 level in Sharepoint 2010


To make the example shown at the top of the page for Country -> Region -> State work, here's what you need to do.
The end result will look like this:



You'll need these three relationship lists:
Countries List The Countries list simply contains all of the country names, stored in the list's Title column.
Regions List The Regions list contains all of the Region names in the Title column. The Country column is a Lookup column into the Countries list's Title column.
 
States List The States list contains all of the State names in the Title column. Note that I've changed the DisplayName of the Title column to State, but the StaticName is still Title. The Region Name column is a Lookup column into the Regions list's Title column. (The State Abbreviation column is only here to show that you can also store additional information about the States in this list. The same is true of the Countries and Regions lists, of course.)
This is the sum total of what you'll need to add to your page to make the function work for the example above. The first two lines simply pull the script files into the page, and the $(document).ready(function() line is a jQuery function that says "Run this script when the page has been fully rendered". In the first call to the function, note that we're turning debug mode on by setting debug: true.
<script language="javascript" type="text/javascript" src="../../jQuery%20Libraries/jquery-1.4.2.js"></script>
<script language="javascript" type="text/javascript" src="../../jQuery%20Libraries/jquery.SPServices-0.5.7.min.js"></script>
NB:Add the  particular version of jquery and spservices otherwise it will not work
<script language="javascript" type="text/javascript">
 $(document).ready(function() {
  $().SPServices.SPCascadeDropdowns({
   relationshipList: "Regions",
   relationshipListParentColumn: "Country",
   relationshipListChildColumn: "Title",
   parentColumn: "Country",
   childColumn: "Region",
   debug: true
  });
  $().SPServices.SPCascadeDropdowns({
   relationshipList: "States",
   relationshipListParentColumn: "Region_x0020_Name",
   relationshipListChildColumn: "Title",
   relationshipListSortColumn: "ID",
   parentColumn: "Region",
   childColumn: "State"
  });
 });
</script>

To add Caml query to filter
CAMLQuery: "<Eq><FieldRef Name='Status'/><Value Type='Text'>Active</Value></Eq>"
To Show the default text Find "Prompttext"  and add  "Choose {0}...",
Ex-Choose Country, Choose State Like this
Reffered From Here




Custom Master Page changes to Add banner in sharepoint

If there is a need to add custom banner in sharepoint 2010 master pages there should be some CSS work

To Hide the Inner contents like the default logo and default page breadcrum

.s4-title-inner
 {display:none !important;

}
To hide the warning message coming after the page edit,
#s4-statusbarcontainer
{display:none !important;
}
To add the banner and the some css changes for the Menu item  in Sharepoint 2010 publishing sites
.s4-title
{
min-height:28px !important;
}
#s4-topheader2
{
background:url('../Image/image.jpg') repeat scroll 0 0 transparent !important ;
}
#s4-tophd2
{

 background:url('../Image/nav-gold-rule.jpg') repeat scroll 0 0 transparent !important ;
/* ../Image/nav-gold-rule.jpg added path  from style library */
}
 .s4-tn li.static > .menu-item
{
padding-top:10px !important;
background:none !important;
color:#669999 !important;
border:none !important;
}
.s4-tn li.static > a:hover
{
background:white !important;
border-color:black !important;
border:thin !important;
color:red !important;
}
.s4-tn li.dynamic > a:visited
{
 color:#666666 !important;
 border-color:black !important;
}


#s4-searcharea
{
padding-top:5px !important;
}

.s4-title {


    background:#F9F9F9 url('../Image/banner.jpg') repeat-x 0px 0px  !important;
 /* ../Image/banner.jpg added path  from style library */

    margin:0 !important;


    min-height:71px !important;


    overflow-x:hidden !important;


    padding:30px 0 0 310px !important;


    word-wrap:break-word !important;


}



Reffered from Here



Custom Breadcrum in sharepoint 2010


<div class="BreadCrumbWrap s4-notdlg">
<asp:SiteMapPath runat="server" SiteMapProvider="SPContentMapProvider" id="ContentMap" CssClass="BreadCrumbStyle" PathSeparator="&gt;">
<CurrentNodeStyle CssClass="BreadCurrentNode" />
<PathSeparatorStyle CssClass="BreadPathSeparator" />
</asp:SiteMapPath>
</div>




/*For Bradcrum Changes*/
.BreadCrumbWrap {
margin-top:10px;
}
.BreadCrumbStyle {
padding-left:15px;
font-size:10px;border-bottom:1px #ebebeb dotted;
padding-bottom:5px;
}
.BreadCrumbStyle a:link, .BreadCrumbStyle a:visited {
color:#3b4f65;
}
.BreadCrumbStyle a:hover{
color:#0072bc; text-decoration:underline
}
.BreadCurrentNode {color:#0072bc}
.BreadPathSeparator{
color:#ccc; padding:0px 8px 0px 8px;
}



Export To PDF in sharepoint 2010/C#

I had an requirement to export some data to PDF format in Sharepoint application pages.

First You have to download and attach a DLL from ItextSharp.dll .(Can be downloaded from Here).Add it into  your webpart or solution  or for application pages.

For application pages and for inline coding add following  lines


<%@ Register TagPrefix="itext" Namespace="iTextSharp.text" Assembly="itextsharp, Version=5.3.0.0, Culture=neutral, PublicKeyToken=8354ae6d2174ddca" %>
<%@ Import Namespace="iTextSharp.text.pdf" %>
<%@ Import Namespace="iTextSharp.text.html.simpleparser" %>


For coding purpose add following lines


using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;


Then add the following  code to export to PDF


private DataTable  SearchItem()
    {
        DataTable dt = new DataTable();
        SPSecurity.RunWithElevatedPrivileges(delegate
        {
            SPList list = SPContext.Current.Web.Lists["TestList"];
         
       
            string query = null;
            SPQuery qry = new SPQuery(list.DefaultView);
            //SPListItemCollection lstColl =
            int iCnt = 0;
            try
            {

                qry.ViewFields = "<FieldRef Name='LinkTitleNoMenu' /><FieldRef Name='TestColumn' />";
                    qry.Query = query;
                 
                dt= list.GetItems(qry).GetDataTable();
                 

                 
                }

            catch (Exception ex) { Response.Write(ex.Message); }
        });
        return dt;
    }
    protected void btnExport_click(object sender, EventArgs e)
    {
        DataTable dt1 = SearchItem();
     

        //Get the data from database into datatable

        GridView GridView1 = new GridView();
        GridView1.AllowPaging = false;
        GridView1.DataSource = dt1;
        GridView1.DataBind();


        Response.ContentType = "application/pdf";
        Response.AddHeader("content-disposition",
          "attachment;filename=DataTable.pdf");
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);

        GridView1.RenderControl(hw);
        StringReader sr = new StringReader(sw.ToString());
        Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
        HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
        PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
        pdfDoc.Open();
        htmlparser.Parse(sr);
        pdfDoc.Close();
        Response.Write(pdfDoc);
        Response.End();
    }
 

  public override void VerifyRenderingInServerForm(Control control)
    {
    }


If you observe above code I added one function that is VerifyRenderingInServerForm this function is used to avoid the error like “control must be placed in inside of form tag”. If we setVerifyRenderingInServerForm function then compiler will think that controls rendered before exporting and our functionality will work perfectly.



After the button Click the PDf file will ask you to save or open the File.After that you can't do any post back options in that page.for doing such you have to add a little bit of code into that page within a script block.
Add the following code to that particular page



   <script type="text/javascript">

            _spOriginalFormAction = document.forms[0].action;

            _spSuppressFormOnSubmitWrapper = true;

</script>



Happy Coding  :)





Sunday 16 September 2012

Show Multiline Textbox value as Text



SPFieldMultiLineText field = (SPFieldMultiLineText)item.Fields["FieldName"];
 string text = field.GetFieldValueAsText(item["FieldName"]);

Thursday 13 September 2012

Convert Your Sharepoint Master Page to HTML 5

Full Blog -Here

The basics

  1. Simplify the DOCTYPE
    Before the DOCTYPE was:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    With HTML5 you only need:
    <!doctype html>
    Please note that using this DOCTYPE can cause issues with JavaScript in IE8. Use at your own risk.
  2. Removed xmlns from the HTML tag
    Before the HTML tag was:
    <html lang="" dir="" runat="server" xmlns:o="urn:schemas-microsoft-com:office:office" __expr-val-dir="ltr">
    We can omit xmlns because it is not required by HTML5 (it is required by XHTML). Our new HTML tag is:
    <html lang="" dir="" runat="server"  __expr-val-dir="ltr">
  3. Removed trailing slashes from self closing tags within the HEAD element that are not SharePoint controls
    That was a mouthful. HTML5 doesn’t require that you self close tags. You certainly can if you want to, it will still validate.  I took them out for the fun of it.  Here is an example of before:
    <meta http-equiv="Expires" content="0"/>
    And then after:
    <meta http-equiv="Expires" content="0">
  4. Changed X-UA-Compatible from IE8 to IE9
    IE8 doesn’t support HTML5 so we have to tell SharePoint to render based on IE9. Here is the tag before:
    <meta http-equiv="X-UA-Compatible" content="IE=8"/>
    Once the change is made:
    <meta http-equiv="X-UA-Compatible" content="IE=9">
    Please note that changing the IE meta tag can cause issues with JavaScript in IE. Use at your own risk. I have started a list of identified bugs at the end of this article that I will add on to as issues are discovered.
  5. Simplify the character encoding
    Another HTML5 gem, the character encoding can be much shorter. Here is the tag before:
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    And you know the drill by now, here is the tag after the change:
    <meta charset="utf-8">
  6. Removed type=”text/css” from link tags and type=”text/javascript” from script tags
    In HTML5 is is assumed that your link tags are for CSS and script tags are for JavaScript. Here is the before:
    <script type="text/javascript">
    <link rel="stylesheet" type="text/css" href="file.css" />
    And the after:
    <script>
    <link rel="stylesheet" href="file.css" />
  7. Add the HTML5 shiv (shim)
    So far our changes have been pretty tame. But we are about to start adding new tags to the master page such as <section> and <nav>. Seeing these tags usually makes people assume they can’t use HTML5 until the year 2022 (I didn’t make that up… it is a real misconception). The truth is you can add a tag in your HTML that says <gettinjiggywithit> and use CSS to style it and almost every browser will render the page just fine (and no, it won’t validate). The exception being Internet Explorer version 8 and earlier. If you toss <gettinjiggywithit> to IE and add some styles, your styles will be completely ignored. This applies to our new HTML5 tags as well. In order for IE8 (and older) to properly render your page, you need to add the HTML5 shiv (also referred to as shim) to your master page. Here is the code:
    <!--[if lt IE 9]>
    <script type="text/javascript" src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
    The first line is a conditional comment that is only read by IE. It translates to “if this is Internet Explorer lower than version 9, do the following”. For those of you who say “what about users who have JavaScript disabled?” – If your users have JavaScript disabled they aren’t going to be using SharePoint very well to begin with.