About Me

My photo
Northglenn, Colorado, United States
I'm primarily a BI Developer on the Microsoft stack. I do sometimes touch upon other Microsoft stacks ( web development, application development, and sql server development).

Tuesday, September 25, 2012

Facebook comments button using jquery

 So, as my offical first try at jquery, I created a facebook button that can be used to display facebook comments.

HTML5 Code:

<!DOCTYPE html>
<html>
<head>
<title>Facebook Comments Test</title>
<link href="StyleSheet.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src=http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.0.js>
</script>
<script type="text/javascript">
  $(document).ready(function () {
    $("#facebookButton").click(function () {
       if ($("#rightFacebook").is(":visible")){
          $("#rightFacebook").hide(1000);
       }
       
else {
          $("#rightFacebook").show(1000);
       }
    });
  });
 
<
/script>
</head>
<body>

<div id="fb-root"></div>
<script type="text/javascript">    (function (d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return;
  js = d.createElement(s); js.id = id;
  js.src =
"//connect.facebook.net/en_US/all.js#xfbml=1";
  fjs.parentNode.insertBefore(js, fjs);
} (document,
'script', 'facebook-jssdk'));
</script>
<h1>Popular Page</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur vitae velit magna. Vivamus nec eros ac ante auctor porta id in velit. Aenean sit amet metus eget tellus dignissim dignissim ac at metus. Maecenas sagittis lectus eu nibh porta non ornare mauris fermentum. Vestibulum vel mi id nibh sagittis gravida. Phasellus ac orci eu ante consequat convallis. Pellentesque ultrices tincidunt dignissim. Phasellus porttitor ornare nisi, in faucibus nisl ornare ornare.</p>

<p>Vivamus ac ultricies mi. Nulla facilisi. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Maecenas urna nibh, interdum eu aliquet quis, molestie ut elit. Maecenas sed arcu ullamcorper lectus consectetur placerat quis at mi. Fusce nisi dui, rutrum quis euismod a, euismod ac justo. Mauris congue blandit sapien, sed aliquet est interdum a. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p>

<p>Nulla a justo id nisl fringilla iaculis. Quisque mollis ipsum in tortor convallis nec commodo massa faucibus. Nullam eget neque nibh, commodo euismod turpis. Nunc quis lobortis augue. Duis interdum commodo nisl, et bibendum mauris congue vitae. Phasellus dignissim fermentum dolor, vel tempus nisi faucibus sed. Curabitur cursus faucibus eros, quis elementum ipsum feugiat quis. Vivamus at sem massa. Pellentesque risus sem, euismod non elementum bibendum, aliquam ac elit.<p>

<p>Nunc lacinia consectetur arcu, nec vestibulum nulla rutrum vel. Quisque sem quam, congue eget molestie sit amet, rhoncus non risus. Aliquam erat volutpat. Nunc vitae feugiat elit. Sed pretium tincidunt lectus, sit amet posuere turpis consequat consectetur. Quisque vel sodales sapien. Quisque tincidunt, augue ut mattis lobortis, eros purus fringilla ante, vitae congue lorem sem eget purus. Phasellus nunc quam, consequat vel fermentum ultrices, sollicitudin sit amet turpis. Vivamus sagittis vehicula tortor.</p>

<p>Donec ut ligula lacus, non fermentum dui. Ut vel ipsum ante. Praesent consequat metus eget eros porttitor vulputate. Fusce tellus lacus, convallis eget tincidunt sit amet, pretium vitae leo. Etiam interdum magna egestas massa feugiat vel ornare elit hendrerit. Etiam id eros sem, ac rhoncus ante. Etiam tellus dui, pretium non commodo nec, pharetra et dui. Suspendisse quis dolor quis magna iaculis suscipit. Nullam fermentum iaculis malesuada.</p>

<div id="rightFacebook">
   <div class="fb-comments" data-href="http://example.com" data-num-posts="2" data-width="470"></div>
</div>
   <button id="facebookButton">
      <img id="facebookButtonImage" alt="facebook comments" src="facebook.png"/>
   </button>
   
</body>
</html>



CSS Code:
div#rightFacebook{
   float: right;
   position:fixed;
   right:20px;
   top: 5px;
   width: 500px;
   background-color: #FFFFDB;
   margin-bottom: 0.5em;
   display:none;
}

button#facebookButton
{
   float: right;    position:fixed;
   right:10px;
   top: 5px;
}
img#facebookButtonImage
{
  width:15px;
  height:15px
}


p#facebookButtonText
{

   font-family:Tahoma;
   font-size:10px;
}



Explaination:

I used this script so, that I didn't have to download the jquery library. Instead I used Microsofts, which can slow things down if not local.
<script type="text/javascript" src=http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.0.js>
</script>

My jquery script, short and simple. If the button was clicked, then I check if my facebook comments are visible/invisible and then hide/show. I gave it 1 second animation when it hides/shows the comments:

<script type="text/javascript">
    $(document).ready(function () {
       $("#facebookButton").click(function () {
          if ($("#rightFacebook").is(":visible")){
             $("#rightFacebook").hide(1000);
          }
         
else {
             $("#rightFacebook").show(1000);
          }
      });
   });   
<
/script>


Facebook gives code to allow you to adjust what page the comments are for, number of posts, width, and color scheme. (http://developers.facebook.com/docs/reference/plugins/comments/)
The first section of code they give, basically the connection to facebook:

<div id="fb-root"></div>
<script type="text/javascript"> (function (d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src =
"//connect.facebook.net/en_US/all.js#xfbml=1";
fjs.parentNode.insertBefore(js, fjs);
} (document,
'script', 'facebook-jssdk'));
</script>

The second code grab are the attributes you filled out on the website, which can easily be adjusted:

<div class="fb-comments" data-href="http://example.com" data-num-posts="2" data-width="470"></div>
 
I placed the second grab in my div, where I wanted the comments to be displayed:

<div id="rightFacebook">
    <div class="fb-comments" data-href="http://example.com" data-num-posts="2" data-width="470"></div>
</div>
<button id="facebookButton">
    <img id="facebookButtonImage" alt="facebook comments" src="facebook.png"/>
</button>

I stole a facebook icon, facebook.png, and used that as my button. In the CSS, I made sure that my button and comments are always in the upper-right hand corner, even when the page is scrolling.




Hidden:
Displayed:
 
Scrolling:



 
 

Tuesday, August 14, 2012

First StreamInsight attempt using Performance Counter

As my first attempt with StreamInsight, I decided to use the Performance Counter as my stream of data. Here is a brief overview of implementing the StreamInsight portion

3 important downloads to get started, with StreamInsight:

Download Reactive: http://www.microsoft.com/en-us/download/confirmation.aspx?id=28568
Download Examples: http://streaminsight.codeplex.com/releases/view/90143


First I created an class to represent the data I wanted to capture in my stream. Not all data types can be used with StreamInsight (ie: enum). Here is a list of supported data types: http://msdn.microsoft.com/en-us/library/ee378905.aspx

Code Snippet
  1. // Input events of CounterSample of supported data types
  2. public class StreamableCounterSample
  3. {
  4.     public float CpuUtilization { get; set; }
  5.     public long TimeStamp { get; set; }
  6. }


The main portion of the program.
Here starting on line 86, I create my StreamInsight server embedded in memory. The server name is the instance name that you give after installing StreamInsight. With StreamInsight 2.1, they added IQStreamable which allows you to query the stream. Lines 104 & 105 is when the stream will be queried for the results.
Code Snippet
  1. private float CalculatePerformance(BackgroundWorker worker, DoWorkEventArgs e)
  2. {
  3.     CreateCounters();
  4.  
  5.     //embedded (in-memory)
  6.     using (Server server = Server.Create("StreamInsight21"))
  7.     {
  8.         Microsoft.ComplexEventProcessing.Application application = server.CreateApplication("app");
  9.  
  10.         //A query for reading events from a stream
  11.         IQStreamable<StreamableCounterSample> inputStream = null;
  12.  
  13.         inputStream = CreateStream(application);
  14.  
  15.         while (true)
  16.         {
  17.             if (worker.CancellationPending)
  18.             {
  19.                 e.Cancel = true;
  20.                 break;
  21.             }
  22.             else
  23.             {
  24.                 perf = inputStream.ToObservable().ToEnumerable().Last().CpuUtilization;
  25.                 timestamp = DateTime.FromFileTime(inputStream.ToObservable().ToEnumerable().Last().TimeStamp);
  26.                 worker.ReportProgress((int)perf);
  27.             }
  28.         }
  29.  
  30.         return inputStream.ToObservable().ToEnumerable().Last().CpuUtilization;
  31.  
  32.     }
  33. }


When creating the stream in line 93, I'm setting up my observation. In this case CollectSamples is my source which is then converted to a temporal stream via ToPointStreamable, which inserts a single event instance with a datetime.

Code Snippet
  1. static IQStreamable<StreamableCounterSample> CreateStream(Microsoft.ComplexEventProcessing.Application application)
  2. {
  3.     // Live data uses IQbservable<>
  4.     return
  5.         application.DefineObservable(() => CollectSamples()).ToPointStreamable(
  6.         r => PointEvent<StreamableCounterSample>.CreateInsert(DateTime.Now, r),
  7.         AdvanceTimeSettings.StrictlyIncreasingStartTime);
  8. }


The collect samples, is where my data will be pulled. In this case I'm pulling my data from the performance counter, but returning an observable interval representing this temporal event that occurs every 1 second.
Code Snippet
  1. private static IObservable<StreamableCounterSample> CollectSamples()
  2. {
  3.     List<StreamableCounterSample> data = new List<StreamableCounterSample>();
  4.     
  5.     data.Add(new StreamableCounterSample
  6.     {
  7.         CpuUtilization = perfCounter.NextValue(),
  8.         TimeStamp = DateTime.Now.ToFileTime()
  9.     });
  10.  
  11.     return ToObservableInterval(data, TimeSpan.FromMilliseconds(1000), Scheduler.ThreadPool);
  12. }


Code Snippet
  1. private static IObservable ToObservableInterval(IEnumerable source, TimeSpan period, IScheduler scheduler)
  2. {
  3.     return Observable.Using(
  4.         () => source.GetEnumerator(),
  5.         it => Observable.Generate(
  6.             default(object),
  7.             _ => it.MoveNext(),
  8.             _ => _,
  9.             _ =>
  10.             {
  11.                 //Console.WriteLine("Input {0}", it.Current);
  12.                 return it.Current;
  13.             },
  14.             _ => period, scheduler));
  15. }


In the end, the final product is a simple winform showing the current CPU Utilization and the last time it ran.


The program can be downloaded from:

Monday, July 09, 2012

SQL-Server Query to get blocking information

A useful query to get the blocking information within SQL-Server:

SELECT
tr1.resource_type,
tr1.resource_subtype,
tr1.resource_database_id,
tr1.resource_associated_entity_id,
tr1.request_mode,
tr1.request_type,
tr1.request_status,
tr1.request_session_id,
tr1.request_owner_type,
tr2.blocking_session_id
FROM sys.dm_tran_locks as tr1
INNER JOIN sys.dm_os_waiting_tasks as tr2 ON tr1.lock_owner_address = tr2.resource_address;

-Source: Microsoft SQL Server 2012 - Pocket Consultant by William R. Stanek

Tuesday, April 03, 2012

Quick Tip: Importing images into a database from SSIS


To have SSIS upload to the database, in your data flow task, add a "Import Column". Set the "Input Columns" as the image file path, and the "Output Columns" as a image datatype. In SQL-Server, the field just needs to be an "image" type, when doing a data flow destination.












Thursday, March 08, 2012

View overall I/O statistics for all databases in your server

A sql script to find the I/O statistics for all databases on the server. This can be helpful for
"drafting a server consolidation strategy, or pointing to eventual need to check perf counters if I/O is waiting more than expected"
- From "Blog do Ezequiel" http://blogs.msdn.com/b/blogdoezequiel/archive/2012/03/08/the-sql-swiss-army-knife-3-view-i-o-per-file-updated.aspx
Code Snippet
-- 2012-03-08 Pedro Lopes (Microsoft) pedro.lopes@microsoft.com (http://blogs.msdn.com/b/blogdoezequiel/)
--
-- Checks the cumulative IO per database file and related information
--
SELECT f.database_id, DB_NAME(f.database_id) AS database_name, f.name AS logical_file_name, f.[file_id], f.type_desc,
    CAST (CASE
        -- Handle UNC paths (e.g. '\\fileserver\readonlydbs\dept_dw.ndf')
        WHEN LEFT (LTRIM (f.physical_name), 2) = '\\'
            THEN LEFT (LTRIM (f.physical_name),CHARINDEX('\',LTRIM(f.physical_name),CHARINDEX('\',LTRIM(f.physical_name), 3) + 1) - 1)
            -- Handle local paths (e.g. 'C:\Program Files\...\master.mdf')
            WHEN CHARINDEX('\', LTRIM(f.physical_name), 3) > 0
            THEN UPPER(LEFT(LTRIM(f.physical_name), CHARINDEX ('\', LTRIM(f.physical_name), 3) - 1))
        ELSE f.physical_name
    END AS NVARCHAR(255)) AS logical_disk,
    fs.size_on_disk_bytes/1024/1024 AS size_on_disk_Mbytes,
    fs.num_of_reads, fs.num_of_writes,
    fs.num_of_bytes_read/1024/1024 AS num_of_Mbytes_read,
    fs.num_of_bytes_written/1024/1024 AS num_of_Mbytes_written,
    fs.io_stall/1000/60 AS io_stall_min,
    fs.io_stall_read_ms/1000/60 AS io_stall_read_min,
    fs.io_stall_write_ms/1000/60 AS io_stall_write_min,
    ((fs.io_stall_read_ms/1000/60)*100)/(CASE WHEN fs.io_stall/1000/60 = 0 THEN 1 ELSE fs.io_stall/1000/60 END) AS io_stall_read_pct,
    ((fs.io_stall_write_ms/1000/60)*100)/(CASE WHEN fs.io_stall/1000/60 = 0 THEN 1 ELSE fs.io_stall/1000/60 END) AS io_stall_write_pct,
    ABS((sample_ms/1000)/60/60) AS 'sample_HH',
    ((fs.io_stall/1000/60)*100)/(ABS((sample_ms/1000)/60))AS 'io_stall_pct_of_overall_sample'
FROM sys.dm_io_virtual_file_stats (default, default) AS fs
INNER JOIN sys.master_files AS f ON fs.database_id = f.database_id AND fs.[file_id] = f.[file_id]
ORDER BY 18 DESC