Loading a JS function onload with SharePoint 2013

I recently worked on a SP2013 solution where i was required to inject a dynamic URL parameter into an iframe. This was done using Javascript and as I had no access to the body tag in the SharePoint page I opted to use JQUERY to trigger the function after the dom had loaded.

Whilst this worked in my non SP test bed it didn't work when i deployed to my on premise SP2013 box. Problem turned out to be SharePoint 2010 uses its own body onload function called _spBodyOnLoadFunctionNames which will collide with the document.ready function. 

Best Practice for executing JS/Jquery functions on load:

create a function with a custom name, and push the custom name into the _spBodyOnLoadFunctionNames array.

instead of:

 

$(document).ready(function() {

     // My custom functionality

});

 

use:

 

_spBodyOnLoadFunctionNames.push("myCustomFunctionName");

function myCustomFunctionName() {

     // My custom functionality

}

 

Worked a treat, hope this helps someone else out.

How to Fix Restore failed for Server while attempting 'RestoreContainer ValidateTargetForCreation'

16. October 2012 14:12 by Stephen in SQL  //  Tags: , ,   //   Comments (0)
Well this happened to me for the first time ever when trying to do a restore from back in SQL 2008 R2. Sometimes the error gets thrown up as "failed to retrieve text for this error reason 15105" Full error is shown below. "Restore failed for Server 'DELL3-PC\SQLEXPRESS'. (Microsoft.SqlServer.SmoExtended) System.Data.SqlClient.SqlError: The operating system returned the error '5(Access is denied.)' while attempting 'RestoreContainer::ValidateTargetForCreation' on 'c:\Program Files\Microsoft SQL" 1. Open Microsoft SQL Server Management Studio 2. Right click on the database you want to restore, then in the menu -> choose Tasks -> Restore -> Database... 3. Now in the SQL Server "Restore Database" pop-up box, select the backup set to restore. Then on the left side under "Select a page", click on "Options" In the Restore options section, I usually will select "Overwrite the existing database (WITH REPLACE), NOTE: If you overwrite the database, just make sure that before restoring, you have a backup located else where in case something goes wrong. HERE's where the "Restore failed" problem arose for me: In the Options page, under the "Restore the database files as:" section, the "Restore As" directoy path name was different than that of the current database that I was trying to restore. So I simply needed to change the directory name of both the .mdf file and the log (.ldf) file for the database to the location of the current database (so they match). Note: You will also need to make sure that the "Restore As" file names are the same name of the database you are restoring (in the past I've run into differing file names, causing a problem restoring databases). Once you've made sure that the "Restore As" directory path and file names for the (.mdf & .ldf) files are the correct location to the current database you are restoring, click "OK" That's it!

Should your assembly name be the same as the root namespace and also be the same as your project name

7. September 2012 11:51 by Stephen in ASP.net development, Visual Studio  //  Tags: ,   //   Comments (0)
I've often mused over the best naming conventions for Project, namespace and assembly name. Below is the best explanation i've found so far. "Assuming that you are talking about .NET (with relation to Visual Studio) then the root namespace is what each class you create in a visual studio project will become part of. It is also the base for any sub-namespaces that are automatically assigned when you create a class inside of a project folder. So with a base namespace of ACMECorp.Bombs all of your classes would become part of the ACMECorp.Bombs namespace so the class GravityBomb would have a full name of ACMECorp.Bombs.GravityBomb. A class called FlyingBomb created in a project folder called GuidedBombs would have a full type name of ACMECorp.Bombs.GuidedBombs.FlyingBomb. The Assembly name is simply the name of the compiled file that your code will be compiled to as either an executable or library etc... A question that I often see on this is should your assembly name be the same as the root namespace and also be the same as your project name (again in visual studio). I used to be of the mind set that you should have a project name the same as the assembly name the same as the root namespace just as is the default with visual studio. However if you need to do some major refactoring and renaming this can become a pain in the bum, especially if you are using source control (as you then should start renaming the project folders). My suggestion would be that your project name is simply a descriptive name of the contents of the project. Your assembly name should consist of the technology area and compnent description or company name and technology area (depending on your preferance), and your root namespace should be as described by the Microsoft naming standards so: Project: Biometric Device Access Assembly: BiometricFramework.DeviceAccess.dll Namespace: ACME.BiometricFramework.DeviceAccess Some reference material for you: http://blogs.msdn.com/brada/archive/2003/04/19/49992.aspx http://msdn.microsoft.com/en-us/library/ms229026.aspx http://msdn.microsoft.com/en-us/library/ms229048.aspx"

Add remove comments for a block of code in Visual Studio (VB)

19. July 2012 16:04 by Stephen in ASP.net development, Visual Studio  //  Tags: ,   //   Comments (0)

I've been using Visual studio since 2005 and have just realised you can do this....doh!

You can add or remove comment symbols for a block of code by selecting one or more lines of code and choosing the Comment () and Uncomment () buttons on the Edit toolbar.

SharePoint designer 2010 check-in check-out issue's

10. July 2012 10:36 by Stephen in SharePoint  //  Tags:   //   Comments (0)

Since moving jobs into a new SharePoint developer role I keep coming up against check-in/check-out issue's where by SPD 2010 thinks files are checked out when they are checked in and vice versa.

Very frustrating but an easyfix, just clear the cache as below.

Simply put, SharePoint Designer is out of sync with SharePoint and you have to delete its cache in order to rebuild it. The cache is composed of these 2 folders:

%APPDATA%\Microsoft\Web Server Extensions\Cache

%USERPROFILE%\AppData\Local\Microsoft\WebsiteCache

Just delete their contents and you are done.

Stephen

Import legacy Customers into Nop Commerce 2.XX

17. January 2012 17:02 by Stephen in Development, SQL  //  Tags: , ,   //   Comments (0)

This was no easy task and took arund 3 days of banging my head against the wall but got there in the end...

We had an old ecommerce system which we were migrating to the new (and Fantastic) Nop Commerce 2.30, there is currently no import option in this version, removed in version 2.0 i believe. So here is a step by step process of what I had to do.

Step 1 -  Create Hashed passwords and Salt Key

Using the old database table for Customers, in my case "RegisteredUsers" which only stored the passwords in plain text i created two new columns, NopPassword and PasswordSalt.

Against that table i ran the following SQL Query.

DECLARE @NopPassword VarChar(50)
DECLARE @MyUserID INT
DECLARE myMaintblCursor CURSOR FOR
SELECT RegisteredUsers.UserID FROM RegisteredUsers

OPEN myMaintblCursor

--Read the initial User ID value from the cursor
FETCH NEXT FROM myMaintblCursor
INTO @MyUserID

WHILE @@FETCH_STATUS = 0
BEGIN
DECLARE @Salt VarChar(50)
EXEC dbo.sp_GenerateRandomString 8, @Salt OUTPUT

UPDATE RegisteredUsers

SET NopPassword = SUBSTRING(UPPER(CONVERT(VarChar(50), HASHBYTES('SHA1', Password + @Salt),1)),3,40), PasswordSalt = @Salt
--CONVERT(NVARCHAR(MAX), HASHBYTES('SHA1', Password + @Salt),1), PasswordSalt = @Salt
--SUBSTRING(UPPER(master.dbo.fn_varbintohexstr(CAST(HASHBYTES('SHA1', Password + @Salt)as varbinary ))),0,40), PasswordSalt = @Salt

WHERE RegisteredUsers.UserID = @MyUserID

--get the next User ID value from the cursor
FETCH NEXT FROM myMaintblCursor
INTO @MyUserID
END

DEALLOCATE myMaintblCursor

Probably not the best way to do this but worked for me, I had to use a cursor so that I could generate a Randon Salt key for every row, then i added this to the origonal user password.  This was where i had the biggest problem, i intitally created the new Columns with NVARCHAR(MAX) to match the NOP DB, which meant the HASHED version of the password was coming in wierd symbols, Then i tried to convert this using "master.dbo.fn_varbintohexstr" but all i ever ended up with was a HEX STRING value which was wrong.

Solution was to change the NopPassword and Password salt to VARCHAR(50) which gave me the Key, but 2 characters to big and lowercase. Nop does not like the password hash in lower case so thats where the following line came in.

SUBSTRING(UPPER(CONVERT(VarChar(50), HASHBYTES('SHA1', Password + @Salt),1)),3,40), PasswordSalt = @Salt

I used the following website to check if things were correct, at last it was! Woop woop!

Also you will need the following SP to generate the random Salt Key

PROCEDURE [dbo].[sp_GenerateRandomString]

    (

      @sLength INT = 10 ,

      @randomString NVARCHAR(255) OUTPUT

    )

AS

    BEGIN

        DECLARE @counter INT ;

        DECLARE @nextChar NCHAR(1) ;

        SET @counter = 1 ;

        SET @randomString = '' ;

 

        WHILE @counter <= @sLength

            BEGIN

                SET @nextChar = NCHAR(ROUND(RAND() * 93 + 33, 0)) ;

                IF ASCII(@nextChar) NOT IN( 34, 39, 40, 41, 44, 46, 96, 58, 59 )

                    BEGIN

                        SET @randomString = @randomString + @nextChar ;

                        SET @counter = @counter + 1 ;

                    END ;

            END ;

    END ;

Step 2 -  Import User details

From here i wrote an import script to import the users from the old DB into NOP.

INSERT INTO Nop.dbo.Customer
(Id,CustomerGuid, Username, Email, Password,PasswordFormatId, PasswordSalt, TaxDisplayTypeId, IsTaxExempt, VatNumberStatusId, UseRewardPointsDuringCheckout, Deleted,IsSystemAccount, CreatedOnUtc, LastActivityDateUtc, Active, BillingAddress_Id, ShippingAddress_Id)
SELECT UserID, NEWID(),EmailAddress, EmailAddress, NopPassword,'1', PasswordSalt, '0','0', '10', '0', '0', '0', GETDATE(),GETDATE(), '1',UserID, UserID  FROM OldSite.dbo.RegisteredUsers
WHERE OldSite.dbo.RegisteredUsers.ApprovedStatus = 'Approved'

NOTE: Indenity needs to be set to NO as we need to keep the same ID for the users across all the relavent tables, remember to turn that back to Yes.

Step 3 - Setup Address mapping

next up is the address.

INSERT INTO Nop.dbo.CustomerAddresses
(Customer_Id, Address_Id)
SELECT Id, Id FROM Nop.dbo.Customer
WHERE Nop.dbo.Customer.Id > 7

I only used the where statement becuase I had some existing data in the new Nop DB.

NOTE: You will need to turn of the Foreign Key retrainst on both Shipping and billing

Step 4 - Setup Roles

Then the Role mapping

INSERT INTO Nop.dbo.Customer_CustomerRole_Mapping
(Customer_Id, CustomerRole_Id)
SELECT Id, '3' FROM Nop.dbo.Customer
WHERE Nop.dbo.Customer.Id > 7

3 is the ID for registered users, but you could use any ID you wanted.

Step 4 - Import Address's

Then the Users address's.

INSERT INTO Nop.dbo.Address
(Id,FirstName, LastName, Email, Company, City, Address1, Address2, ZipPostalCode, PhoneNumber, CreatedOnUtc)
SELECT UserID, FirstName, Surname, EmailAddress, CompanyName, TownCity, Address1, Address2, Postcode, Telephone, GETDATE() FROM Live.dbo.RegisteredUsers
WHERE Live.dbo.RegisteredUsers.ApprovedStatus = 'Approved'

Optional

The only thing which i did not do which you could is add in the address/name and email details into the CustomerAttribute table, you need this if you want the users to see thier address on the first page of "My Account".

Hope this helps anyone having to do the same thing and saves them some time.!

 

 

List all the tables in your SQL database

19. October 2011 22:00 by Stephen in Development, SQL  //  Tags: ,   //   Comments (0)

Never had a reason to ever do this until tonight...and here is how.

USE YourDBName

GO 

SELECT *

FROM sys.Tables

ORDER BY Col

GO

Centre widthless floats in a text basd menu.

19. October 2011 09:33 by Stephen in ASP.net development, CSS  //  Tags:   //   Comments (0)

Tried a couple of different methods over the years for achieving a text based menu (unordered list) using floated il but this one seems the best and simplest. You can find the full post here.

#buttons{
float:right;
position:relative;
left:-50%;
text-align:left;
}
#buttons ul{
list-style:none;
position:relative;
left:50%;
}

#buttons li{float:left;position:relative;}/* ie needs position:relative here*/

#buttons a{
text-decoration:none;
margin:10px;
background:red;
float:left;
border:2px outset blue;
color:#fff;
padding:2px 5px;
text-align:center;
white-space:nowrap;

}
#buttons a:hover{ border:2px inset blue;color:red;background:#f2f2f2;}
#content{overflow:hidden}/* hide horizontal scrollbar*/

Robin red breast

7. October 2011 23:47 by Stephen in General  //  Tags:   //   Comments (0)

Seen this Robin red breast today outside the office, quite happy for me to get within touching distance! Cool as a cucumber!

David Orr Golf coaching website goes live

7. October 2011 19:13 by Stephen in Development, Umbraco  //  Tags: , , ,   //   Comments (0)

 

We're delighted to announce we've launched a new website with David and Rona Orr, fantastic people and great clients and we're sure the site and business are going to be a massive success.  Click here to visit the site.

About the author

Something about the author

Month List

Page List