Monday, March 11, 2013

How to Add Custom JavaScript and jQuery to SharePoint : The best Way

The Best Way to Add Custom JavaScript and jQuery to SharePoint

During extensive SharePoint user interface customization you'll likely encounter a scenario where you need to make a web part or user control do something it was not intended to do or have a look that cannot be accomplished using the CSS hooks provided out-of-the-box. The solution is to create a custom master page and include a reference to a JavaScript file where you can modify the Document object. While straight JavaScript will do, I prefer to use the jQuery JavaScript library, which is far more robust, easier to use, and allows for plugins. Follow the steps below to add jQuery to your master page.

  1. Go to jquery.com and download the latest jQuery library to your desktop. You want to get the compressed production version, not the development version.
  2. Open SharePoint Designer (SPD) and connect to the root level of your site's site collection.
  3. In SPD, open the "Style Library" folder.
  4. Create a folder named "Scripts" inside of the Style Library.
  5. Drag the jQuery library JavaScript file from your desktop into the Scripts folder.
  6. In the Scripts folder, create a new JavaScript file and name it (e.g. "actions.js").
  7. Open your master page file in SPD.
  8. Within the <head> tag of the master page, add a script reference to the jQuery library just above the content place holder named "PlaceHolderAdditonalPageHead" (and above your custom CSS references, if applicable) as follows:
    <script src="/Style%20Library/Scripts/{jquery library file}.js" type="text/javascript"></script>
  9. Immediately after the jQuery library reference add a script reference to your custom scripts file as follows:
    <script src="/Style%20Library/Scripts/actions.js" type="text/javascript"></script>
Your custom master page now includes jQuery and a reference to your custom scripts file where you can add jQuery scripts. SharePoint includes a number of JavaScript files throughout the site, so be careful that the scripts you add do not conflict with SharePoint's; the jQuery library itself does not conflict with SharePoint.

Hope you Good Reading!

Tip/Trick: Guard Against SQL Injection Attacks

SQL Injection attacks are really nasty security vulnerabilities, and something all web developers (regardless of platform, technology or data layer) need to make sure they understand and protect themselves against. Unfortunately developers too often neglect putting focused time on this - and leave their applications (and worse their customers) extremely vulnerable.
Michael Sutton recently published a very sobering post about just how widespread this issue is on the public web. He built a C# client application that uses the Google Search API to look for sites vulnerable to SQL Injection Attacks. The steps to achieve this were simple:
  1. Look for sites that have querystring values (example: search for URLs with "id=" in the URL)
  2. Send a request to the sites identified as dynamic with an altered id= statement that adds an extra quote to attempt to cancel the SQL statement (example: id=6')
  3. Parse the response sent back to look for words like "SQL" and "query" - which typically indicate that the app is often sending back detailed error messages (also bad)
  4. Review whether the error message indicates that the parameter sent to SQL wasn't encoded correctly (in which case the site is open to SQL Injection Attacks)
Of a random sampling of 1000 sites he found via his Google search, he detected possible SQL Injection Attack vulnerability with 11.3% of them. That is really, really scary. It means hackers can remotely exploit the data in those applications, retrieve any unhashed/encrypted passwords or credit-card data, and potentially even log themselves in as administrators to the application. This is bad not only for the developer who built the application, but even worse for any consumer/user of the application who has provided data to the site thinking it will be secure.
So what the heck is a SQL Injection Attack?
There are a couple of scenarios that make SQL Injection attacks possible. The most common cause are cases where you are dynamically constructing SQL statements without using correctly encoded parameters. For example, consider this SQL query code that searches for Authors based on a social security number provided via a querystring:
Dim SSN as String
Dim
SqlQuery as String
SSN = Request.QueryString("SSN")
SqlQuery
= "SELECT au_lname, au_fname FROM authors WHERE au_id = '" + SSN + "'"

If you have SQL code like the snippet above, then your entire database and application can be hacked remotely. How? Well in the normal scenario users will hit the site using a social security number which will be executed like so:
' URL to the page containing the above codehttp://mysite.com/listauthordetails.aspx?SSN=172-32-9999
' SQL Query executed against the database SELECT au_lname, au_fname FROM authors WHERE au_id = '172-32-9999'

This does what the developer expected, and searches the database for author information filtered by the social security number. But because the parameter value hasn't been SQL encoded, a hacker could just as easily modify the querystring value to embed additional SQL statements after the value to execute. For example:
' URL to the page containing the above codehttp://mysite.com/listauthordetails.aspx?SSN=172-32-9999';DROP DATABASE pubs --

' SQL Query executed against the database
SELECT au_lname, au_fname FROM authors WHERE au_id = '';DROP DATABASE pubs --
Notice how I was able to add the ';DROP DATABASE pubs -- clause to the SSN querystring value and use it to terminate the current SQL statement (via the ";" character), and then add my own malicious SQL statement to the string, and then comment out the rest of the statement (via the "--" characters). Because we are just manually concatenating the SQL statement in our code, we will end up passing this to the database - which will execute first the query against the authors table, and then delete our pubs database table. Bang - it is now gone.
In case you think the idea of anonymous hackers deleting your database tables is bad, that is unfortunately actually one of the better scenarios when a SQL Injection Attack is involved. Rather than just destroy data, a hacker could instead use the above code vulnerability to perform a JOIN that retrieves all of the data within your database and displays it on the page (allowing them to retrieve username/passwords/credit-cards). They could also add UPDATE/INSERT statements to modify product prices, add new admin users, and really screw up your life (imagine auditing your inventory at the end of the month, only to discover that the actual number of products in your warehouse is different then what your accounting system reports...).
How do you protect yourself?
SQL Injection Attacks are something you need to worry about regardless of the web programming technology you are using (all web frameworks need to worry about it). A couple of very basic rules you must always follow:
1) Don't construct dynamic SQL Statements without using a type-safe parameter encoding mechanism. Most data APIs (including ADO + ADO.NET) have support for allowing you to specify the exact type of a parameter being provided (for example: string, integer, date) and can ensure that they are escaped/encoded for you to avoid hackers trying to exploit it. Always use these features.
For example, with dynamic SQL using ADO.NET you could re-write the code above like below to make it safe:
Dim SSN as String = Request.QueryString("SSN")

Dim cmd As
new SqlCommand("SELECT au_lname, au_fname FROM authors WHERE au_id = @au_id")
Dim param
= new SqlParameter("au_id", SqlDbType.VarChar)
param.Value
= SSN
cmd.Parameters.Add(param)
This will prevent someone from trying to sneak in additional SQL expressions (since ADO.NET above knows to string encode the au_id value), and avoid other data problems (incorrectly type-casting values, etc). Note that the TableAdapter/DataSet designer built-into VS 2005 uses this mechanism automatically, as do the ASP.NET 2.0 data source controls.
One common misperception is that if you are using SPROCs or a ORM you are completely safe from SQL Injection Attacks. This isn't true - you still need to make sure you are careful when you pass values to a SPROC, and/or when you escape or customize a query with an ORM that you do it in a safe way.
2) Always conduct a security review of your application before ever put it in production, and establish a formal security process to review all code anytime you make updates. This later point is super important. Too often I hear of teams that conduct a really detailed security review before going live, then have some "really minor" update they make to the site weeks/months later where they skip doing a security review ("it is just a tiny update - we'll code review it later"). Always do a security review.
3) Never store sensitive data in clear-text within a database. My personal opinion is that passwords should always be one-way hashed (I don't even like to store them encrypted). The ASP.NET 2.0 Membership API does this for you automatically by default (and also implements secure SALT randomization behavior). If you decide to build your own membership database store, I'd recommend checking out the source code for our own Membership provider implementation that we published here. Also make sure to encrypt credit-card and other private data in your database. This way even if your database was compromised, at least your customer private data can't be exploited.
4) Ensure you write automation unit tests that specifically verify your data access layer and application against SQL Injection attacks. This is really important to help catch the "it is just a tiny update so I'll be safe" scenario, and provide an additional safety layer to avoid accidentally introducing a bad security bug into your application.
5) Lock down your database to only grant the web application accessing it the minimal set of permissions that it needs to function. If the web application doesn't need access to certain tables, then make sure it doesn't have permissions to them. If it is only read-only generating reports from your account payables table then make sure you disable insert/update/delete access.

Friday, March 8, 2013

Les iPad et iPad mini risquent de pâtir d’une pénurie de capteurs tactiles

 

Le fournisseur de capteurs tactiles d'Apple n'aurait pas les capacités de production nécessaires pour satisfaire les demandes de la marque à la pomme. Les livraisons risquent de ralentir.



Décidemment Apple semble jouer de malchance avec ses fournisseurs. L’été dernier, des retards sur la livraison d’écrans LCD risquaient de pénaliser sa production d’iPhone 5. La qualité demandée par la marque à la pomme ralentissait la production de Sharp. Un investissement d’Apple dans les usines du japonais aurait « résolu » le problème. Aujourd’hui, ce sont les iPad et iPad mini qui sont concernés. D’après Digitimes, le principal fournisseur de capteurs tactiles à couche mince, Impression Nissha, ne serait pas en mesure de produire les quantités demandées.
Il est prévu que la prochaine génération d’iPad utilise les mêmes capteurs tactiles que l’iPad mini et Apple compte sur Nissha pour lui fournir ces composants a indiqué une source industrielle. La capacité de production annuelle de l’entreprise japonaise est de 60 millions de capteurs. Sachant qu’Apple compte fournir 33 millions d'iPad et 55 millions d’iPad mini en 2013, la capacité de production Nissha de capteurs de contact est clairement sous-dimensionnée. Cependant, des sources ont déclaré que l’entreprise japonaise prévoit d'étendre sa capacité de production de 30 % avant la fin du premier trimestre de 2013.
Cela dit, Apple pourrait être confronté à un autre souci : les chaînes d'approvisionnement des deux produits pourraient avoir à « se battre » pour ces capteurs au cours du deuxième trimestre afin de pouvoir chacune répondre aux demandes le trimestre suivant... Cela dit au vu du succès de l’iPad mini, celui-ci pourrait bien griller la politesse à son aîné et obtenir l’essentiel des capteurs.
Source : Digitimes



Wednesday, March 6, 2013

Défaut de Ballot Screen : Microsoft écope d'une amende de 561 millions d'euros

Microsoft-logo
Pour l'absence du choix du navigateur par défaut dans Windows 7 SP1 pendant plusieurs mois en Europe, la Commission européenne réclame 561 millions d'euros à Microsoft. La firme de Redmond accepte la sanction.
Attendue, la sanction est tombée pour Microsoft et elle est lourde. Pour ne pas avoir respecté ses engagements afin de permettre le choix du navigateur Web par défaut dans Windows, la firme de Redmond écope d'une amende de 561 millions d'euros de la part de la Commission européenne.
En 2009, la Commission européenne avait bouclé une enquête pour des soupçons d'abus de position dominante en relation avec ce qui avait été qualifié de " vente liée d'Internet Explorer avec Windows ". Microsoft avait alors pris l'engagement jusqu'en 2014 de proposer à l'utilisateur le choix du navigateur par défaut via l'affichage d'un écran multichoix.
Windows-Choix-NavigateurEntre mai 2011 et juillet 2012, cet écran multichoix n'a pas été intégré à Windows 7 Service Pack 1, soit 15 millions d'utilisateurs de Windows concernés dans l'Union européenne d'après Bruxelles. Un manquement à ses engagements qui vaut aujourd'hui sa lourde amende au géant du logiciel.
Pour Joaquín Almunia, vice-président de la Commission chargé de la concurrence, c'est une " infraction très grave qui doit être sanctionnée en conséquence ".
La Commission européenne explique que le montant de l'amende a été déterminé en tenant compte de la " gravité et de la durée de l'infraction ", de la " nécessité de conférer un effet dissuasif à l'amende ". Une circonstance atténuante retenue a été la coopération de Microsoft qui avait reconnu une erreur technique.
L'amende aurait pu aller jusqu'à 10 % du chiffre d'affaires annuel de Microsoft qui a été de 73,2 milliards de dollars en 2012 ( 56 milliards d'euros ). Finalement, cela n'aura été que 1 %.
En réaction à la sanction de la Commission européenne, Microsoft déclare assumer " l'entière responsabilité de son erreur technique " et rappelle avoir déjà présenté ses excuses :
" Nous avons fourni une évaluation complète et sincère de la situation à la Commission, et nous avons pris des mesures pour renforcer notre développement logiciel et autres processus pour éviter cette erreur à l'avenir. "
 

Hidden Tricks To SQL Server Table Cleanup

Today I'm gonna share with you a very intersting article related to SQL Cleanup in a very efficient Way ! Enjoy reading

Problem

Your SQL Server environment has millions of obsolete rows that need to be removed but you can’t impact the business and there is no maintenance window. How do you remove those rows with no business impact and avoid getting your boss on a tirade? What little known SQL tricks can you leverage to ensure a quick and non disruptive cleanup?

Solution

Building upon my earlier article published in SQLServerCentral, Large Table Clearnup with Minimal Locks, I have added to the small batch concept discussed there one key improvement: A coding trick to allow very efficient deletions by ordered primary key. Read on to discover how this works.

Background

For this article consider a 400 million row table called Event with 330 million obsolete rows. The primary index is on identity column EventID, figure 1.
CREATE TABLE [dbo].[Event](
      [EventId] [bigint] IDENTITY(1,1)  NOT NULL,
      [EventStatusId] [int] NOT NULL,
      [EventDuration] [float] NULL,
      [EventCloseDate] [datetime] NULL,
 CONSTRAINT [CUPK_Event_EventId] PRIMARY KEY CLUSTERED
(     [EventId] ASC )                                                  ) 
Figure 1
Since the column, EventId, is of type identity, it always increases in value upon insert so the oldest rows are the first ones inserted. If you select top 10 * from Event order by EventId you always get the ten oldest rows. This will come in handy.
How can you remove 330 million rows with very little impact? If you attempt
DELETE FROM EVENT WHERE EventCloseDate < yyyy-mm-dd 
the result will most likely be angry users due to all the lock contention. Operations won’t like you much with this approach since EventCloseDate could take up significant IO and CPU since has no index defined on it. Wouldn’t it be great if we could delete by the primary key, EventId, and use its index? Is this valid SQL?
DELETE TOP 1000000 FROM Event
Regrettably no. However using a hidden trick and a quick three step process you can accomplish the same thing.
The process is:
  1. Create a view to force row deletion by ordered primary key
  2. Create a store procedure to loop through the table deleting in small batches
  3. Setup a SQL job for nonstop execution.
Step One: Begin by using a hidden trick. This trick is to create a view to selected the top 2000 rows ordered by the primary key identity column (see figure 2). This view will be the target of the delete statement. The ‘order by’ ensures the rows are the oldest for the delete to follow and lets us add an order by to a delete, something SQL will not allow.
CREATE VIEW [dbo].[VEventCleanup] 
AS
 (SELECT TOP(2000)
   FROM EventTracking.dbo.Event 
   ORDER BY Eventid
  )
Figure 2
I keep the number of rows selected small (2000) for each transaction. You should experiment with this number to find the best fit for your shop. Remember the probability of contention issues increase as this number increases.
Step Two: Create a store procedure to loop through the table deleting rows in small batches, as shown in figure 3. As described in my previously mentioned article, take a large number of rows to delete, say 330 million, and delete them in small batches. Keeping the number of rows to delete below 5000 avoids lock escalations and limits the amount of time exclusive locks are held. This is the key to avoiding contention.
First set the maximum number of rows to delete. In this case a count of rows with column EventCloseDate older than 6 days. The 6 days is an arbitrary value, so substitute a value which works for you.
The code loops through the table deleting 2,000 rows in each transaction. This continues until all the table rows are deleted that are less than the maximum value.

USE [EventTracking]
GO
/****** Object:  StoredProcedure [dbo].[usp_VTrickleDeleteEvent]    
        Script Date: 12/15/2012 22:23:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/********************************************************************
  File Name:    usp_TrickleDeleteEvent.sql
  Applies to:   SQL Server 2008 R2
  Purpose:      To remove obsolete rows with minimal impact
  Returns:      0 = Succesful, 1 = Errors.
  Author:       Edward A. Polley       
********************************************************************/

ALTER PROCEDURE [dbo].[usp_VTrickleDeleteEvent]
AS
SET NOCOUNT ON
SET QUOTED_IDENTIFIER OFF

DECLARE @N INT     -- Row count for each transaction
DECLARE @cnt INT    -- Total row count for this run, can be hardcoded
DECLARE @loops INT  -- Number of transactions

BEGIN
 SET @N = 2000  —-must be same value as rows selected in view
 SELECT @cnt = COUNT(*)
  FROM [EventTracking].[DBO].[Event]
  WHERE EventCloseDate <  GETDATE() - 6   -- remove rows older than 6 days

 SET @loops = CEILING(@cnt/@N)  -- transactionHow many times to run
 WHILE @loops > 0
    BEGIN 
      BEGIN TRAN RemoveEvent
        DELETE FROM VEventCleanup   –- delete from view with order by
        SET @loops = @loops  1     -- decrement @loop
        COMMIT TRAN                 -- COMMIT to release locks   
    END   
 END                                                        
Step Three: Create a SQL batch job. At 330 million rows this job will take days to complete, but the good news is there is very little contention, I run cleanup jobs right through the busiest processing window with no issues. Try experimenting with the @N variable. The larger this value is, the fewer loops, but the higher the probability of timeouts. Remember this @N value must match the Top x statement in the view.
The wasiest way to create the new job in Management Studio is by expanding SQLServer Agent folder and then right clicking Jobs folder. The General tab might look like this:


Figure 4
Then click Steps tab and enter the name of the stored procedure from step 2 above. Set the Type of job to TSQL and the Database to EventTracking. The New Job Step tab might look like this:


Figure 5
Save this and you are done.
In three steps you’ve created a job to remove obsolete rows with very low contention. Give it a try, I think you’ll find is removes rows with so little contention even your cranky boss won’t notice.

Thanks to  Edward Polley from sqlservercentral Team

Tuesday, March 5, 2013

FILESTREAM with SharePoint 2010

Tuesday, January 15, 2013

SharePoint Document Library: Add document link or Link to a Document

In SharePoint, there’s a way to add document link. Many of use not aware of it. To add the document link you need to add “Link to a Document” Content type in your library. By default content type modification is disabled in any list/library. To enable editing content type you need to go to list/library settings. Once you have enabled the content type editing, you can add/remove content type.

Enable Content Type Modification in List/Library

To enable content type editing go to list/library settings page. Then from the list settings page,  Click “Advanced Settings” and in the advanced settings page, click “Yes” for option “Allow Management of Content Types”. Enabling this option will allow you to modify content type settings. Click Ok after selecting Yes option.
After coming back to list settings page you will find the content modifying option as  shown below:
image

Add Link To Document Content Type to the library

Now from the ‘Add from Existing site content types’ link as shown in the image above, you can add the “Link to Document” content type. click “Add from existing site content types” and from the page you have landed you can the content type as shown below:
image
After adding the content type go back to document library page. You’ll find that when you’ll try to add new item, you’ll get the ‘Link to a Document’ option as shown below:
image
With this link to document item, you can add links to content not only in sharepoint but non-SharePoint content from other sites.

Programmatically Add Link to a document using SharePoint Object Model

Once you enable the ‘link to document’ support in any document library you can add the document programmatically. The following code snippet shows how to add a link to a document content in a library.
public static void AddDocumentLink(string webUrl, string libraryName,string documentPath, string documentName, string documentUrl)
{
    using (var site = new SPSite(webUrl))
    {
        using (var web = site.OpenWeb())
        {
            var contentType = web.AvailableContentTypes["Link to a Document"];
            var docLibrary = web.Lists[libraryName];
                 
            //get full path of the document to add
            var filePath = docLibrary.RootFolder.ServerRelativeUrl;
            if(!string.IsNullOrEmpty(documentPath))
            {
                filePath += "/" + filePath; 
            }
            var currentFolder = web.GetFolder(filePath);

            var files = currentFolder.Files;
            var urlOfFile = currentFolder.Url + "/" + documentName + ".aspx";

            const string format = @"<%@ Assembly Name='{0}' %>
            <%@ Register TagPrefix='SharePoint' Namespace='Microsoft.SharePoint.WebControls' Assembly='Microsoft.SharePoint' %>
            <%@ Import Namespace='System.IO' %>
            <%@ Import Namespace='Microsoft.SharePoint' %>
            <%@ Import Namespace='Microsoft.SharePoint.Utilities' %>
            <%@ Import Namespace='Microsoft.SharePoint.WebControls' %>
                <html>
                    <head> 
                            <meta name='progid' content='SharePoint.Link' /> 
                    </head>
                    <body>
                        <form id='Form1' runat='server'>
                            <SharePoint:UrlRedirector id='Redirector1' runat='server' />
                        </form>
                    </body>
                </html>";

            var builder = new StringBuilder(format.Length + 400);
            builder.AppendFormat(format, typeof(SPDocumentLibrary).Assembly.FullName);

            var properties = new Hashtable();
            properties["ContentTypeId"] = contentType.Id.ToString();

            var file = files.Add(urlOfFile, new MemoryStream(new UTF8Encoding().GetBytes(builder.ToString())), properties, false, false);
            var item = file.Item;
            item["URL"] = documentUrl + ", ";
            item.UpdateOverwriteVersion();
        }
    }
}
The above code snippet is the modified version of what SharePoint does when you add a document link from UI. I have used reflector to view the code and placed here a modified version. I have tested this against SharePoint 2010.