Umer Pasha Blogs

www.umerpasha.com

Google Home vs. Amazon Echo 2nd gen. unbiased review.

I got to test both echo dot 2nd gen and Google Home together. I have a honeywell smart thermostat, philips hue lighting and a lifx bulb.

So Google home lost out in the end! It needs a lot of work with it’s integration. Even though the current price of $99 is appealing and it does have much better sound recognition, it’s integration with smart things is abysmal.
It is on the right track though and if it does not receive the Google Axe soon, it will bypass echo in it’s next generation.

Problems with Home:
There is not much direct native support for many brands to start wth. So you are reliant on IFTTT to do most of the stuff. That is where the problems start.

In the end, it was not able to do the primary job of toggling all lights upstairs on or off using one voice command….. and that did it!

Pros:
Speaker is good. Pleasent friendly human voice. Not robotic like echo.
Looks way more aesthetic than an echo.
Voice recognition is miles better than echo.
Human voice interaction is very good and again, daylights better than echo.
Love it that I can insert numbers and text in IFTTT triggers. Like I can say set the temperature to #. Or, set the bulb color to $. Something not available with echo.
It does not say “Sending it to IFTTT” for every IFTTT trigger like echo and I can customize what it says. More Human again.

Cons:
Cannot create groups of lights for hue. Mainly a problem with Hue itself but Echo mitigates it by providing groups. So basically, you can ask home to turn on the light in bedroom but are unable to turn on all lights upstairs with one voice command.
Cannot toggle hue lights in IFTTT trigger. Works 1/10 times. Adds to the problem above because you cannot even use IFTTT to mitigate that by creating multiple triggers on same event. The trigger worked fine with Lifx though.
It was not able to see my bought music on Google play and play it. Kept saying my playlist is empty. gave up soon on this and just played from my phone.
Have a properietery power input. For someone who likes to hide wires behind furniture, it hinders my mobility of things. Should have been some standard USB input.

Leave a comment »

Windows authentication fails on iOS when accessing an https URL on mobile-data/LTE

Windows authentication fails on iOS when accessing an https URL on mobile-data/LTE.

We are are trying to access a dot net web service with https URL and are not able to authenticate. It keeps on asking for username and password.

What we know:
– Works fine on http
– Works fine if connected to WiFi
– Any windows authenticated site on https does not work with mobile data but works fine with wifi
– Any windows authenticated site on https does not work with safari but works fine with Chrome on iOS
– Have tried both iOS 8.1 and 9.1

https://discussions.apple.com/thread/7343260

Anybody got any answers? Please let me know.

Leave a comment »

MS SQL Source code for Las vegas Slot Machine game

Sometimes while working you feel like running away and to take a break…. maybe a drive to Vegas.

Now with this script, you will not have to. You will bring Vegas to your MS-SQL Server Query Window!

Just change the DB name (UmerDB) in the script below to any of your DB where you want to host. Maybe name it your favorite casino! and run the script.

To play all you have to do is execute the following command repeatedly in the query window with the DB selected:
USAGE: sp_LVG ‘login’,’password’,
EXAMPLE: sp_LVG ‘Umer’,’pwd123′,15.50

Different symbols have different winning factors. Every double or triple wins! It’s that easy!
Even if you have a $ show up in one of the slots, you don’t lose! See… told you it was easy!

Winnings go up in this order. $$$ is a jackpot:

‘#’
‘€’
‘£’
‘†’
‘A’
‘7’
‘¤’
‘$’

Enjoy!


USE [UmerDB]
GO

/****** Object: StoredProcedure [dbo].[sp_LVG] Script Date: 02/08/2010 15:06:53 ******/
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_LVG]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_LVG]
GO

USE [UmerDB]
GO

/****** Object: StoredProcedure [dbo].[sp_LVG] Script Date: 02/08/2010 15:06:53 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--USAGE: sp_LVG 'login','password',
--EXAMPLE: sp_LVG 'lgn','pwd',15.50

Create Procedure [dbo].[sp_LVG] 
 @Login varchar(10),
 @Password varchar(10),
 @Money Money

AS
BEGIN
SET NOCOUNT ON;

Declare @Count As int
Declare @StartingBalance As Money
Declare @Slot1 As char(1)
Declare @Slot2 As char(1)
Declare @Slot3 As char(1)
Declare @Temp As char(1)
Declare @Slots varchar(3)
Declare @Factor As Float
Declare @Tries Int


Select @StartingBalance = 100
Select @Count = 0
Select @Tries = 0

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[LVG]') AND type in (N'U'))
BEGIN
 CREATE TABLE [dbo].[LVG]
 (
 vLogin varchar(10),
 vPassword varchar(10),
 mMoney Money,
 iTries Int 
 )
END

Select @Count = Count(vLogin) From LVG Where vLogin = @Login and vPassword = @Password 
If @Count > 0
Begin
 Select vLogin As Your_Login, mMoney as Your_Balance, iTries as Tries From LVG Where vLogin = @Login and vPassword = @Password

 Select @StartingBalance = mMoney From LVG Where vLogin = @Login and vPassword = @Password
 If @StartingBalance > 0 AND @StartingBalance >= @Money
 Begin

 Create Table #Slots
 (
 iInt int,
 cASCII tinyint 
 )

 Insert into #Slots values (1,35)
 Insert into #Slots values (2,36)
 Insert into #Slots values (3,55)
 Insert into #Slots values (4,65)
 Insert into #Slots values (5,128)
 Insert into #Slots values (6,134)
 Insert into #Slots values (7,163)
 Insert into #Slots values (8,164)

 Create Table #Winnings
 (
 vSymbol varchar(1),
 iOccurance tinyint,
 fFactor float
 )

 Insert into #Winnings values ('#',2,0)
 Insert into #Winnings values ('€',2,0.25)
 Insert into #Winnings values ('£',2,0.5)
 Insert into #Winnings values ('†',2,0.75)
 Insert into #Winnings values ('A',2,1.75)
 Insert into #Winnings values ('7',2,1.50)
 Insert into #Winnings values ('¤',2,1.25)
 Insert into #Winnings values ('$',2,2.0)
 Insert into #Winnings values ('#',3,1.25)
 Insert into #Winnings values ('€',3,1.5)
 Insert into #Winnings values ('£',3,1.75)
 Insert into #Winnings values ('†',3,2.0)
 Insert into #Winnings values ('A',3,2.25)
 Insert into #Winnings values ('7',3,2.50)
 Insert into #Winnings values ('¤',3,2.75)
 Insert into #Winnings values ('$',3,3.0)



 Select @Slot1 = char(cASCII) from #Slots Where iInt = CEILING(8 * RAND()) 
 Select @Slot2 = char(cASCII) from #Slots Where iInt = CEILING(8 * RAND()) 
 Select @Slot3 = char(cASCII) from #Slots Where iInt = CEILING(8 * RAND()) 

 Select @Slot1 As Slot_1, @Slot2 As Slot_2, @Slot3 As Slot_3 

 If @Slot1 = @Slot2 Or @Slot1 = @Slot3 Or @Slot2 = @Slot3
 Begin
 Select @Slots=@Slot1 + @Slot2 + @Slot3
 DECLARE temp_cursor CURSOR FORWARD_ONLY FOR 
 Select distinct vSymbol, fFactor from #winnings where 
 ((3 - LEN(REPLACE(@Slots, @Slot1, ''))) =iOccurance and vSymbol = @Slot1)
 OR
 ((3 - LEN(REPLACE(@Slots, @Slot2, ''))) =iOccurance and vSymbol = @Slot2)
 OR
 ((3 - LEN(REPLACE(@Slots, @Slot3, ''))) =iOccurance and vSymbol = @Slot3)

 OPEN temp_cursor
 FETCH NEXT FROM temp_cursor INTO @Slots, @Factor
 CLOSE temp_cursor
 DEALLOCATE temp_cursor

 Update LVG Set mMoney = (mMoney + (@Money * @Factor)) ,
 iTries = iTries + 1
 Where vLogin = @Login 
 End
 Else
 Begin
 --Select @Count = max(iInt) from #Slots 
 Select @Count = 2 --For $ 
 Select @Temp = char(cASCII) from #Slots where iInt = @Count

 If @Temp <> @Slot1 And @Temp <> @Slot2 And @Temp <> @Slot3
 Update LVG Set mMoney = (mMoney - @Money) ,iTries = iTries + 1 Where vLogin = @Login 
 Else
 Update LVG Set iTries = iTries + 1 Where vLogin = @Login 
 
 End
 
 

 Drop Table #Slots
 Drop Table #winnings

 Select @Login As Your_Login, mMoney as Your_Balance, iTries as Tries From LVG Where vLogin=@Login
 End
End
Else
Begin
 Insert into LVG values (@Login, @Password, @StartingBalance, 0)
 Select @Login As Your_Login, @Password as Your_Password, @StartingBalance as Your_Balance 
End

--Drop Table LVG
--Drop proc sp_lvg
--sp_LVG 'up2','up2',10


END
GO


Leave a comment »

Simplest example of Phonegap testing bar code, camera picture, camera video and geo location

When I started using phonegap, It took a while even with the available documentation to get the app going. I made this example project to trim it to bare minimum but still perform the most sought after functions on any mobile device.

For build purposes i am using build.phonegap.com. Create a test account that allows for one app.

You will probably also need a github account as it makes it very simple to pull updated code from repository when making a build on build.phonegap.com.

I am testing this on an android device as it is just easy to update and download app for testing using android. For Apple/iOS, you will need to have a key.

The functionality has been tested on latest versions of Android, iOS and WinPhone.

To understand this tutorial, you should already know:
Some knoweldge of HTML and HTML5
Working knowledge of Javascript
Some idea what phonegap really is

It has examples of camera function, video recording and geo location.

The only files you have to look into are in www folder.

Config.xml has all the plug-ins defined:

Example: <gap:plugin name=”org.apache.cordova.core.geolocation” version=”0.3.10″ />

Index.html has all the UI and buttons to invoke different functions along with DIVs to show results

Js/app.js has all the javascript code.

I wait for device to be ready to listen to events:

Example: document.addEventListener(“deviceready”, onDeviceReady, false);

If an event is fired (touch end of a button), separate functions are called:

Example: document.querySelector(“#startGLoc”).addEventListener(“touchend”, startGLoc, false);

On event completion, result is updated:

Example: GLocDiv = document.querySelector(“#GLoc”);
Code location is on GitHUb: https://github.com/genrex/PhonegapCamera

Build can be accessed from this QR code:

1 Comment »

Simplest Phonegap Barcode reader example

Created a small app last night to read barcodes.

 

Nothing fancy. Just a button to invoke the barcode reader camera and then returns the barcode number along with the barcode standard.

 

You can get it here:

 UmerBarcodeReader_QR

 

Checked on iPhone 5S and Android Kit Kat.

 

I am only using an html file and a js file along with the config.xml.

 

You can get the code from my github repository. You can remove the resource files from config.xml. I just got it from the base template.

 https://github.com/genrex/PhonegapBarcode

 

Instructions:

 

  1. To add the plugin , in Config.xml you need to have:

<gap:plugin name=”com.phonegap.plugins.barcodescanner”/>

 

  1. Write the following javascript to listen for an event (button click) and then start the scanner

 

</p><p>var resultDiv;</p><p> </p><p>document.addEventListener("deviceready", init, false);</p><p>function init() {</p><p>               
 document.querySelector("#startScan").addEventListener("touchend", startScan, false);</p><p>               
 resultDiv = document.querySelector("#results");</p><p>}</p><p> </p><p>function startScan() {</p><p> </p><p>               
 cordova.plugins.barcodeScanner.scan(</p><p>                               function(result) {</p><p>                                               
 var s = "Result: " + result.text + "&lt;br/&gt;" +</p><p>                                               "Format: " + result.format + "&lt;br/&gt;" +</p><p>                                               "Cancelled: " + result.cancelled;</p><p>                                               
 resultDiv.innerHTML = s;</p><p>                               
 },</p><p>                               function(error) {</p><p>                                               
 alert("Scanning failed: " + error);</p><p>                               
 }</p><p>               );</p><p> </p><p>}</p><p> </p><p>

 

 

 

 

 

7 Comments »

Sharepoint – Cannot open Visio files FIXED!

This issue comes up in Sharepoint 2013 when you have Visio 2010 installed and also Office 2013 installed.

This seems to be a known problem for Visio 2010 files when you have Visio 2010 and Office 2013 installed on the machine.

If you see the URL, you will see a small prefix “ms-visio:ofv” which is the protocol used for Office 2013. But, as we do not have Visio 2013 installed, it throws an error.

I have created a small registry file that will trick the system into thinking that there is Visio 2013 installed but route it to Visio 2010.

I have attached the file here having default paths. If your Office or Visio is installed elsewhere, please change. here is the source of the .reg file. Otehrwise, all users need to do is rename the file here to open up as a zip file, run the .reg file and accept all warning messages.

Download VisioReg.Zip file here

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\ms-visio]
@="Url:Visio Protocol"
"URL Protocol"=""
"UseOriginalUrlEncoding"=dword:00000001

[HKEY_CLASSES_ROOT\ms-visio\DefaultIcon]
@="C:\\PROGRA~2\\MICROS~1\\Office14\\VISIO.EXE,0"

[HKEY_CLASSES_ROOT\ms-visio\shell]

[HKEY_CLASSES_ROOT\ms-visio\shell\open]

[HKEY_CLASSES_ROOT\ms-visio\shell\open\command]
@="C:\\PROGRA~2\\MICROS~1\\Office15\\PROTOC~1.EXE \"%1\""


5 Comments »

VB Source Code to get facebook status messages using Graph API

You will need an authentication token from facebook to access it. Please check apps.facebook.com for that. Again, you will have to create an app and get an authentication token generated with the correct rights.


        url = "https://graph.facebook.com/me/statuses?fields=id,message&amp;limit=50&amp;offset=0&amp;access_token=" & sToken

        strJSON = get_page_contents( URL ) 

        set user = JSON.parse( strJSON )
 

                    TmpVal=user.data.get(FBScounter).id
                    If TmpVal=OldVal then
                        ErrFlag=1
                        exit do
                    End If
'                        FBStatus2 = cdate(left(user.data.get(FBScounter).updated_time,10) & " " & mid(user.data.get(FBScounter).updated_time,12,5)) & ": " & user.data.get(FBScounter).message 
                        response.write "<li><span>" & cdate(left(user.data.get(FBScounter).updated_time,10) & " " & mid(user.data.get(FBScounter).updated_time,12,5)) & "</span><a href='#'>" & user.data.get(FBScounter).message  & "</a></li>"

3 Comments »

C# dot net code to get latest tweets using twitter API 1.1

Twitter just recently retired their old API 1.0. The new API requires oAuth. Following code will help you jumpstart to write code in C# to get your tweets.

This is using dot net framework 4.0
I am also using NewtonSoft’s excellent JSON library. You can get it here. Use the dot net 4.0 library and add as a reference to your C# Web project.

You first have to create a twitter app here. Use the oAuth Tool tab to get the 4 tokens/codes that you will be replacing in the code below.


Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div id="myDiv" runat="server">
    
    </div>s
    </form>
</body>
</html>


Default.aspx.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Security.Cryptography;
using System.Net;
using System.IO;
using Newtonsoft.Json.Linq;


public partial class _Default : System.Web.UI.Page
{


    public string query = "umerpasha";
//    public string url = "https://api.twitter.com/1.1/users/search.json" ;
    public string url = "https://api.twitter.com/1.1/statuses/user_timeline.json" ;


    protected void Page_Load(object sender, EventArgs e)
    {
        findUserTwitter(url, query);
    }

    public void findUserTwitter(string resource_url, string q)
    {

        // oauth application keys
        var oauth_token = "xxx"; //"insert here...";
        var oauth_token_secret = "xxx"; //"insert here...";
        var oauth_consumer_key = "xxx";// = "insert here...";
        var oauth_consumer_secret = "xxx";// = "insert here...";

        // oauth implementation details
        var oauth_version = "1.0";
        var oauth_signature_method = "HMAC-SHA1";

        // unique request details
        var oauth_nonce = Convert.ToBase64String(new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
        var timeSpan = DateTime.UtcNow
            - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
        var oauth_timestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();


        // create oauth signature
        var baseFormat = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" +
                        "&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}&q={6}";

        var baseString = string.Format(baseFormat,
                                    oauth_consumer_key,
                                    oauth_nonce,
                                    oauth_signature_method,
                                    oauth_timestamp,
                                    oauth_token,
                                    oauth_version,
                                    Uri.EscapeDataString(q)
                                    );

        baseString = string.Concat("GET&", Uri.EscapeDataString(resource_url), "&", Uri.EscapeDataString(baseString));

        var compositeKey = string.Concat(Uri.EscapeDataString(oauth_consumer_secret),
                                "&", Uri.EscapeDataString(oauth_token_secret));

        string oauth_signature;
        using (HMACSHA1 hasher = new HMACSHA1(ASCIIEncoding.ASCII.GetBytes(compositeKey)))
        {
            oauth_signature = Convert.ToBase64String(
                hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes(baseString)));
        }

        // create the request header
        var headerFormat = "OAuth oauth_nonce=\"{0}\", oauth_signature_method=\"{1}\", " +
                           "oauth_timestamp=\"{2}\", oauth_consumer_key=\"{3}\", " +
                           "oauth_token=\"{4}\", oauth_signature=\"{5}\", " +
                           "oauth_version=\"{6}\"";

        var authHeader = string.Format(headerFormat,
                                Uri.EscapeDataString(oauth_nonce),
                                Uri.EscapeDataString(oauth_signature_method),
                                Uri.EscapeDataString(oauth_timestamp),
                                Uri.EscapeDataString(oauth_consumer_key),
                                Uri.EscapeDataString(oauth_token),
                                Uri.EscapeDataString(oauth_signature),
                                Uri.EscapeDataString(oauth_version)
                        );



        ServicePointManager.Expect100Continue = false;

        // make the request
        var postBody = "q=" + Uri.EscapeDataString(q);//
        resource_url += "?" + postBody ;
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(resource_url);
        request.Headers.Add("Authorization", authHeader);
        request.Method = "GET";
        request.ContentType = "application/x-www-form-urlencoded";
        var response = (HttpWebResponse)request.GetResponse();
        var reader = new StreamReader(response.GetResponseStream());
        var objText = reader.ReadToEnd();
        myDiv.InnerHtml = objText;/**/
        string html = "";
        try
        {
            JArray jsonDat = JArray.Parse(objText);
            for (int x = 0; x < jsonDat.Count(); x++)
            {
                //html += jsonDat[x]["id"].ToString() + "<br/>";
                html += jsonDat[x]["text"].ToString() + "<br/>";
               // html += jsonDat[x]["name"].ToString() + "<br/>";
                html += jsonDat[x]["created_at"].ToString() + "<br/>";

            }
            myDiv.InnerHtml = html;
        }
        catch (Exception twit_error)
        {
            myDiv.InnerHtml = html + twit_error.ToString();
        }
    }
}
98 Comments »

jQuery to change size of the Promoted Links in Sharepoint 2013

Sharepoint 2013 comes with standard Metro UI links app called “Promoted Links”. I will not go into how to set them up as you can google it and find various resources for that.

I was trying to put in two strips of promoted links and also wanted the second strip to be smaller than the first giving it a feel of a sub-menu. Coincidentally, there is no out of the box way of doing that. The images seemed to be scaled to 150px fixed.

So I added in a little bit of jQuery to resize them.

Here is the code that goes into a content editor webpart on the same page. Please change the path to your jQuery library reference. Change the image size you want. Change the WPQ number of the promoted link. You can find it by using developer tools on your browser hitting F12. Look for “promotedlinksbody_WPQ” :

<!--JQuery script to make promoted links any size. Also shifts to 2nd row if more than specified tiles. Author: Umer Pasha , Date: 3/15/2013-->

<script type="text/javascript" src="/scripts/jquery/jquery-1.8.1.min.js"></script>


<script language="javascript">
$(document).ready(function () {
 
// Update this value to the number of links you want to show per row
var numberOfLinksPerRow = 10;

// Set Image Size 
var ImageSize = "76";

// in case we have multiple promoted links on page, name the WPQ here
var promotedlinksbody_WPQ = "4";
 
// local variables
var pre = "<tr><td><div class='ms-promlink-body' id='promlink_row_";
var post = "'></div></td></tr>";
var numberOfLinksInCurrentRow = numberOfLinksPerRow;
var currentRow = 1;
// find the number of promoted links we're displaying

var numberOfPromotedLinks = $('#promotedlinksbody_WPQ' + promotedlinksbody_WPQ + ' > .ms-tileview-tile-root').length;
//var numberOfPromotedLinks = $('.ms-promlink-body > .ms-tileview-tile-root').length;

  // if we have more links then we want in a row, let's continue
  if (numberOfPromotedLinks > numberOfLinksPerRow) {
    // we don't need the header anymore, no cycling through links
    $('.ms-promlink-root > .ms-promlink-header').empty();
    // let's iterate through all the links after the maximum displayed link
    for (i = numberOfLinksPerRow + 1; i <= numberOfPromotedLinks; i++) {


      // if we're reached the maximum number of links to show per row, add a new row
      // this happens the first time, with the values set initially
      if (numberOfLinksInCurrentRow == numberOfLinksPerRow) {
        // i just want the 2nd row to
        currentRow++;

 
        // create a new row of links
        $('.ms-promlink-root > table > tbody:last').append(pre + currentRow + post);
        // reset the number of links for the current row
        numberOfLinksInCurrentRow = 0


    }
    

    // move the Nth (numberOfLinksPerRow + 1) div to the current table row
    $('.ms-promlink-body > .ms-tileview-tile-root:nth-child(' + (numberOfLinksPerRow + 1) + ')').appendTo($('#promlink_row_' + currentRow));
    // increment the number of links in the current row
    numberOfLinksInCurrentRow++;

  }
}


	// Set the size of main promoted links body
	var ControlID='promotedlinksbody_WPQ';
	ControlID=ControlID + promotedlinksbody_WPQ;
	$("#" + ControlID).height(ImageSize);
	
	// iterate through each link and set the size
    for (i = 1; i <= numberOfPromotedLinks; i++) {
        
		ControlID='Tile_WPQ' + promotedlinksbody_WPQ + '_' + i ;
		ControlID= ControlID + '_1';
    	$("#" + ControlID).width(ImageSize);
    	$("#" + ControlID).height(ImageSize);
		
		ControlID='Tile_WPQ' + promotedlinksbody_WPQ + '_' + i ;
		ControlID= ControlID + '_2';
    	$("#" + ControlID).width(ImageSize);
    	$("#" + ControlID).height(ImageSize);

		ControlID='Tile_WPQ' + promotedlinksbody_WPQ + '_' + i ;
		ControlID= ControlID + '_7';
    	$("#" + ControlID).width(ImageSize);
		
		ControlID='Tile_WPQ' + promotedlinksbody_WPQ + '_' + i ;
		ControlID= ControlID + '_4';
    	$("#" + ControlID).width(ImageSize);
    	$("#" + ControlID).height(ImageSize);
    	
    	
		ControlID='Tile_WPQ' + promotedlinksbody_WPQ + '_' + i ;
		ControlID= ControlID + '_4';
    	$("#" + ControlID).width(ImageSize);
    	$("#" + ControlID).height(ImageSize);
    	//$("#" + ControlID).top(ImageSize);

	}

	ControlID="promotedlinksheader_WPQ" + promotedlinksbody_WPQ;
	$("#" + ControlID).hide();


});

</script>

Image

 

I am putting the javascript above in a .js file and putting the link to the .js file in a content editor. The content editor is on the same page as the promoted links.

smallPL1

These are the paths to the online vector icons I am using:

http://modernuiicons.com/icons/svg/appbar.reply.calendar.svg
http://modernuiicons.com/icons/svg/appbar.money.svg
http://modernuiicons.com/icons/svg/appbar.man.suitcase.svg
http://modernuiicons.com/icons/svg/appbar.calendar.14.svg
http://modernuiicons.com/icons/svg/appbar.calendar.svg
http://modernuiicons.com/icons/svg/appbar.places.svg

Here is the link to the .js file. Please rename to .js:   Link

 

74 Comments »

jQuery append, prepend, before, after functions for inserting rows in HTML table

I have been using jQuery extensively for the past couple of years or so. Mostly to add visual effects to my own site at http://www.umerpasha.com.

Unfortunately, due to shortcomings of Microsoft Sharepoint that my client uses as a portal builder, a lot of patchwork needs to be done on forms using jQuery as well. Mostly, it works well for cross-browser compatibility so I hardly check for cross-browser compatibility when working with Sharepoint/jQuery mostly because the portal is on an intranet and IE is the preferred browser for sharepoint anyway. In this particular case, they needed certain pages for public viewing pertaining to a show/event.

I have been using jQuery to insert rows at will between sharepoint edit forms to put in labels and headings and to change the look and feel of the form if required. I have always used append and prepend jQuery functions to do that.

So to add a heading “About You” after a certain textbox I will put in:
var str = ‘<tr><td width=”190″ class=”ms-formlabel” noWrap=”nowrap” vAlign=”top” ><FONT Color=”Red”>ABOUT YOU</FONT></td><td width=”400″ class=”ms-formbody” vAlign=”top”><span dir=”none”><input type=”hidden” name=”lblAboutYou” title=”lblAboutYou” class=”ms-long” id=”lblAboutYou”  /></td></tr>’;
$(‘input[title=StudentID]’).parent().parent().parent().append(str);

To add a heading after a certain textbox I will use “append” the same way.

So it turns out what “append” does is, APPEND (duh!) the HTML text WITHIN the TR tag. So in the following example, if I want to add a TR with id=3, i used to write the above code to insert row 3, finding row 2 and appending it.

<TR id=1>…</TR>
<TR id=2>…</TR>
<TR id=4>…</TR>

Turns out, this is WRONG! What is needed is this:
<TR id=1>…</TR>
<TR id=2>…</TR>
<TR id=3>…</TR>
<TR id=4>…</TR>

What actually happens is this:

<TR id=1>…</TR>
<TR id=2>… … … .. .  <TR id=3>…</TR>  </TR>
<TR id=4>…</TR>

 

As you can see, the new row is BETWEEN the TR tags of row 2. I never noticed this because of….. drumroll please….. IE!!! (Isn’t it always the case?????)

1. IE forgives you for having a totally blasphemous structure like above! It treats TR 3 as a separate row.

2. If you turn on “Inspect” tool (using F12) in IE, it freakin’ does not show you the ending tags!!!

So because of those 2 reasons I never got to know what monster i was creating!

So I create the page using the above wrong code and it messes up in firefox and chrome big time. No fault of jQuery though. Append is doing what it should…. APPENDING it!

So if you are in such a rut…. use jQuery functions “AFTER” and “BEFORE”.

Here is the correct code using the same str variable value as above and reaching the parent TR:

$(‘input[title=Name]’).parent().parent().parent().parent().after(str);

<TR id=1>…</TR>
<TR id=2>…</TR>
<TR id=3>…</TR>
<TR id=4>…</TR>

Leave a comment »