Thursday 22 December 2011

Some More Examples on difference between two dates using Javascript

Calculating days remaining until Christmas:
<script type="text/javascript">

//Set the two dates
today=new Date()
var christmas=new Date(today.getFullYear(), 11, 25) //Month is 0-11 in JavaScript
if (today.getMonth()==11 && today.getDate()>25) //if Christmas has passed already
christmas.setFullYear(christmas.getFullYear()+1) //calculate next year's Christmas
//Set 1 day in milliseconds
var one_day=1000*60*60*24

//Calculate difference btw the two dates, and convert to days
document.write(Math.ceil((christmas.getTime()-today.getTime())/(one_day))+
" days left until Christmas!")

</script>
 
Example: 3 days left until Christmas!
Calculating time expired since the Millennium (Jan 1st, 2000)
<script type="text/javascript">

//Set the two dates
var millennium =new Date(2000, 0, 1) //Month is 0-11 in JavaScript
today=new Date()
//Get 1 day in milliseconds
var one_day=1000*60*60*24

//Calculate difference btw the two dates, and convert to days
document.write(Math.ceil((today.getTime()-millennium.getTime())/(one_day))+
" days has gone by since the millennium!")

</script>
Example: 4374 days has gone by since the millennium!
Dynamically indicating what's new on your page:
<script type="text/javascript">

var newimage='<img src="news.gif">'
var today=new Date()

function whatsnew(yr,mon,day){
var expire=new Date(yr,mon,day)
if (today.getTime()<=expire.getTime())
document.write(newimage)
}

</script>

<!--"New" image will disappear after Dec 30th, 2002-->
<script>whatsnew(2002,11,30)</script> This is new content!
Example: This is new content!

Calculate difference between two dates

Example-1:

Find day difference between two dates (excluding weekend days)

<script type="text/javascript">

    $
("#startdate, #enddate").change(function() {      

   
var d1 = $("#startdate").val();
   
var d2 = $("#enddate").val();

           
var minutes = 1000*60;
           
var hours = minutes*60;
           
var day = hours*24;

           
var startdate1 = getDateFromFormat(d1, "d-m-y");
           
var enddate1 = getDateFromFormat(d2, "d-m-y");

           
var days = 1 + Math.round((enddate1 - startdate1)/day);            

   
if(days>0)
   
{ $("#noofdays").val(days);}
   
else
   
{ $("#noofdays").val(0);}


   
});

   
</script>

Example-2:

Calculate Business Days between two dates




  1. function calcBusinessDays(dDate1, dDate2) { // input given as Date objects
  2.  
  3. var iWeeks, iDateDiff, iAdjust = 0;
  4.  
  5. if (dDate2 < dDate1) return -1; // error code if dates transposed
  6.  
  7. var iWeekday1 = dDate1.getDay(); // day of week
  8. var iWeekday2 = dDate2.getDay();
  9.  
  10. iWeekday1 = (iWeekday1 == 0) ? 7 : iWeekday1; // change Sunday from 0 to 7
  11. iWeekday2 = (iWeekday2 == 0) ? 7 : iWeekday2;
  12.  
  13. if ((iWeekday1 > 5) && (iWeekday2 > 5)) iAdjust = 1; // adjustment if both days on weekend
  14.  
  15. iWeekday1 = (iWeekday1 > 5) ? 5 : iWeekday1; // only count weekdays
  16. iWeekday2 = (iWeekday2 > 5) ? 5 : iWeekday2;
  17.  
  18. // calculate differnece in weeks (1000mS * 60sec * 60min * 24hrs * 7 days = 604800000)
  19. iWeeks = Math.floor((dDate2.getTime() - dDate1.getTime()) / 604800000)
  20.  
  21. if (iWeekday1 <= iWeekday2) {
  22. iDateDiff = (iWeeks * 5) + (iWeekday2 - iWeekday1)
  23. } else {
  24. iDateDiff = ((iWeeks + 1) * 5) - (iWeekday1 - iWeekday2)
  25. }
  26.  
  27. iDateDiff -= iAdjust // take into account both days on weekend
  28.  
  29. return (iDateDiff + 1); // add 1 because dates are inclusive
  30.  
  31. }

Example-3:
Calculating the Number of Days Between Any Two Dates

<script language="JavaScript" type="text/javascript">
<!--

function days_between(date1, date2) {

    // The number of milliseconds in one day
    var ONE_DAY = 1000 * 60 * 60 * 24

    // Convert both dates to milliseconds
    var date1_ms = date1.getTime()
    var date2_ms = date2.getTime()

    // Calculate the difference in milliseconds
    var difference_ms = Math.abs(date1_ms - date2_ms)
    
    // Convert back to days and return
    return Math.round(difference_ms/ONE_DAY)

}

//-->
</script>
This function accepts

Example-4
<script type="text/javascript">
function PreSaveAction()
{
     //var Date1=document.getElementById("ctl00_m_g_a3891a90_455d_467d_888a_d925ce4fc814_ctl00_ctl04_ctl01_ctl00_ctl00_ctl04_ctl00_ctl00_DateTimeField_DateTimeFieldDate");
 
 var dtStDate = new Date(document.getElementById("ctl00_m_g_c19e22b2_bb2e_4ea5_8598_6c207adec1b2_ctl00_ctl04_ctl01_ctl00_ctl00_ctl04_ctl00_ctl00_DateTimeField_DateTimeFieldDate").value);
 //Getting End date value from the control
    var dtEndDate = new Date(document.getElementById("ctl00_m_g_c19e22b2_bb2e_4ea5_8598_6c207adec1b2_ctl00_ctl04_ctl02_ctl00_ctl00_ctl04_ctl00_ctl00_DateTimeField_DateTimeFieldDate").value);
    var one_day=1000*60*60*24; 
   
   if(dtStDate !="NaN" &&  dtEndDate !="NaN")  
 {
 
  //Assigning the Difference in days to the control
        var fnlValue=Math.ceil((dtEndDate.getTime()-dtStDate.getTime())/(one_day))+1;  
        //var fnlValue=((dtEndDate.getTime()-dtStDate.getTime())/(one_day))+1;  
  var today=new Date()
  var selectedDay=new Date(dtStDate.getFullYear(), dtStDate.getMonth(),dtStDate.getDate(1)) //Month is 0-11 in JavaScript
  //Calculate difference btw the two dates, and convert to days
  var leaveDuration =(Math.ceil((selectedDay.getTime()-today.getTime())/(one_day))); 
  //var leaveDuration=(Math.ceil((selectedDay.getTime()-today.getTime())/(one_day)));
  //var leaveDuration=calcBusinessDays(selectedDay,today);
  //alert(leaveDuration); 
  if(dtEndDate < dtStDate )
  {
          alert('Please check your selected dates');
    return false;
  }
  if(leaveDuration < -60)
  {
        alert('Sorry! You have selected dates that have passed more than 60 days');
         return false;
  }
  else
  {
  if(leaveDuration < -0)
    {
      if(confirm("Are you sure you want to proceed? "+"\n \n"+"You have selected dates that have passed. This is only possible if you have been absent on account of illness."))
      {       
        return true;
            }
            else
            {
             return false;
            }
    }
  }
  if(fnlValue >4)
  {
    if(leaveDuration <=14)
    {   
  
   if(confirm("WARNING :Are you sure you want to continue?"+"\n \n"+"Your application for Leave is late. There is insufficient notice as per the norms laid down by the Leave Policy. Your request for leave is being forwarded, but your Manager may not consider it on grounds of Short Notice."))
      {          
         return true;
      }
      else
   {
      
       return false;
   }         
    }
  }
  else
  {
    //alert('Your total leaves are applied :'+ fnlValue);
    return true;
  }
  return true;   
  } 
}
</script>

Wednesday 21 December 2011

How do we enable anonymous access in SharePoint 2010

Enabling anonymous access has two stages. First, this has to be enabled in Central Administration for the respective Web-Application. Then it has to be set for the respective Site (site collection).
Navigate to the central administration page.
Click on Application Management ->Manage Web Applications. Select the web application and click on ‘Authentication providers’


A pop-up window opens, from which you need to select your authentication provider as shown in the image below. Click on ‘Default’
This opens up the edit window of the selected authentication provider. In this window CHECK the “Enable Anonymous Access” field and click on ‘Save’

The above process sets anonymous access at CA level. We still have to set the anonymous access for a single site-collection or for a root site.
Enabling Anonymous Access for a Site
Go to the respective site, for which anonymous access has to be enabled.
Navigate to Sites->Site Permissions. You will notice a new option ‘Anonymous Access’ in the ribbon.

Click on Anonymous Access and select the required option. Selecting ‘Entire Web site’ gives read-only permissions to all users who visit the site.

The process described above is how we enable Read-Only access to anonymous users. But there are also few scenarios where we need to give limited Write/Edit permissions to anonymous users.

For example, when we create a blog site in SharePoint we need to give permissions for all users to add comments to the (published) posts.
(**Note: A SharePoint blog site has three lists – Categories, Posts and Comments—which are created by default. Categories and Posts can be ‘Read only’ lists. But when Comments are taken into consideration, we need to allow anonymous users to write/enter their comments.)
Enabling Anonymous Users to Add Comments to Blog Posts
Navigate to your blog site. Click on, Sites->Site Settings. There in the left menu bar find all the available lists in the blog site. Select ‘Comments’

Now all the available comments will be shown.
In the ribbon select, List Tools->List->List Permissions

Here, we can set permissions for anonymous users to add comments by stopping ‘Inherit permissions’ and giving permissions exclusively for this list. Click on ‘Stop Inheriting Permissions’, this stops inheriting permission from parent site.

When we stop inheriting permissions from parent site, ‘Anonymous Access’ appears in the ribbon menu. Click on this and select ‘Add Items- Add items to lists’

You are done and any user can add comments to your blog posts!!!
But wait, this may not work in cases where BLOG is set as a sub site under a publishing site.
This is because site collection is based on publishing portal and have a ‘ViewFromPagesLockdown’ feature. This feature prevents anonymous users from gaining access to certain areas of site. So, first check if ‘ViewFromPagesLockdown’ feature is enabled for the site.

To determine if a site has ‘ViewFromPagesLockdown’ enabled run the following in Powershell:
get-spfeature -site http://sitecollectionURL
If ViewFormPagesLockDown is listed, it’s enabled.
To toggle lockdown mode to off:
$lockdown = get-spfeature viewformpageslockdown
disable-spfeature $lockdown -url

Now re-set the anonymous access and try to add comments to a blog post without signing in. You can add comments!!!!

How To Hide Ribbon From Users Without Edit Page Privilege in SharePoint 2010

Ribbon is a great new feature introduced by SharePoint 2010. It provides great user experience for users with elevated privileges, like contributors and site owners. However, for users with lease privilege, such as visitors and anonymous users, it seems like a big waste of page real estate. Because for those users, all ribbon provides are navigation breadcrumb and welcome control (user name with a drop down list on top-right corner).
So I have been asked to figure out a way to remove or hide the ribbon area from user with lease privilege, and here is how:
1)      Open your SharePoint master page
2)      Locate this line:<div id="s4-ribbonrow" class="s4-pr s4-ribbonrowhidetitle">
3)      Change it to:<div id="s4-ribbonrow" class="s4-pr s4-ribbonrowhidetitle" style="display:none">
4)      Now find the end of the “s4-ribbonrow” tag and add following block right after it:<Sharepoint:SPSecurityTrimmedControl ID="SPSecurityTrimmedControl2" runat="server" PermissionsString="AddAndCustomizePages">    <script type="text/javascript">        document.getElementById("s4-ribbonrow").style.display = "block";
    </script>
</
Sharepoint:SPSecurityTrimmedControl>
5)      Save the new master page and publish it.
Now when a user without “AddAndCustomizePages” access to view the site, they would not see the ribbon area. You may want to move at least the welcome control to somewhere outside the ribbon area so your lease privilege users can see their user names.
The reason that you have to do it the other way around: make the ribbon invisible (step 3) and make it visible only when users have “AddAndCustomizePages” access (step 4) is the ribbon HTML code has to be rendered to the browser otherwise you would lose some basic abilities on the page, like, to be able to scroll up and down.
Enjoy your page real estate back!

Some General Difference Between Microsoft Office SharePoint and SharePoint Server 2010

MOSS 2007 Vs SPS 2010

I have noted down some difference between MOSS 2007 Vs SPS 2010. I have also refered some points form MSDN and other MVP's blogs. Hope you will like these.


Microsoft Office SharePoint
Server 2007
SharePoint Server 2010
Office client required to view and edit documents uploaded to document libraries (Download and open)
Office Web Application enables Word, PowerPoint, Excel and Visio documents, using Silverlight or HTML with JavaScript (Depending on Browser Support)
No Co-Authoring Capability
Co-Authoring Capabilities available for Word, PowerPoint (with client software) and Excel (Available over the web)
Lot of post backs
Fewer post backs for default actions – more Ajax usage
No inherent support of Ajax or Silverlight
Fully supported
Static themes. You just pick a theme and its applied across the site, no preview
You can select a theme , customize it and preview before applying it on the site
No bookmarking, tagging or rating capability
Its all there
Content Types scoped to site collections
New concept of having a Content Type hub which can be shared across web applications
Media files would have to be downloaded before playing
Progress download feature available (not streaming)
BDC used to store info in SharePoint
BCS reads data real-time (with some caching for performance)
5 million item limit in document library
10 million
Views are CAML driven
Views XSLT based
To query a list we had to use CAML
Queries via LINQ, JavaScript and Silverlight API’s
No restriction for installation
Ability to prevent people from installing SharePoint (Managed at the AD level)
Shared Services scoped to Farm
Shared Services architecture changed to make it more flexible and ability to share across farm
Profile synch could be done by anyone
Additional permission check for account to carry out profile synch
Basic web Analytics
Web analytics capability enhanced
Search results are static
Clicking on a search result affects the search results for the other searches for the same keyword
To limit issues with rogue code that could bring down the server, CAS had to be defined /maintained for different applications. This was not easy to do and Admins used to say – no code allowed
Sandbox available that restricts the scope of code. Deployment is also easy, the code just needs to be uploaded by the site admin, no need for intervention from the SharePoint farm admin to run scripts on the server
People with contribute access could upload .aspx pages in a document library. It was possible to restrict, however it would restrict everyone from uploading .aspx pages
People with contribute access cannot load .aspx pages
Contributors could edit tool pane parameters
Not editable by contributors
Explorer view on browser
Opens up Windows explorer with web dav access
Simplistic Mobile Page OOTB
Able to create richer mobile pages using OOTB features
Usage of outlook for offline access
SharePoint Workspace used for offline access – more capability eg. ability to synch up lists (even external content from BCS)
Not possible to have a common document ID that is associated with a document regardless of which document library it moves into
Document ID can be defined and associated to the document regardless of where it is located(within the site collection)
To upload a document or page, one needs to go to that appropriate site/subsite and library and upload
Content organizer moves document to appropriate libraries based on metadata rules which can be defined
When a file with a same name is uploaded, it creates a new version
Option to have another version or append a unique ID to the document being uploaded
Fixed layout with defined web part zones where web parts can be placed
More “Fluid” UI; ability to place web parts without having web part zones
Retention policy allows only delete or invoke workflow by default
Multiple other options – eg send to another library etc
EBS – to store docs out side SharePoint, possible but not easy to configure
RBS -  managed by SQL
Requires Server OS to install(32 or 64)
Can be installed on Win 7 (64 bit) and Win 2008 (64 bit)
No field validations
Field validations available
Workflows created in SPD or VS.Net – not possible to move a workflow developed in SPD to VS.Net
Workflows can be defined in Visio, Imported to SPD with rules added and then moved to VS.Net
Table based layouts
Div Based layouts (better for accessability)



SP 2010
MOSS 2007
Look and feel
In SP 2010 look and feel perspective there will be a ribbon where we can have a look and feel like Office 2010
In MOSS 2007 there is no ribbon
Deployment of Web parts
In SharePoint 2010 deploying custom web part is pretty simple i.e. just right click on the solution and click Deploy
In MOSS 2007 you need to drag the dll either to bin or GAC
Silverlight Application
In SP 2010 we can create a Silverlight application directly from Visual Studio 2010
In MOSS 2007 we have to create a web part to host Silverlight application
Shared Database & Service Application
In SP 2010 there is no SSP but there is a concept of Service Application like BCS as one service application, Excel Services as another service application, User Profile as separate service application
General idea is that you have an application for each service, rather than one application with lots of service crammed into it
Own database rather than shared database in SP 2010
In MOSS 2007 we have SSP where we can work around with BI,Search Settings, User Profile Import, Excel Services, Info path
In Database also we use to have separate area for SSP stuff
Easy exports/imports between the forms
In SP 2010 we can update existing information
In MOSS 2007 through we can just read the information and we can't update the existing services
Improvement in Deployment
In SP 2010 we can Deploy through Farm based and solution based solution in SP 2010
In MOSS 2007 there is no such option
Alerts
In SP 2010 it has been improved in validation and unique values. While creating column itself we have an option "Allow Duplicate values" to Yes or No
In MOSS 2007 alerts were sent only through emails but in SP 2010 users can also send alerts to mobile device as SMS message. A New property delivery channel is introduced to indicate, whether the alerts is delivered as Email or an SMS message
Improvements of events
New events for list creation and web creation
No List and web events in MOSS 207
Getting Items from the list
In SP 2010 through object model we can fetch multiple list data by LINQ query and object model
In MOSS 2007 we can fetch only through object model
Rating
In SP 2010 we can have rating column by default
In MOSS 2007 we should install the feature that is available in codeplex to have rating
Key Word Suggestions
In SP 2010 we can have keyword suggestions
In MOSS 2007 we don’t have any keyword suggestions
Taxonomy
In SP 2010 we can create Taxonomy by using Managed Metadata service
In MOSS 2007 we don’t have taxonomy
Other Features
In SP 2010 we have Power Shell Scripting, JavaScript object model, Chart Web Parts
In MOSS 2007 we don’t have Power Shell Scripting, JavaScript object model, Chart Web Parts
Running stsadm command
In SP 2010 we have to go 14 hive path to run stsadm command
In MOSS 2007 we have to go 12 hive path to run stsadm command