Tuesday, May 12, 2020

Zoom - Suggested Default Admin settings

This video explains default admin settings, with respect to privacy & security, for a Zoom account holder.

Please watch the full video here:

Monday, May 11, 2020

Zoom - Securing your LIVE stream recording on Youtube

This video explains how to secure recordings of your LIVE streamed meeting from Zoom.

Please watch the full video here:

Friday, May 8, 2020

Zoom - Hosting a meeting, Best practices as Host and Security options for Meeting Host

This video will explain how to host a meeting, what are the best practices as a Host and what Security options a Meeting Host have.

References used in this video:

1️⃣ Host a quick Video Meeting: https://support.zoom.us/hc/en-us/articles/201362613-How-Do-I-Host-A-Video-Meeting-
2️⃣ Schedule a meeting: https://support.zoom.us/hc/en-us/articles/201362413-Scheduling-meetings
3️⃣ Schedule a Recurring/Repeated Meetings: https://support.zoom.us/hc/en-us/articles/214973206-Scheduling-Recurring-Meetings
4️⃣ Meeting templates, save the settings for a meeting as a template and reuse the settings while creating a new meeting of similar type (e.g. Monthly Status Meeting): https://support.zoom.us/hc/en-us/articles/360036559151-Meeting-templates
5️⃣ Sharing your screen during meeting: https://support.zoom.us/hc/en-us/articles/201362153-Sharing-your-screen
6️⃣ Virtual Background: https://support.zoom.us/hc/en-us/articles/210707503-Virtual-Background
7️⃣ Nonverbal Feedback During Meetings: https://support.zoom.us/hc/en-us/articles/115001286183-Nonverbal-Feedback-During-Meetings
8️⃣ In-Meeting Chat: https://support.zoom.us/hc/en-us/articles/203650445-In-Meeting-Chat
9️⃣ Breakout rooms, split the participants of the meeting into multiple separate sessions: https://support.zoom.us/hc/en-us/articles/206476093-Enabling-breakout-rooms#h_9285303e-c6b2-46d6-96af-59c5bb206448


Please watch the full video here:

Thursday, May 7, 2020

Zoom - Joining a Zoom Meeting as a Participant

This video will explain how to join a Zoom Meeting as a Participant and what best practices we should follow. References used in this video: Joining a Zoom Meeting: https://support.zoom.us/hc/en-us/articles/201362193-Joining-a-Meeting Joining a test meeting: https://support.zoom.us/hc/en-us/articles/115002262083-Joining-a-test-meeting

Please watch the full video here:

Wednesday, May 6, 2020

Zoom - Live stream on Youtube

This video will explain how to stream live on YouTube from a Zoom meeting.

Other References:
Streaming a Meeting or Webinar on YouTube Live: https://support.zoom.us/hc/en-us/articles/360028478292-Streaming-a-Meeting-or-Webinar-on-YouTube-Live

Please watch the full video here:

Zoom - Licenses and Payment options

This video gives explains various Licenses and Payment options in Zoom Application - A recently became popular Video Conferencing Application. References used in this video: Zoom Meeting Plans & Pricing: https://zoom.us/pricing Zoom Payment Methods: https://support.zoom.us/hc/en-us/sections/201728983-Payment-Methods Zoom Accept PayPal: https://support.zoom.us/hc/en-us/articles/207583123-Does-Zoom-Accept-PayPal- Add a debit or credit card to my PayPal account: https://www.paypal.com/in/smarthelp/article/faq826

Please watch the full video here:

Introduction to Zoom Video Conferencing Application

This video gives basic introduction of Zoom Application - A recently became popular Video Conferencing Application.

Please watch the full video here:



Wednesday, April 27, 2016

Difference between Angular 1.x and Angular 2

Angular 2 is still in beta (at the time of writing this post), but it has already created a buzz in community. Angular 2 will be a huge learning curve for developers. It is written entirely in Typescript and meets the ES6 specification. And it’s not an update for Angular 1.x. As it’s rewritten and includes breaking changes. So the best way to learn is to compare with Angular 1.x and find out what’s new in Angular 2. In this post, find out difference between Angular 1.x and Angular 2.

Difference between Angular 1.x and Angular 2

  • Angular 1.x was not built with mobile support in mind, where Angular 2 is mobile oriented.
  • Angular 2 provides more choice for languages. You can use any of the language from ES5, ES6, TypeScript or Dart to write Angular 2 code. Where, Angular 1.x has ES5, ES6 and Dart. Addition of TypeScript is a great step as TypeScript is awesome way to write JavaScript. 
  • Angular 1.x controllers and $scope are gone. We can say that controllers are replaced with “Components” in Angular 2. Angular 2 is component based.
    Angular 1.x Controller
    var myApp = angular
       .module("myModule", [])
       .controller("productController", function($scope) {
         var prods = { name: "Prod1", quantity: 1 };
         $scope.products = prods;
    }); 
    
    Angular 2 Components using TypeScript
    import { Component } from 'angular2/core';
    
    @Component({
      selector: 'prodsdata',
      template: `
        <h3>{{prods.name}}</h3> `
    })
    
    export class ProductComponent {
      prods = {  name: 'Prod1', quantity: 1 };
    }
    
    Notice, there is a class with export keyword, @Component annotation (that’s also new in Angular 2). The @Component annotation adds the metadata to the class.
  • Angular 1.x has 2 ways to bootstrap angular. One using ng-app attribute and other via code.
    <script>
       angular.element(document).ready(function() {
          angular.bootstrap(document, ['myApp']);
       });
    </script>
    
    In Angular 2, say goodbye to ng-app. The only way to bootstrap angular is via code.
      import { bootstrap } from 'angular2/platform/browser';
      import { ProductComponent } from './product.component';
    
      bootstrap(ProductComponent);
    
    The bootstrap function is used and it takes starting component which is also parent component of your angular application.
  • Structural directives syntax is changed. ng-repeat is replaced with *ngFor.
    Angular 1.x structural directives
    <ul>
       <li ng-repeat="technology in technologies">
         {{technology.name}}
       </li>
    </ul>
    <div ng-if="technologies.length">
       <h3>You have {{technologies.length}} technologies.</h3>
    </div>
    
    Angular 2 structural directives
    <ul>
      <li *ngFor="#technology of technologies">
        {{technology.name}}
      </li>
    </ul>
    <div *ngIf="technologies.length">
      <h3>You have {{technologies.length}} technologies.</h3>
    </div>
    
    Notice that Asterisk(*) sign is used as prefix for structural directives, in is replaced with of and camelCase syntax is used.
  • In Angular 2, local variables are defined using hash(#) prefix (see above code for *ngFor).
  • To filter output in our templates in Angular 1.x, we use the pipe character (|) and one or more filters. Where in Angular 2 they are called pipes. The syntax remains same.
  • Angular 2 uses camelCase syntax for built-in directives. For example, ng-class is now ngClass and ng-model is now ngModel.
  • One of the major change in Angular 2 is, that it directly uses the valid HTML DOM element properties and events. Due to this, many of the available built-in directives in Angular 1.x are now no longer required. Like, ng-href, ng-src, ng-show and ng-hide. Angular 2 uses href, src and hiddenproperties to get the same output. And same goes with event based directives like ng-click and ng-blur.
    <button ng-click="doSomething()">
    
    And in Angular 2, take the HTML event and wrap it with parentheses.
    <button (click)="doSomething()">
    
  • In Angular 1.x, ng-bind is used for one way data binding, but with Angular 2 it is replaced with [property], where property is valid HTML DOM element property.
    Angular 1.x, one way data binding
    <input ng-bind="technology.name"></input>
    
    Angular 2, one way data binding is achieved via wrapping the properties with square brackets.
    <input [value]="technology.name"></input>
    <div [style.color]="color">Some text...</div>
    
    Remember for events, parentheses is used and for properties, square brackets are used.
  • In Angular 1.x, ng-model is used for two way data binding, but with Angular 2 it is replaced with [(ngModel)].
    Angular 1.x, two way data binding
    <input ng-model="technology.name"></input>
    
    In Angular 2,
    <input [(ngModel)]="technology.name"></input>
    
  • In Angular 1.x, we can define a service via 5 different ways.
    • Factory
    • Service
    • Provider
    • Constant
    • Values
    And in Angular 2, class is the only way to define a service.
    import { Injectable } from 'angular2/core';
    
    @Injectable()
    export class TechnologyService {
      getTechnologies() {
        return [
          new technology(1, 'Angular'),
          new technology(2, 'jQuery',
          new technology(3, 'Node'),
          new technology(4, 'Knockout')
        ];
      }
    }
    
    And once defined, you need to register it with your main component usingprovider.
    import { Component } from 'angular2/core';
    import { TechnologyService } from './character.service';
    
    @Component({
      selector: 'my-app',
      template: '<technology-list></technology-list>',
      providers: [TechnologyService]
    })
    export class AppComponent {}
    
  • One of the advantage of Angular is Dependency Injection. With Angular 2 DI is there but now there is a different way to inject dependencies. As everything is class in Angular, so DI is achieve via constructor.
    var myApp = angular
       .module("myModule", [])
       .controller("productController", function($scope, $http) {
         var prods = { name: "Prod1", quantity: 1 };
         $scope.products = prods;
    }); 
    
    In Angular 2,
    import { Injectable } from 'angular2/core';
    
    @Injectable()
    export class TechnologyService {
      constructor(private _http: Http) { }
    
      getTechnologies() {
        return [
          new technology(1, 'Angular'),
          new technology(2, 'jQuery',
          new technology(3, 'Node'),
          new technology(4, 'Knockout')
        ];
      }
    }
    
    Notice, @Injectable() is added to service class. It is similar to Angluar 1.x$inject used for DI.
  • In Angular 1.x, we use $routeProvider.when() to configuring routing. Where in Angular 2, @RouteConfig{(...}) is used. ng-view present in Angular 1.x is replaced with <router-outlet>
    In Angular 1.x,
    var app = angular
            .module("MyModule", ["ngRoute"])
            .config(function ($routeProvider) { 
                $routeProvider 
                  .when("/home", { templateUrl: "home.html", controller: "homeController" })
                  .when("/technology", { templateUrl: "technology.html", controller: "technologyController" }) 
            })
           .controller("homeController", function ($scope) {
                $scope.message = "Home Page"; 
            })    
           .controller("technologyController", function ($scope) {
                 $scope.technologies = ["ASP.NET", "jQuery", "AngularJS", "JavaScript"]; 
           }) 
    
    In Angular 2,
    import { Component } from 'angular2/core';
    import { RouteConfig, ROUTER_DIRECTIVES, ROUTER_PROVIDERS } from 'angular2/router';
    import { TechnologyComponent } from './technology/technology.component';
    import { TechnologyService } from './Technology/Technology.service';
    
    @Component({
      selector: 'my-app',
      templateUrl: 'app/app.component.html',
      directives: [ROUTER_DIRECTIVES],
      providers: [
        ROUTER_PROVIDERS,
        TechnologyService
      ]
    })
    @RouteConfig([
      { path: '/home', name: 'Home', component: HomeComponent, useAsDefault: true },
      { path: '/technology', name: 'Technology', component: TechnologyComponent },
    ])
    export class AppComponent { }
    
    Routing is a separate module that’s why need to import it. And 2 more configurations needs to be to make routing work, one is adding[ROUTER_DIRECTIVES] as directive and other is to add ROUTER_DIRECTIVES in providers list. And in HTML page,
    <ul>
      <li><a [routerLink]="['Home']" href="">Home</a></li>
      <li><a [routerLink]="['Technology']" href="">Technology</a></li>
    </ul>
    
    ng-href is also replaced by [routerLink]
  • Angular 2 implements webstandards like components and it’s provide better performance than Angular 1.
Summary
Angular 2 is a really big step forward. And it certainly requires some efforts to migrate from Angular 1 to Angular 2. But it is in the right direction. Things are looking better and more inline with HTML. It is still in beta but eagerly waiting for the final release.

Monday, April 18, 2016

Run Inline Scripts And External JS with Content Security Policy

“In general, CSP works as a black/whitelisting mechanism for resources loaded or executed by your extensions. Defining a reasonable policy for your extension enables you to carefully consider the resources that your extension requires, and to ask the browser to ensure that those are the only resources your extension has access to. These policies provide security over and above the host permissions your extension requests; they're an additional layer of protection, not a replacement.”

To set content security policy add following meta tag in head
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'unsafe-inline' 'unsafe-eval'">

If we will use Content Security Policy then Inline JavaScript will not be executed. This restriction bans both inline <script> blocks and inline event handlers (e.g. <button onclick="...">).

For Whitelist Inline Scripts and External JS…

CSP Level 2 offers backward compatibility for inline scripts by allowing you to whitelist specific inline scripts using either a cryptographic nonce (number used once) or a hash. Although this may be cumbersome in practice, it is useful in a pinch.

To use a nonce, give your script tag a nonce attribute. Its value must match one in the list of trusted sources. For example

Add nonce in meta tag  (For Inline) :
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'unsafe-inline' 'unsafe-eval' 'nonce-EDNnf03nceIOfn39fn3e9h3sdfa'">

Add nonce attribute in script tags :
<script nonce="EDNnf03nceIOfn39fn3e9h3sdfa">
    alert('Hello, world.');
</script>

For External JS and Bundling JS we need to define Domain Name or CDN URL in Meta tag (We can define both also) :
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'unsafe-inline' http://xyz.com  https://ajax.googleapis.com 'unsafe-eval';style-src 'unsafe-inline' http://xyz.com  https://ajax.googleapis.com 'unsafe-eval'">

</script>
@Scripts.Render("~/bundles/bootstrap")

“It is better to take all Inline scripts into External JS and don’t use nonce and Instead use Domain URL for calling External JS. Because by using nonce any hacker can call Script Injection in Browser by using same nonce.”

For more details use this :
http://www.html5rocks.com/en/tutorials/security/content-security-policy/#source-whitelists

Wednesday, March 30, 2016

@Html.EnumDropDownListFor in MVC

For MVC v5.1 use Html.EnumDropDownListFor

        @Html.DropDownList("MyType", 
           Html.GetEnumSelectList(typeof(MyType)) , 
           "Select My Type", 
           new { @class = "form-control" })
    

For MVC v5 use EnumHelper

        @Html.DropDownList("MyType", 
           EnumHelper.GetSelectList(typeof(MyType)) , 
           "Select My Type", 
           new { @class = "form-control" })
    

For MVC >5 and lower

I rolled Rune's answer into an extension method:
        namespace MyApp.Common
        {
            public static class MyExtensions{
                public static SelectList ToSelectList(this TEnum enumObj)
                    where TEnum : struct, IComparable, IFormattable, IConvertible
                {
                    var values = from TEnum e in Enum.GetValues(typeof(TEnum))
                        select new { Id = e, Name = e.ToString() };
                    return new SelectList(values, "Id", "Name", enumObj);
                }
            }
        }
    
This allows you to write:
     ViewData["taskStatus"] = task.Status.ToSelectList();
    
by
using MyApp.Common

Alternatively:
Create a custom helper class and use Html.EnumDropDownListFor for all lower version MVC < 5.1 (i.e. 3.x, 4.x, 5.0). Here is the class code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Web.Mvc;
using System.Web.Mvc.Html;
/// 
/// Class ENUM Helper
/// 
public static class EnumHelper
{
    /// 
    /// The single empty item
    /// 
    private static readonly SelectListItem[] SingleEmptyItem = new[] { new SelectListItem { Text = string.Empty, Value = string.Empty } };
    /// 
    /// Gets the ENUM description.
    /// 
    /// The type of the ENUM.
    /// The value.
    /// ENUM Description
    public static string GetEnumDescription(TEnum value)
    {
        FieldInfo fi = value.GetType().GetField(value.ToString());
        DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
        if ((attributes != null) && (attributes.Length > 0))
        {
            return attributes[0].Description;
        }
        else
        {
            return value.ToString();
        }
    }
    /// 
    /// ENUMS the drop down list for.
    /// 
    /// The type of the model.
    /// The type of the ENUM.
    /// The HTML helper.
    /// The expression.
    /// MVC Html String
    public static MvcHtmlString EnumDropDownListFor(this HtmlHelper htmlHelper, Expression> expression)
    {
        return EnumDropDownListFor(htmlHelper, expression, null);
    }
    /// 
    /// ENUMS the drop down list for.
    /// 
    /// The type of the model.
    /// The type of the ENUM.
    /// The HTML helper.
    /// The expression.
    /// The HTML attributes.
    /// MVC Html String
    public static MvcHtmlString EnumDropDownListFor(this HtmlHelper htmlHelper, Expression> expression, object htmlAttributes)
    {
        ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
        Type enumType = GetNonNullableModelType(metadata);
        IEnumerable values = Enum.GetValues(enumType).Cast();
        IEnumerable items = from value in values
                                            select new SelectListItem
                                            {
                                                Text = GetEnumDescription(value),
                                                Value = value.ToString(),
                                                Selected = value.Equals(metadata.Model)
                                            };
        // If the enum is nullable, add an 'empty' item to the collection
        if (metadata.IsNullableValueType)
        {
            items = SingleEmptyItem.Concat(items);
        }
        return htmlHelper.DropDownListFor(expression, items, htmlAttributes);
    }
    /// 
    /// Gets the type of the non null-able model.
    /// 
    /// The model metadata.
    /// real Model Type
    private static Type GetNonNullableModelType(ModelMetadata modelMetadata)
    {
        Type realModelType = modelMetadata.ModelType;
        Type underlyingType = Nullable.GetUnderlyingType(realModelType);
        if (underlyingType != null)
        {
            realModelType = underlyingType;
        }
        return realModelType;
    }
}

Usage:

   @Html.EnumDropDownListFor(model => model.EnumProperty, "Select Enum", new { @class = "form-control", type = "text"})

Monday, February 22, 2016

jQuery cheatsheet

Thanks Abhinay Rathore for providing always up-to-date cheatsheet for jQuery API .

Check the up-to-date cheat sheet here.

jQuery - Coding Standards & Best Practices

These are some of the common standards and best practices for writing better code with jQuery . These standards do not cover JavaScript standards or best practices. Browse the jQuery Cheatsheet for API reference.

Thanks to Abhinay Rathore for such a good article.

The original article can be found Here.

Monday, November 16, 2015

How to use stored procedure with Entity Framework Code First

To learn about how we can use stored procedure with Entity framework code first, jalpesh vadgama has written a very good blog post here.

Thanks jalpesh vadgama.

Working with transaction in Entity Framework 6

In  any Relation database, maintaining integrity of database is very important and Transaction is one way of maintaining database integrity. When you have situation, where you need to insert data into multiple tables and if inserting a data in one of the table fails you should always rollback other inserts transaction becomes very useful. Same scenario can be occurred for update or delete operations. If transactions are not there you will be end up with lots of junk data in tables. Entity framework is one of most popular ORM in Microsoft.NET World. So in this post we are going to learn how we can use transactions with Entity Framework 6.

Read full article here by jalpesh vadgama.

How doing a case sensitive search in SQL Server?

Question: How doing a case sensitive search in SQL Server?
Answer:
If Column1 of Table1 has following values ‘CaseSearch, casesearch, CASESEARCH, CaSeSeArCh’, following statement will return you all the four records.
SELECT Column1FROM Table1WHERE Column1 = 'casesearch'
To make the query case sensitive and retrieve only one record (“casesearch”) from above query, the collation of the query needs to be changed as follows.
SELECT Column1FROM Table1WHERE Column1 COLLATE Latin1_General_CS_AS = 'casesearch'
Adding COLLATE Latin1_General_CS_AS makes the search case sensitive.
Default Collation of the SQL Server installation SQL_Latin1_General_CP1_CI_AS is not case sensitive.
To change the collation of the any column for any table permanently run following query.
ALTER TABLE Table1ALTER COLUMN Column1 VARCHAR(20)COLLATE Latin1_General_CS_AS
To know the collation of the column for any table run following Stored Procedure.
EXEC sp_help DatabaseName
Second results set above script will return you collation of database DatabaseName.
Thanks @PinalDave for the beautiful post.

Thursday, October 8, 2015

Some useful c# code snippets for visual studio users

Public Class - code snippet

(Code snippet for public class)
Many times we, visual studio users, use common code snippets (already available with visual studio setup) like for, if, class, prop etc...
Out of these class is used many times, an every time we need to prepend Public with generated class declaration. So to automate this here I have created a custom C# code snippet that generates code for class declaration along with Public :

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
 <CodeSnippet Format="1.0.0">
  <Header>
   <Title>pclass</Title>
   <Shortcut>pclass</Shortcut>
   <Description>Code snippet for public class</Description>
   <Author>Microsoft Corporation</Author>
   <SnippetTypes>
    <SnippetType>Expansion</SnippetType>
    <SnippetType>SurroundsWith</SnippetType>
   </SnippetTypes>
  </Header>
  <Snippet>
   <Declarations>
    <Literal>
     <ID>name</ID>
     <ToolTip>Class name</ToolTip>
     <Default>MyClass</Default>
    </Literal>
   </Declarations>
   <Code Language="csharp"><![CDATA[public class $name$
 {
  $selected$$end$
 }]]>
   </Code>
  </Snippet>
 </CodeSnippet>
</CodeSnippets>

Copy above code and save into a file with name - "pclass.snippet" at "%USERPROFILE%\Documents\My Projects\Code Snippets\Visual C#\My C# Code Snippets". After restarting visual studio in any C# class file, type pclass + tab and see the difference.

Property with matching name - code snippet

(Code snippet for property and backing field with matching name)
One more code snippet - propfull we use many times, an every time we need to change Property name and private variable name with generated class declaration, though we use the same name for both with prepending underscore(_). So to automate this here I have created a custom C# code snippet:

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
 <CodeSnippet Format="1.0.0">
  <Header>
   <Title>propmatchname</Title>
   <Shortcut>propmatchname</Shortcut>
   <Description>Code snippet for property and backing field with matching name</Description>
   <Author>Microsoft Corporation</Author>
   <SnippetTypes>
    <SnippetType>Expansion</SnippetType>
   </SnippetTypes>
  </Header>
  <Snippet>
   <Declarations>
    <Literal>
     <ID>type</ID>
     <ToolTip>Property type</ToolTip>
     <Default>int</Default>
    </Literal>
    <Literal>
     <ID>property</ID>
     <ToolTip>Property name</ToolTip>
     <Default>MyProperty</Default>
    </Literal>
   </Declarations>
   <Code Language="csharp"><![CDATA[private $type$ m_$property$;
 public $type$ $property$
 {
  get { return m_$property$;}
  set { m_$property$ = value;}
 }
 $end$]]>
   </Code>
  </Snippet>
 </CodeSnippet>
</CodeSnippets>

Copy above code and save into a file with name - "propmatchname.snippet" at "%USERPROFILE%\Documents\My Projects\Code Snippets\Visual C#\My C# Code Snippets". After restarting visual studio in any C# class file, type propmatchname + tab and see the difference. Now try to change either public property name OR private variable name. Both will be in sync.


Hope many visual studio users/developers love this.
Enjoy !!!

TSQL Query for Global Search in Database

Hello Friends,

          2 months back I was looking for a string saved in database from my application. Suddenly I found that the string value was not saved in expected SQL table. However the application-logs had no logs for any error raised by insert query.

          I was surprised and wondering where the hell my string value stored in database of approx. 15 GB of size and approx. 108 tables.

          Finally to help myself, I prepared a TSQL script that helps me to find a varchar-value among any table from a database. Later I extended the same script to support seeking multiple databases. 

          You just need to specify @Text_To_Search, @DBname and a flag - @Single_DB_Only to indicate whether to seek in single database OR all databases on the sql-server.

SET NOCOUNT OFF
GO

declare @Text_To_Search nvarchar(max)
declare @TableName nvarchar(max)
declare @ColName nvarchar(max)
declare @CMD nvarchar(max)
declare @DBname nvarchar(max)
declare @Single_DB_Only bit

 
set @Text_To_Search = 'SOMETHING'   -- Enter the Text here which you want to search
set @Single_DB_Only = 1     -- If @Single_DB_Only = 0 then the search will be in only one database
if @Single_DB_Only = 1
 set @DBname = 'MY_DATABASE'    -- Enter Database Name in which you want to search
 

/* ********************** Validation ********************** */
IF @Single_DB_Only = 1 AND NOT EXISTS(SELECT name FROM [master].[sys].[databases] WHERE name = @DBname)
BEGIN
 PRINT 'Please enter valid database name'
 RAISERROR('Please enter valid database name', 20, -1) WITH LOG
END
/*-- ********************** Validation ********************** */
 
if exists(select * from [master].[dbo].sysobjects where xtype = 'U' and [Name] = 'MY_INFO_ALL_TABLES')
  drop table [master].[dbo].MY_INFO_ALL_TABLES
create table [master].[dbo].MY_INFO_ALL_TABLES (TableName nvarchar(max), ColName nvarchar(max))
 
if exists(select * from [master].[dbo].sysobjects where xtype = 'U' and Name = 'MY_INFO')
  drop table [master].[dbo].MY_INFO
create table [master].[dbo].MY_INFO (DBName nvarchar(max), TableName nvarchar(max), ColName nvarchar(max), FieldValue nvarchar(max))

if @Single_DB_Only = 0
Begin
 declare CUR_DB cursor for select name from [master].[sys].[databases] where name not in('master','tempdb', 'model','msdb','tempdb') and state = '0' 
 open CUR_DB
 fetch next from CUR_DB  into @DBname
 while @@FETCH_STATUS = 0
 Begin
  print @DBNAME 
  
  set @CMD = 'insert into [master].[dbo].MY_INFO_ALL_TABLES (TableName, ColName) select T1.Name as TableName , T0.Name as ColName from [{3}].sys.syscolumns T0 inner join [{3}].sys.sysobjects T1 on T0.id = T1.id where T1.xtype = ''U'' and T0.Name not like ''MY_TABLES%'' '
  set @CMD = replace(@CMD,'{3}',@DBname)
  -- print @CMD
  exec (@CMD)
  
  declare CUR cursor for select TableName , ColName from [master].[dbo].MY_INFO_ALL_TABLES
  open CUR
  fetch next from CUR  into @TableName, @ColName
  while @@FETCH_STATUS = 0
  Begin
     set @CMD = 'insert into [master].[dbo].MY_INFO (DBName,TableName,ColName,FieldValue) select ''{3}'',''{1}'',''{0}'', cast({0} as nvarchar) from [{3}].dbo.{1} where {0} like ''%{2}%'' '
     set @CMD = replace(@CMD,'{0}',@ColName)
     set @CMD = replace(@CMD,'{1}',@TableName)
     set @CMD = replace(@CMD,'{2}',@Text_To_Search)
     set @CMD = replace(@CMD,'{3}',@DBname)
     -- print @CMD
     exec (@CMD)
     fetch next from CUR into @TableName, @ColName
  End
  close CUR
  deallocate CUR
  
  fetch next from CUR_DB  into @DBname
 End
 close CUR_DB
 deallocate CUR_DB
End
Else
Begin
 print @DBNAME 
 
 set @CMD = 'insert into [master].[dbo].MY_INFO_ALL_TABLES (TableName, ColName) select T1.Name as TableName , T0.Name as ColName from [{3}].sys.syscolumns T0 inner join [{3}].sys.sysobjects T1 on T0.id = T1.id where T1.xtype = ''U'' and T0.Name not like ''MY_TABLES%'' '
 set @CMD = replace(@CMD,'{3}',@DBname)
 -- print @CMD
 exec (@CMD)
 
 declare CUR cursor for select TableName , ColName from [master].[dbo].MY_INFO_ALL_TABLES
 open CUR
 fetch next from CUR  into @TableName, @ColName
 while @@FETCH_STATUS = 0
 Begin
    set @CMD = 'insert into [master].[dbo].MY_INFO (DBName,TableName,ColName,FieldValue) select ''{3}'',''{1}'',''{0}'', cast({0} as nvarchar) from [{3}].dbo.{1} where {0} like ''%{2}%'' '
    set @CMD = replace(@CMD,'{0}',@ColName)
    set @CMD = replace(@CMD,'{1}',@TableName)
    set @CMD = replace(@CMD,'{2}',@Text_To_Search)
    set @CMD = replace(@CMD,'{3}',@DBname)
    -- print @CMD
    exec (@CMD)
    fetch next from CUR into @TableName, @ColName
 End
 close CUR
 deallocate CUR
 
 fetch next from CUR_DB  into @DBname
End
 
select * from [master].[dbo].MY_INFO
GO



          Hope this TSQL script can save a lot time of yours,

          Enjoy!!!

Heirarchical data - SQL query

Creating Table:

CREATE TABLE [Category](
 [CatId] [int] IDENTITY(1,1) NOT NULL,
 [PCatId] [int] NULL,
 [CatName] [varchar](50) NULL,
 CONSTRAINT [PK_Category] PRIMARY KEY CLUSTERED 
(
 [CatId] ASC
))
GO

Sample Data:

Insert into [Category] ([PCatId],[CatName]) values (0,'Cat1');
Insert into [Category] ([PCatId],[CatName]) values (0,'Cat2');
Insert into [Category] ([PCatId],[CatName]) values (1,'Cat3');
Insert into [Category] ([PCatId],[CatName]) values (1,'Cat4');
Insert into [Category] ([PCatId],[CatName]) values (2,'Cat5');
Insert into [Category] ([PCatId],[CatName]) values (2,'Cat6');
Insert into [Category] ([PCatId],[CatName]) values (0,'Cat7');
Insert into [Category] ([PCatId],[CatName]) values (7,'Cat8');
Insert into [Category] ([PCatId],[CatName]) values (7,'Cat9');
Insert into [Category] ([PCatId],[CatName]) values (7,'Cat10');
Insert into [Category] ([PCatId],[CatName]) values (8,'Cat11');
Insert into [Category] ([PCatId],[CatName]) values (8,'Cat12');
Insert into [Category] ([PCatId],[CatName]) values (8,'Cat13');
GO

Final SQL Query

Now, Get Category with CatId = 8 and all it's child-hierarchy :

declare @catId int = 8;

-- select * from Category;

WITH hierarchy AS (
  SELECT c1.CatId,
         c1.CatName,
         c1.PCatId,
         CAST(NULL AS VARCHAR(50)) AS parentname
    FROM Category c1
   WHERE c1.PCatId = 0
  UNION ALL
  SELECT c2.CatId,
         c2.CatName,
         c2.PCatId,
         y.CatName
    FROM Category c2
    JOIN hierarchy y ON y.CatId = c2.PCatId)
SELECT s.CatId,
       s.CatName,
    s.PCatId,
       s.parentname
  FROM hierarchy s
  where s.PCatId = @catId OR s.CatId = @catId
  order by s.PCatId

Code / Syntax Highlighting with Blogger Engine

Introduction

I've been using Blogger as my blogging engine for a couple of weeks. I've been quite impressed at how easy it makes it to update your blogs look and feel and how free you are with the HTML and semantic layout of the pages.
One thing that seemed to be missing was allowing developers to copy and paste code into their blogs and allow other users to copy and paste the code from the blog into their own code.

Using SyntaxHighlighter Javascript Library

So in my search to find something better i came across this post which usessyntax highlighter.

Adding Syntax Highlighter to Blogger Template



  • Copy the following code
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<link href='http://alexgorbatchev.com/pub/sh/current/styles/shCore.css' rel='stylesheet' type='text/css'/>
<link href='http://alexgorbatchev.com/pub/sh/current/styles/shThemeDefault.css' rel='stylesheet' type='text/css'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shCore.js' type='text/javascript'></script>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushCpp.js' type='text/javascript'></script>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushCSharp.js' type='text/javascript'></script>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushCss.js' type='text/javascript'></script>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushJava.js' type='text/javascript'></script>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushJScript.js' type='text/javascript'></script>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPhp.js' type='text/javascript'></script>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPython.js' type='text/javascript'></script>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushRuby.js' type='text/javascript'></script>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushSql.js' type='text/javascript'></script>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushVb.js' type='text/javascript'></script>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushXml.js' type='text/javascript'></script>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPerl.js' type='text/javascript'></script>
<script language='javascript'>
SyntaxHighlighter.config.bloggerMode = true;
SyntaxHighlighter.config.clipboardSwf = 'http://alexgorbatchev.com/pub/sh/current/scripts/clipboard.swf';
SyntaxHighlighter.all();
</script>


  • paste it into your Blogger Template just above the </head> tag
  • Save the template
  • Then you can start creating code blocks in your existing or new Blog entries.
  • There are 2 ways to add a code block using syntaxhighlighter


Method 1: Using the script Tag

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<script type=&quot;syntaxhighlighter&quot; class=&quot;brush: csharp&quot;>
<![CDATA[
// Comment
public class Testing {
public Testing() {
}
public void Method() {
/* Another Comment
on multiple lines */
int x = 9;
}
}
]]></script>


becomes:

?
1
2
3
4
5
6
7
8
9
10
11
// Comment
public class Testing {
    public Testing() {
    }
    public void Method() {
        /* Another Comment
           on multiple lines */
        int x = 9;
    }
}


Method 2: Using the pre Tag

?
1
2
3
4
5
6
7
8
9
10
11
12
<pre class="brush: csharp">// Comment
public class Testing {
public Testing() {
}
public void Method() {
/* Another Comment
on multiple lines */
int x = 9;
}
}
</pre>


becomes:

?
1
2
3
4
5
6
7
8
9
10
11
// Comment
public class Testing {
    public Testing() {
    }
    public void Method() {
        /* Another Comment
           on multiple lines */
        int x = 9;
    }
}


Code Containing Less that or Greater than

One person noticed that if you try and publish any code with < or > in it, you'll need to HTML Encode the code before adding it to the blog post using something like this. Then you'll be able to publish code with generic's such as the following:
?
1
static Dictionary<int, List<Delegate>> _delegate = new Dictionary<int, List<Delegate>>();


Conclusion

I have to say i'm pretty impressed. There are a couple of things you have to watch out for:
  • The java script uses the <code> Tag. So as lots of blogger templates have styles for this tag you have to remove any styles before it looks like the above.
  • If you paste in HTML or XML with <Tags>. You'll need to HTML encode them. Which is a bit of a shame, as i was hoping the CDATA would help get around that problem. Maybe in the next version.

Find a cool free stuff everyday

Giveaway of the Day

Hiren Bharadwa's Posts

DotNetJalps