Wednesday, October 19, 2011

Who is there?

Today I needed to take a database offline. Generally we send notification to all requesting to log off. But today I thought to do something differently. Before I send notification to everyone I wanted to see if anyone is using that database at all.

There are a system stored procedure sp_who which returns information regarding current sessions on given database.








There is an extended version of this stored procedure is also available.

Friday, September 23, 2011

Exception log simplified

One of very common problem is to keep log of exception/error which happens in production environment for debugging and quality improvement purpose.

There are many great logging tools/framework available in the market with many enhanced functionality. In most cases these detailed functionalities are not required.

Few weeks back, when this problem presented itself (to log exception detail to database or file) I thought let’s make things simpler.

Problem Description: Quickly log exception details without any 3rd party framework.

Conditions:

  1. Where to log exceptions details was controlled by system parameter and can be managed from UI.
  2. Exception log method should have ability to log more details if required and supplied.
Solution
  1. Method to get exception details for log
  2. Decide which logging method(s) to call
  3. Implementation of various logging methods


public static void ProcessError(Exception exception, string otherDetails = "")
{
 StackTrace stackTrace = new StackTrace();
 string methodName = stackTrace.GetFrame(1).GetMethod().Name;
 string className = stackTrace.GetFrame(1).GetMethod().DeclaringType.Name;
 string classDetail = string.Format("{0}.{1}", className, methodName);
 string exceptionDetail = string.Format("Error occurred in {0}. {1}Message:{2}", 
  classDetail,
  Environment.NewLine,
  exception.Message
 );

 if (!string.IsNullOrWhiteSpace(otherDetails))
 {
  exceptionDetail = string.Format("{0}{1}Other Details: {2}.",
   exceptionDetail,
   Environment.NewLine,
   otherDetails
  );
 }
 // send this detail for saving
 LogError(exceptionDetail);
}

Here the trick is to get Calling method and class name for logging. We used following lines to do that job

// to get name of calling method
string methodName = stackTrace.GetFrame(1).GetMethod().Name; 

// to get name of calling class
string className = stackTrace.GetFrame(1).GetMethod().DeclaringType.Name; 

Now lets decide where to save this detail



public enum LogMethods
{
 Database,
 File,
 Email
};


...
...


public static void LogError(string exceptionDetail)
{
 switch (errorLogMethod)
 {
  case LogMethods.Database:
   LogErrorInDatabase(exceptionDetail);
   break;
  case LogMethods.File:
   LogErrorInFile(exceptionDetail);
   break;
  case LogMethods.Email:
   SendErrorLog(exceptionDetail);
   break;
  case default:
   SendErrorLog(exceptionDetail);
   break;
 }
}

Now last step, implement save methods


Here is an example of saving detail in database. Similarly other methods can be implemented.


public static void logErrorMessageInDB(string exceptionDetail, string methodName)
{
 try
 {
  MyDataContext myDC = DataContext;

  Log lerror = new Log
  {
   FullDescription = exceptionDetail,
   MethodName = methodName,
   CreateDataTime = DateTime.Now
  };

  iDC.Log.InsertOnSubmit(lerror);
  iDC.SubmitChanges();
 }
 catch (Exception exp)
 {
  /*
   LogErrorInFile(exp);
   // OR
   LogErrorInEventLog(exp);
  */
 }
}

Tuesday, June 21, 2011

Publish Infopath (2010) Form on Sharepoint Server (2010)


From last few months I am working with InfoPath forms; especially for web hosted
forms. I needed to create a page to host InfoPath form. Here is a quick tutorial
to do this

Assumptions:

  1. User has required rights to perform this task
  2. Server is SharePoint 2010 Server.

We need to do few tasks

  1. Publish InfoPath form.
  2. Upload and Publish that form on SharePoint Server.
  3. Create a page to host this InfoPath form.

So let’s get started.

Publish InfoPath form.

1. 1. In InfoPath click on File Menu and select Publish.



1. 2. From various options on right side of page, Select “SharePoint Server” (Publish
form to a SharePoint Library). This will open Publishing Wizard dialog.



1. 3. In Publishing Wizard dialog type URL of SharePoint server where you want to
host this InfoPath form and click Next.



1. 4. Select “Administrator-approved form template (advanced)” option from list
and click next.



1. 5. Select location where you want to publish your InfoPath form; (Please make
sure that SharePoint admin can access this location) and hit Next.



1. 6. If you want to add new columns in SharePoint list add that here, otherwise
click Next.



1. 7. Please review information and click “Publish” if everything seems OK.



1. 8. After you click on publish it may take few minutes to update screen, Once
published you will see confirmation screen indicating that publication was successful.
Click on Close to finish “Publishing Wizard”



Upload and Publish that form on SharePoint Server

Now Our InfoPath form is ready for publication on SharePoint server. First we need
to upload InfoPath form on server. For that …

2. 1. Open SharePoint website on web browser and select “Site Settings” from Site
Actions menu. (top left side)



2. 2. a) This will open central Administration screen, From left side list, Select
“General Application Settings.”



2. 2. b) When selected (General Application Settings) you will see list of settings
options on right side, Select “Manage Form Template” from InfoPath Forms Services.
(Assuming InfoPath Forms Services is installed and available)


2. 3. You will see list of available InfoPath forms. On top of the page you will
see link for uploading form template


2. 4. From upload page click on browse and select the file we saved in Step 5 of
first section and click Upload


2. 5. Once form is uploaded you will see confirmation message. By clicking OK you
will be redirected to Template management page where you will see your form on list.


2. 6. Select your form and open options menu (when you move your cursor to right
side of forms name you will see dropdown box click there which will open options
menu) and select “Activate to a Site Collection” option.


2. 7. Select site where you want to active this form and click OK. This ends part
2


Create a page to host this InfoPath form.

Now we have InfoPath form available on SharePoint site; we need to make it accessible
to end user for data entry. First of all (assuming we don’t have one) we need to
create a new page to host InfoPath form.

3. 1. To be able to do this open SharePoint website in web browser and select “New
Page” from Site actions menu. (top left)


3. 2. Type name of form and click “Create”. Your page will be available in edit
mode.


3. 3. From ribbon menu select “Library Settings” to make that InfoPath form available
as type.


3. 4. From Library Settings->Content Types select Add existing site content types.


3. 5. From list of available types select the InfoPath from you want to add and
click on “Add” button. Once done click OK to save your changes.


3. 6. Open your (new page) in edit mode, and from Ribbon menu select Insert->Web
Part.


3. 7. From Categories select “Forms”, From Web Parts select “InfoPath Form web part”
and click “Add”


3. 8. You will see following web part on your page, Click on Link to open tool pane.


3. 9. From tool pane select “Pages” from List or Library, Select

from Content Type List.


3. 10. (optional) By default any InfoPath webpart will appear with header, In some
cases you don’t need header, to remove header expand “Appearance” section and select
“None” from Chrome Type. Which will remove header.


3. 11. Once done Click Apply and your page is ready. You can publish it (after any
other formatting related changes you may want to do)

Happy Coding !!! :)

Thursday, June 2, 2011

The power of Basics, LINQ

Few days back I needed to write a small utility program in C# to update few million (91 to be exact) records in a table.

I thought it is fairly straight forward, single user, single connection application scenario hence I used WPF and Linq to do the job.

First run and updated record number started to fly like Jet. In a minute or two it processed entire table (yes! With 91 Million records). I was surprised to see that kind of performance.

Then I want to check database to check updated records, there were none

I was scratching my head for a while and it occurred to me that there may be some problem in table structure; hence I checked table structure, to my surprise there was no primary key defined (no wonder it got processed so fast !!!).

I requested that change to our DBA, and updated code accordingly, and I started the program again

Now I started to get more believable numbers (like 200 - 500 records / second)

Lesson learned:
  • Do not assume that input supplied to you (the table in this case) is correct; Verify it before you start processing it.
  • If there is no primary key defined in the table, given table will not update any rows (and it will not complaint either)

Wednesday, March 30, 2011

Join Multiple Text Files using Dirty Operating System (DOS)


Dirty Operating System (DOS)

Few days back I needed to join few (Thousand) text file as One file. I thought of
several options

  1. Open Notepad and copy paste files one by one :(
  2. Write a program which joins files.
  3. Download and use 3rd party program like TXTCollector
  4. Try something new ...

I remembered earlier (dark) days of DOS (Dirty Operation System) when screen was
black and text was white, everything was between 32 rows and 80 columns. Few of
DOS commands were very interesting like | (more) and > or >> (pipe). I thought to
do an experiment with that. I went to DOS prompt in same directory where all .txt
files were stored and used following command

type *.txt > MergedFile.txt

and ...

Yes !!! I got combined file named MergetFile.txt which was 14GB. There are few more
tricks like this

type firstFile.txt secondFile.txt thirdFile.txt fifthFile.txt > MergedFile.txt

This will join FirstFile.txt, SecondFile.txt, ThirdFile.txt and fifthFile.txt into
MergedFile.txt, this is useful when you want to join files in certain order.

Please note that each file is separated by a space. As you may already know, if
are in different folders please use full path instead of just file name.

type *.txt *.csv >MergedFile.txt

This will first join all files with .txt extension and then will join all files
with .csv extension to create a file called MergedFile.txt Here the magic command
is > which takes output of left side command and gives as input to right side command.
If used as >> then output gets be appended. As stated in
the principal of "Occam's razor" "The simplest explanation is
most likely the correct one"

Instead of writing my own code (spending few hours) or download or buy 3rd party
tool (spending money earned in few hours !!!) I used DOS to do the work. Hope this
helps Enjoy coding !!!