Tuesday, 27 October 2015

LINKS

Links:-

https://msdn.microsoft.com/en-us/library/ee539350.aspx
https://msdn.microsoft.com/en-us/library/ee535717.aspx
https://msdn.microsoft.com/en-us/library/ee539429.aspx

http://www.learningsharepoint.com/2011/04/13/sharepoint-2010-object-model-tutorial-iii/
http://www.learningsharepoint.com/sharepoint-2010-ecmascriptjavascript-client-object-model-tutorialsamples/
http://expert-sharepoint.blogspot.in/2015/06/sharepoint-client-object-model.html
http://expert-sharepoint.blogspot.in/2015/06/create-new-sharepoint-website-using.html

Usefull Java Script

1.Only Numeric value with one dot like 10.50:-

    function isNumber(evt, element) {

        var charCode = (evt.which) ? evt.which : event.keyCode

        if (
            (charCode != 45 || $(element).val().indexOf('-') != -1) &&      // “-” CHECK MINUS, AND ONLY ONE.
            (charCode != 46 || $(element).val().indexOf('.') != -1) &&      // “.” CHECK DOT, AND ONLY ONE.
            (charCode < 48 || charCode > 57))
            return false;

        return true;

    }

Call the above method   onkeypress="return isNumber(event,this);"

2.Only Numeric value:-

    <script type="text/javascript">
        function numvalidate(text) {
            // numeric with decimal
            //var test_str = /(?!^0*$)(?!^0*\.0*$)^\d{1,9}(\.\d{1,2})?$/
            // only numeric value
            if (test_str.test(text.value))
            {
                if (text.value > 10000000)
                {
                    alert("Please enter a valid Amount.");
                    text.focus();
                    return false;
                }
                return true;
            }
            else {
                if (text.value == "")
                    return true;
                alert("Please enter a valid Amount.");
                text.focus();
                return false;
            }
        }

    </script>
Call below
                  <td>
                    <asp:TextBox ID="txtAmountLTC" runat="server" Text="" onblur="return numvalidate(this);" ToolTip="Only decimal value"></asp:TextBox>                  
                </td>


3. "Only nemeric with two decimal values allowed for ex. 5.23"

  <script type="text/javascript">

function QtyNPrice(me) {
            var str = me.value;
            var regexstr = /^[0-9]{1,12}(\.[0-9]{1,2})?$/;
            if (!str.match(regexstr) && str.length > 0) {
                alert("Only nemeric with two decimal values allowed for ex. 5.23");
                me.focus();
            }
        }
 </script>
  <asp:TextBox ID="txtAmountLTC" runat="server" Text="" onblur="QtyNPrice(this);" ToolTip="Only decimal value"></asp:TextBox>


4. Confirmation message by client side code
    <script type="text/javascript">
        function ConfirmMsg(msg)
      {
            var r = confirm(msg);
            if (r == true) {
                return true;
            }
            else {
                return false;
            }
        }  
    </script>
<asp:Button ID="btnResetAll" runat="server" Text="Reset All" onclick="btnResetAll_Click"
                    OnClientClick="return ConfirmMsg('Are you sure you want to reset this page?');" TabIndex="13" />


5. Valid PAN number
    <script type="text/javascript">
 function validatePANNo(idPAN) {
        var obj = document.getElementById(idPAN);
        //if (!validateTextBox(idPAN, 'Please enter PAN number')) { return false; }
        var regexstr = /[A-Za-z]{5}\d{4}[A-Za-z]{1}/; var str = obj.value;
        if (trim(str).length > 0 && trim(str).length < 11) {
            if (!str.match(regexstr)) { alert("Please enter valid PAN."); obj.focus(); return false; }
            else { return true; }
        }
        else {
            alert("Please enter valid PAN."); obj.focus(); return false;
        }
    }
    </script>

               <td>
                <span>PAN</span>
            </td>
            <td>
                <asp:TextBox ID="txtPAN" runat="server" Text="" onblur="javascript:return validatePANNo('txtPAN'); "></asp:TextBox>
            </td>

6. Only alphanumeric values are allowed.
<script type="text/javascript">
function isAlphanumeric(me) {
        if (me.value.length > 0) {
            var regexstr = /[^a-z 0-9.-\/\\ A-Z]/; regexstr.multiline = true; var str = me.value;
            if (str.match(regexstr)) { alert("Only alphanumeric values are allowed."); me.focus(); me.select(); return false; }
        } return true;
    }
    </script>
<td>
                <span>Company Name</span>
            </td>
            <td>
                <asp:TextBox ID="txtCompany" runat="server" Text="" onblur="javascript:return isAlphanumeric(this);" Width="98%" BorderWidth="0px" ReadOnly="true"></asp:TextBox>
            </td>


7. Mobile number 
<script type="text/javascript">
function isMobileNumber(me) {
        if (me.value.length > 0) {
            var regexstr = /[^0-9]/;
            var str = me.value;
            if (me.value.length > 10 || (str.match(regexstr))) {
                alert("Only 10 digit mobile number is allowed");
            }
        }
    }
    </script>
<td>
                <span>Mobile No.</span>
            </td>
            <td>
                <asp:TextBox ID="txtMobile" runat="server" onblur="javascript:return isMobileNumber(this);"></asp:TextBox>
            </td>

8.Count the Grid Row
<script type="text/javascript">
function grdRowCount(grdID,errMsg)
    {
    try{
      var obj = document.getElementById(grdID);
       if(obj.rows.length<1)
       {
       alert(errMsg);
       return false;
       }
       else
       {
       return true;
       }
       }
       catch(err){
       alert(errMsg);
       return false;
       }
    }
    </script>

9.trim the String

  function trim(str) {
        str = str.replace(/^\s+/, '');
        for (var i = str.length - 1; i >= 0; i--) {
            if (/\S/.test(str.charAt(i))) { str = str.substring(0, i + 1); break; }
        } return str;
    }

10. Clear All controls of Div

    function ClearAllControls(divName) {
        var searchEles = document.getElementById(divName).children;
        for (var i = 0; i < searchEles.length; i++) {
            if (searchEles[i].tagName == 'INPUT') doc.value = "";
            if (searchEles[i].tagName == 'SELECT') doc.selectedIndex = 0;
        }
    }


 11.   function isAlphabetBorrower(me) {
        if (me.value.length > 0) {
            var regexstr = /[^a-z ,. A-Z]/; var str = me.value;
            if (str.match(regexstr)) { alert("Only alphabets and (,) are allowed."); me.focus(); me.select(); return false; }
        } return true;
    }
       function isNumericBorrower(me) {
        if (me.value.length > 0) {
            var regexstr = /[^0-9,]/; var str = me.value;
            if (str.match(regexstr)) { alert("Only Numeric and (,) are allowed without space."); me.focus(); me.select(); return false; }
        } return true;
    }




Tuesday, 15 September 2015

Read the Excel file

Config File :-      <add key ="Excel07ConString"  value="Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0}; Extended Properties='Excel 12.0 Xml;HDR=YES';"/>


    <add key="sourceDirPath" value="D:\BIO10_DATA\PRD\SAP2INET\EmployeeMaster" />



string strSourcedirPath = ConfigurationManager.AppSettings["sourceDirPath"].ToString();

 try
            {
                FileInfo f = new FileInfo(ExcelFilePath);
                string FileName = Path.GetFileName(f.Name);
                string Extension = Path.GetExtension(f.Name);

                string conStr = "";
                switch (Extension)
                {
                    case ".xls": //Excel 97-03
                        conStr = ConfigurationManager.AppSettings["Excel03ConString"].ToString();
                        break;
                    case ".xlsx": //Excel 07
                        conStr = ConfigurationManager.AppSettings["Excel07ConString"].ToString();                  
                        break;
                }
                //string ConnStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + ExcelFilePath + "; Extended Properties='Excel 12.0 Macro;HDR=NO';";
                conStr = String.Format(conStr, ExcelFilePath);


                //OleDbConnection con = new OleDbConnection(conStr);
                //string strquery = "select * from [Sheet1$]";
                //OleDbDataAdapter oledbDA = new OleDbDataAdapter(strquery, con);
                //DataTable dt = new DataTable();
                //oledbDA.Fill(dt);



                //OleDbConnection connExcel = new OleDbConnection(conStr);
                //OleDbCommand cmdExcel = new OleDbCommand();
                //OleDbDataAdapter oda = new OleDbDataAdapter();
                //DataTable dtExcel = new DataTable();
                //cmdExcel.Connection = connExcel;
                //connExcel.Open();
                //DataTable dtExcelSchema;
                //dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                //string SheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();          
                //cmdExcel.CommandText = "SELECT * From [" + SheetName + "]";
                //oda.SelectCommand = cmdExcel;
                //oda.Fill(dtExcel);

                OleDbConnection con = new OleDbConnection(conStr);
                //string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + ExcelFilePath + ";Extended Properties='Excel 12.0 Xml;HDR=YES'";
                //OleDbConnection con = new OleDbConnection(connectionString);
                string strquery = "select * from [Sheet1$]";
                OleDbDataAdapter oledbDA = new OleDbDataAdapter(strquery, con);
                DataTable dt = new DataTable();
                oledbDA.Fill(dt);

  }
            catch (Exception e)
            {
                Console.WriteLine(e.Message.ToString());
                Console.ReadKey();
            }




Thursday, 6 August 2015

hide some of the FormMenuItem Buttons on a New, Display or Edit form in SharePoint List 2007

To hide some of the FormMenuItem Buttons on a New, Display or Edit form in SharePoint is very easy.







All you have to do is to add a bit of Javascript to the form. You can quickly do this via the SharePoint designer.

Open the form on which you want to hide the menu item button in SharePoint Designer. Once opened switch to code view.



















Once you have the code view open, find the PlaceHolderBodyAreaClass section and insert the following code:

<script type="text/javascript"> 
  alert('Hello');
</script>










Save the form and hit F12 to view in browser.
You should now see an alert message popup when you access the form.
If you go the following message then it means that your Javascript is executing without any problems and that you can now proceed to add the relevant code to hide the desired buttons. 
  
  
  
  
  
  
  
  
  
  
  
So, in SharePoint Designer, at the same location where you added the Javascript code, replace the following code: 
<script type="text/javascript"> 

alert('Hello');
</script>
with:
<script type="text/javascript"> 

  hideFormMenuItems("Delete Item");


  function hideFormMenuItems()
  { 
   var titleToHide="";
   var anchorTag;
   var allAnchorTags = document.getElementsByTagName('a');
   for(var i = 0; i < hideFormMenuItems.arguments.length; i++ ) 
   { 
    titleToHide = hideFormMenuItems.arguments[i]; 
    if(titleToHide!='Alert Me')
    {
     for (var j = 0; j < allAnchorTags.length; j++)
     {
      anchorTag= allAnchorTags[j]; 
      if (anchorTag.title.indexOf(titleToHide)!=-1)
      { 
anchorTag.parentNode.parentNode.parentNode.parentNode.parentNode.style.display="none";
anchorTag.parentNode.parentNode.parentNode.parentNode.parentNode.nextSibling.style.display="none"; 
       break;
      }
     }
    }
    else
    {
     for (var k=0; k < allAnchorTags.length;k++)
     {
      anchorTag= allAnchorTags[k]; 
      if (anchorTag.id.indexOf("SubscribeButton")!=-1)
      { 
anchorTag.parentNode.parentNode.parentNode.parentNode.parentNode.style.display="none";
       break;
      }
     }
    }
   }
  var allSpanTags = document.getElementsByTagName("span"); 
  var spanTag;
  var toolbarRow;
  var lastCell;
  for(var m=0; m < allSpanTags.length;m++)
  {
   spanTag = allSpanTags[m];
   if(spanTag.id=='part1')
   {
    toolbarRow = spanTag.childNodes[2].firstChild.firstChild;
    lastCell = toolbarRow.lastChild.previousSibling 
    while(lastCell.style.display=='none')
    { 
     lastCell = lastCell.previousSibling; 
    } 
    if(lastCell.innerText == '')
    { 
     lastCell.style.display='none'; 
    } 
    break; 
   }
  }
 }
</script>


So, when done, save your form and run.... you will see the "Delete Item" button is hidden.
You can now add more javascript to only hide the button based on certain conditions.



Enjoy!!



Wednesday, 29 July 2015

Hide Columns in SharePoint New, Edit and Disp Forms

To hide fields in a SharePoint 2007 form, follow these steps (I will use the NewForm.aspx in my example)


  1. Open SharePoint Designer and navigate to the site that contains the list or document library you wish to customize.
  2. Expand the folder named “Forms” under the desired list or document library.  You should see about seven .aspx pages (AllItems.aspx, EditForm.aspx, NewForm.aspx, etc)
  3. Open the NewForm.aspx page and switch to the “code” view to edit the HTML of the page.
  4. Paste the JavaScript code immediately below the the following HTML tag <asp:Content ContentPlaceHolderId=”PlaceHolderMain” runat=”server”>  This will add the JavaScript to the HTML inside the content placeholder tag.  Note: be sure to include the entire script below, including the <script and </script> tags.
  5. Modify the “hidefields()” section of the JavaScript code to refer to each SharePoint list field name to hide.  For example, the code sample below will hide the SharePoint fields named Title, Document Link, and PublishDate    Notice that you do not need to worry about internal field names or field types like other JavaScript techniques, you simply need to know the name of the field.
  6. Save the changes.  Select “Yes” when prompted to “…customize the page from the site definition…”
  7. Test the form
<script language="javascript" type="text/javascript">

_spBodyOnLoadFunctionNames.push("hideFields");

function findacontrol(FieldName) {

   var arr = document.getElementsByTagName("!");
   // get all comments
   for (var i=0;i < arr.length; i++ )
   {
      // now match the field name
      if (arr[i].innerHTML.indexOf(FieldName) > 0)
      {         return arr[i];      }
   }
}

function hideFields() {

   var control = findacontrol("Title");
   control.parentNode.parentNode.style.display="none";
   control = findacontrol("Document Link");
   control.parentNode.parentNode.style.display="none";
   control = findacontrol("PublishDate");
   control.parentNode.parentNode.style.display="none";

}
</script>




Another way:-


<script type="text/javascript">
$(document).ready(function() {
    $('nobr:contains("Completion time")').closest('tr').hide();
    $('nobr:contains("Score")').closest('tr').hide();
});
</script>


Monday, 15 June 2015

Java Script Method

Helpfull Java Script Method 

1.   <script language="javascript" type="text/javascript">
        function textboxMultilineMaxNumber(txt, maxLen) {
            try {
                if (txt.value.length > (maxLen - 1)) return false;
            } catch   {
            }
        }
    </script>

 <asp:TextBox ID="txtRemarks" onkeypress="javascript:return textboxMultilineMaxNumber(this,4000)"
  runat="server" TextMode="MultiLine" Width="98%" Height="100"></asp:TextBox>


Wednesday, 10 June 2015

Add the ... after string 50 character

Add the ... after string lengh

  public string strStringTruncates(string s, int length)
        {
            if (String.IsNullOrEmpty(s))
                throw new ArgumentNullException(s);
            var words = s.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            if (words[0].Length > length)
                return words[0];
            var sb = new StringBuilder();

            foreach (var word in words)
            {
                if ((sb + word).Length > length)
                    return string.Format("{0}...", sb.ToString().TrimEnd(' '));
                sb.Append(word + " ");
            }
            return string.Format("{0}...", sb.ToString().TrimEnd(' '));

        }


Call the method:-
lblTechnologyUsed.Text = strStringTruncates((e.Row.DataItem as DataRowView).Row["Technology_x0020_Used"].ToString().Trim(), 50);



Wednesday, 13 May 2015

hotfix for problem with SharePoint PeopleEditor in IE-9


Sharepoint 2010 and IE9 compatibility


I created a javascript file called entityeditor.ie9fix.js, added the javascript code that will follow, and saved it in /layouts/1033.


https://social.msdn.microsoft.com/Forums/en-US/90b3835c-6754-4bb6-9fd4-b74f16f236ff/sharepoint-2010-and-ie9-compatibility?forum=sharepointgeneralprevious


In my master page I added
<script type="text/javascript" src="/_layouts/1033/entityeditor.ie9fix.js"></script>
to the very BOTTOM of the master page, right before the following tags:
<input type="text" name="__spDummyText1" style="display:none;" size="1"/>
<input type="text" name="__spDummyText2" style="display:none;" size="1"/>

function ConvertEntityToSpan(ctx, entity)
{ULSGjk:;
    if(matches[ctx]==null)
        matches[ctx]=new Array();
    var key=entity.getAttribute("Key");
    var displayText=entity.getAttribute("DisplayText");
    var isResolved=entity.getAttribute("IsResolved");
    var description=entity.getAttribute("Description");
    var style='ms-entity-unresolved';
    if(isResolved=='True')
        style='ms-entity-resolved';
    var spandata="<span id='span"+STSHtmlEncode(key)+"' isContentType='true' tabindex='-1' class='"+style+"' ";
    if (browseris.ie8standard)
        spandata+="onmouseover='this.contentEditable=false;' onmouseout='this.contentEditable=true;' contentEditable='true' ";
    else
        spandata+="contentEditable='false' ";
    spandata+="title='"+STSHtmlEncode(description)+"'>"
    spandata+="<div style='display:none;' id='divEntityData' ";
    spandata+="key='"+STSHtmlEncode(key)+"' displaytext='"+STSHtmlEncode(displayText)+"' isresolved='"+STSHtmlEncode(isResolved)+"' ";
    spandata+="description='"+STSHtmlEncode(description)+"'>";
    var multipleMatches=EntityEditor_SelectSingleNode(entity, "MultipleMatches");
    matches[ctx][key]=multipleMatches;
    var extraData=EntityEditor_SelectSingleNode(entity, "ExtraData");
    if(extraData)
    {
        var data;
        if(extraData.firstChild)
            data=extraData.firstChild.xml;
        if(!data) data=extraData.innerXml || extraData.innerHTML;
        if(!data && document.implementation && document.implementation.createDocument)
        {
            var serializer=new XMLSerializer();
            data=serializer.serializeToString(extraData.firstChild);

                    // **** CUSTOM FUNCTION ****
            data = fixDataInIE9(data);
        }
        if(!data) data='';
        spandata+="<div data='"+STSHtmlEncode(data)+"'></div>";
    }
    else
    {
        spandata+="<div data=''></div>";
    }
    spandata+="</div>";
    if(PreferContentEditableDiv(ctx))
    {
        if(browseris.safari)
        {
            spandata+="<span id='content' tabindex='-1' contenteditable='false'  onmousedown='onMouseDownRw(event);' onContextMenu='onContextMenuSpnRw(event,ctx);' >";
        }
        else
        {
            spandata+="<span id='content' tabindex='-1' contenteditable onmousedown='onMouseDownRw(event);' onContextMenu='onContextMenuSpnRw(event,ctx);' >";
        }
    }
    else
    {
        spandata+="<span id='content' tabindex='-1' contenteditable onmousedown='onMouseDownRw(event);' onContextMenu='onContextMenuSpnRw(event,ctx);' >";
    }
    if (browseris.ie8standard)
        spandata+="\r";
    if(displayText !='')
        spandata+=STSHtmlEncode(displayText);
    else
        spandata+=STSHtmlEncode(key);
    if (browseris.ie8standard)
        spandata+="\r</span></span>\r";
    else
        spandata+="</span></span>";
    return spandata;
}

// **** CUSTOM FUNCTION ****
function fixDataInIE9(data)
{
    if(data.indexOf('<ArrayOfDictionaryEntry>') >= 0)
    {
        data = data.replace('<ArrayOfDictionaryEntry>', '<ArrayOfDictionaryEntry xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema-instance\">');
    }
    return data;
}


After setting that up and publishing the master page I reloaded my site and had no problems saving people from the people picker. Heck of a lot easier than trying to get everyone to use firefox, or some kind of plugin.
PS: I marked my code with // ** CUSTOM FUNCTION **
/**** UPDATED 4/25/2012 ******/
Added reference to the exact location in which to place updated entityeditor.ie9fix.js script tag. Placing the script here will allow you to create new items and edit existing ones which contain a people picker control.