Are you looking for customized advices? Click here to contact the expert!
cghersi
cghersi
Reputation Top 1%
Cristiano Ghersi
Great passion for Software Engineering, mostly coding in Java and C#, I enjoy creating modular and reusable code for everybody!
195 Snippets  (2nd place)
Published
13 Channels
Created
60 Channels
Following
13 hours ago
Last Visit
May 5, 2012
Registered
6891 points  (2nd place)
Reputation
Top 1% Publisher
Junior Code Generator
Serious Code Generator
Senior Code Generator
Master Code Generator
Guru Code Generator
Junior Publisher
Serious Publisher
Senior Publisher
Master Publisher
Guru Publisher
Master Topic Creator
Guru Topic Creator
Junior Topic Hub
Serious Topic Hub
Senior Topic Hub
Master Topic Hub
Junior Trend Maker
Serious Trend Maker
Senior Trend Maker
Senior Team Manager
Junior Influencer
Serious Influencer
Senior Influencer
Junior Commenter
Serious Commenter
Senior Commenter
Master Commenter
Junior Judge
Serious Judge
Senior Judge
Master Judge
Junior Popular Coder
Serious Popular Coder
Senior Popular Coder
Master Popular Coder
Guru Popular Coder
Junior Autobiographer
Serious Autobiographer
Senior Autobiographer
Master Autobiographer
Junior Geek Aggregator
Serious Geek Aggregator
Senior Geek Aggregator
Junior Famous Coder
Serious Famous Coder
Junior Wise Coder

Recent Snippets See all snippets by cghersi

public by cghersi modified Mar 12, 2015  58  3  0

Git update from Batch

How to perform a git update from Batch script
cd my/path
call git reset <branch_name> --hard
call git checkout <branch_name>
call git pull                      

public by cghersi modified Feb 14, 2015  196  6  0

Nice way to show the current time of day

Current Time printed in a nice way
public static string NiceCurrentTime()
{  
  int hour = DateTime.Now.Hour;

  if (hour <= 5)
    return "this night oh yeah";
  else if (hour > 5 && hour <= 12)
    return "this morning";
  else if (hour > 12 && hour < 18)
    return "this afternoon";
  else 
    return "this evening";
}                                                                                    

public by cghersi modified Dec 16, 2014  487  5  1

How to view active SQL sessions onto a MS SQL Server

This script lets the sysadmin check the active SQL session on a server. Thanks to David Kranes, original post can be found here: http://www.sqlservercentral.com/scripts/Administration/88041/
SQL
SET NOCOUNT ON
GO

IF OBJECT_ID('tempdb..#curSQL') IS NOT NULL
 DROP TABLE #curSQL
GO

CREATE TABLE #curSQL
(spID SMALLINT,
blocked VARCHAR(3),
hostName VARCHAR(2000),
dbName VARCHAR(100),
cmd VARCHAR(100),
sqlText NTEXT,
phyIO BIGINT,
Status VARCHAR(100),
programName VARCHAR(1000),
loginTime DATETIME,
lastBatch DATETIME
)

DECLARE @spID smallint,
        @Blocked VARCHAR(3),
        @sqltext VARBINARY(128),
        @physIO BIGINT,
        @hostName VARCHAR(2000),
        @desSPID SMALLINT,
        @dbName VARCHAR(100),
        @Cmd VARCHAR(100),
        @status VARCHAR(100),
        @programName VARCHAR(1000),
        @loginTime DATETIME,
        @lastBatch DATETIME
        

-- Set desired SPID. If NULL, it will return all non-system SPID's.
--SET @desSPID = <Put desired SPID her to filter>


BEGIN TRY
    IF @desSPID IS NOT NULL
        DECLARE spID_cursor CURSOR
        FORWARD_ONLY READ_ONLY
        FOR SELECT spid, CASE blocked WHEN 0 THEN 'NO' ELSE 'YES' END blocked, hostname, db_name(dbid), cmd, physical_io, status, program_name, login_time, last_batch
            FROM sys.sysprocesses 
            WHERE spid = @desSPID
            GROUP BY spid, blocked, physical_io, hostname, db_name(dbid), cmd, physical_io, status, program_name, login_time, last_batch
            ORDER BY spid

    ELSE
        DECLARE spID_cursor CURSOR
        FORWARD_ONLY READ_ONLY
        FOR SELECT spid, CASE blocked WHEN 0 THEN 'NO' ELSE 'YES' END blocked, hostname, db_name(dbid), cmd, physical_io, status, program_name, login_time, last_batch
            FROM sys.sysprocesses 
            WHERE spid > 50
            GROUP BY spid, blocked, physical_io, hostname, db_name(dbid), cmd, physical_io, status, program_name, login_time, last_batch
            ORDER BY spid
        OPEN spID_cursor

        FETCH NEXT
        FROM spID_cursor
        INTO @spID, @Blocked, @hostName, @dbName, @cmd, @physIO, @status, @programName, @loginTime, @lastBatch

        WHILE @@FETCH_STATUS = 0
        BEGIN

         SELECT @sqltext = sql_handle
         FROM sys.sysprocesses
         WHERE spid = @spID

         INSERT INTO #curSQL
         SELECT @spID, @Blocked, @hostName, @dbName, @cmd, TEXT, @physIO, @status, @programName, @loginTime, @lastBatch
         FROM ::fn_get_sql(@sqltext)
         
         FETCH NEXT
         FROM spID_cursor
         INTO @spID, @Blocked, @hostName, @dbName, @cmd, @physIO, @status, @programName, @loginTime, @lastBatch
         
         END
         
         CLOSE spID_cursor
         DEALLOCATE spID_cursor
     
    SELECT * FROM #curSQL ORDER BY blocked asc, spid
END TRY

BEGIN CATCH
    CLOSE spID_cursor
    DEALLOCATE spID_cursor
    
    SELECT ERROR_NUMBER() ErrorNBR, ERROR_SEVERITY() Severity, ERROR_LINE() ErrorLine, ERROR_MESSAGE() Msg
    
    PRINT 'There was an error in the script.'
    
END CATCH    

            

public by cghersi modified Dec 10, 2014  183  5  3

How to query some values inside XML in SQL Server

This query relies on 'value' operator applied on XML fields. You can directly transform the resulting value into a particular type with the second parameter of this function.
WITH XMLNAMESPACES ('http://www.snip2code.com/namespaces/s2c' AS s2c)
SELECT  field1, field2
FROM    MyTable
WHERE   MyXMLField.value('/s2c:root/fieldName != ""', 'bit') = 1      

WITH XMLNAMESPACES ('http://www.snip2code.com/namespaces/s2c' AS s2c)
SELECT  field1, field2
FROM    MyTable
WHERE   MyXMLField.value('(/s2c:root/fieldName/text())[1]', 'varchar(100)') = 'some text'

public by cghersi modified Dec 5, 2014  1277  7  3

How to retrieve GMail contacts via API, using OAuth2 token and not username/password credentials

This class takes charge of the interaction with Google Contacts API, authenticating with an AccessToken authorization flow. In this way the final user should type the credentials in the Google form and not in your form. The "token" parameter of GetContacts() method is the one sent by Google to the callback url specified in the static constant "s_
using System;
using System.Linq;
using System.Collections.Generic;
using Google.Contacts;
using Google.GData.Contacts;
using Google.GData.Client;
using Google.GData.Extensions;

namespace Contact.Utils
{
  /// <summary>
  /// Summary description for GmailHelper
  /// </summary>
  public class GmailHelper
  {
    private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

    private static fastJSON.JSON jsonUtils = EntityUtils.InitJSONUtils();

    private static readonly string APP_NAME = "my app name";
    private static readonly string s_ClientId = "client id given by Google";
    private static readonly string s_ClientSecret = "secret given by Google;
    private static readonly string s_accessTokenUrl = "https://accounts.google.com/o/oauth2/token";
    private static readonly string s_redirUri = WebConfig.Current.PublicPath + "User/GmailCallback";

    #region PUBLIC API
    //////////////////////////////////////////////////////////////////////////////////////////////////////

    public static string GetRedirUriForContacts()
    {
      return string.Format("https://accounts.google.com/o/oauth2/auth?scope=https://www.google.com/m8/feeds&redirect_uri={0}&response_type=code&client_id={1}",
        s_redirUri, s_ClientId);
    }

    public static List<SimpleContact> GetContacts(string token)
    {
      List<SimpleContact> results = new List<SimpleContact>();

      //exchange the code for a token:
      string postData = string.Format("code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type=authorization_code",
        token, s_ClientId, s_ClientSecret, s_redirUri);
      string accessTokenResp = Utilities.SendHttpRequest(s_accessTokenUrl, postData, true);
      if (string.IsNullOrEmpty(accessTokenResp))
        return results;

      AccessTokenStruct parsedJson = null;
      try
      {
        parsedJson = jsonUtils.ToObject<AccessTokenStruct>(accessTokenResp); 
      }
      catch (Exception e)
      {
        log.ErrorFormat("Cannot deserialize access token response: '{0}' due to {1}", accessTokenResp, e.Message);
        return results;
      }
      if (parsedJson == null)
        return results;

      //ask for contacts:
      RequestSettings settings = new RequestSettings(APP_NAME, parsedJson.access_token); 
      settings.AutoPaging = true;
      ContactsRequest cr = new ContactsRequest(settings);
      Feed<Contact> contactsFeed = cr.GetContacts();
      IEnumerable<Contact> contacts = null;
      if (contactsFeed != null)
        contacts = contactsFeed.Entries;
      if (contacts == null)
        return results;

      try
      {
        foreach (SimpleContact c in contacts)
        {
          if (c.PrimaryEmail == null)
            continue;
          string preferredEmail = c.PrimaryEmail.Address;
          if (string.IsNullOrEmpty(preferredEmail))
            continue;
          string[] otherEmails = null;
          if (c.Emails != null)
            otherEmails = c.Emails.Select(e => e.Address).ToArray();
          S2CContact contact = new S2CContact((c.Name == null ? "" : c.Name.FullName), 
                                              preferredEmail, otherEmails);
          results.Add(contact);
        }
      }
      catch (Exception e)
      {
        log.ErrorFormat("Cannot retrieve contacts due to {0}", e.Message);
        return results;
      }

      return results;
    }

    #endregion
    //////////////////////////////////////////////////////////////////////////////////////////////////////
  }

  public class AccessTokenStruct
  {
    public string access_token { get; set; }
    public int expires_in { get; set; }
    public string token_type { get; set; }

    public AccessTokenStruct() { }
  }

  public class SimpleContact
  {
    public string PreferredEmail { get; set; }
    public string Name { get; set; }
    public string[] Emails { get; set; }

    public SimpleContact(string name, string preferredEmail, string[] emails = null)
    {
      Name = name;
      PreferredEmail = preferredEmail;
      if (emails == null)
        Emails = new string[] { preferredEmail };
      else
      {
        List<string> allEmails = new List<string>(emails);
        allEmails.Add(preferredEmail);
        Emails = allEmails.Distinct().ToArray();
      }
    }

    public override string ToString()
    {
      if (string.IsNullOrEmpty(Name))
        return PreferredEmail;
      else
        return string.Format("{0} [{1}]", Name, PreferredEmail);
    }
  }

}