Building Windows Service using visual studio-C#

December 5, 2013 Leave a comment

Hi All,
Here I come back again and this time with Windows Service and related things. 🙂
In my carrier I had came across this stuff several times and always thought of writing something on this but unfortunately it always got skipped and went out side of the bucket.
Anyways here I start with:
Windows Service is an windows utility which keeps running behind the screens silently but sometime violently. As this utility runs behind the screen hence its obvious this has nothing to do with the UI, forms or any other cosmetic works.

  • So, how to build it?

Well building an win.service basically one needs to have 2 things:
1. Windows Service Class: Accommodates the code for which the service is written
2. Installer Class: For installing the service

Open visual studio 2010 (the steps are almost same since from ages!) & create an project , while doing so choose the WindowsService Template under the winodws header of your intended programming language.
More details can be retrieved from MSDN, CodeProject

Installing / Unistalling Window Service

      1. Windows service can be installed by firing installutil from the visual studio command prompt – Details on MSDN
      2. Alternative for the installutil is to make use of System.Configuration.Install assembly

using System;
using System.Collections.Generic;
using System.ServiceProcess;
using System.Configuration.Install;
using System.Reflection;
namespace WinService
{
static class Program
{
static void Main(string[] args)
{
if (Environment.UserInteractive)
{
string parameter = string.Concat(args);
switch (parameter)
{
case "--install":
ManagedInstallerClass.InstallHelper(new[] { Assembly.GetExecutingAssembly().Location });
break;
case "--uninstall":
ManagedInstallerClass.InstallHelper(new[] { "/u", Assembly.GetExecutingAssembly().Location });
break;
}
}
else
{
ServiceBase[] servicesToRun = new ServiceBase[]
{
new Service11()
};
ServiceBase.Run(servicesToRun);
}
}
#region Commented Code -- default code
//static void Main()
//{
// ServiceBase[] ServicesToRun;
// ServicesToRun = new ServiceBase[]
// {
// new Service11()
// };
// ServiceBase.Run(ServicesToRun);
//}
#endregion
}
}

    1. For Deployment purpose we can make use of the installer package as mentioned in these articles MSDN, Torben M. Philippsen
Categories: .NET, General Tags:

Add properties to visual webparts sharepoint 2010

November 7, 2013 Leave a comment

Hi,
This post talks on how one can add custom properties to their SharePoint 2010 visual webparts. Microsoft has brought visual webparts for easing the developer life with SharePoint 2010 development. But when it comes to adding some custom properties for these webparts then there is bit of trouble hidden.
To troubleshoot this issue lets us dive in entities inside webpart project.

  • Inside the webparts folder of the project one can see following files (considering webpart name as “VisualWebPart1”):
  1. Webpart class “VisualWebPart1.cs” that is derived from webpart class
  2. User control file “VisualWebPart1UserControl.ascx” and its associated designer and .cs files

Since we think that merely writing the property and setting its attributes to WebBrowsable=true & Personalizable inside the usercontrol class (VisualWebPart1UserControl.ascx.cs) file will go ahead and add properties into webpart, but in reality this will not work.
So how we gonna do this?
Even though the above assumption of ours is true but its partially true. The fact is, before adding this property to user control class we should
http://www.lamber.info/post/2010/05/21/How-do-I-create-custom-properties-in-Visual-Web-Parts.aspx
http://onlinecoder.blogspot.in/2011/04/custom-properties-in-sharepoint-2010_7158.html

Invoke SSRS reports from ASP.NET and or sharepoint webpart application by passing parameters

October 22, 2013 Leave a comment

Hi All,

After a good long break getting back to what like to 🙂
In this post I’m planning to take you through the execution of SSRS reports from an ASP.NET application, now what is so great about this (simple its my first post after long break 🙂 ) because we will see how to pass parameters to the report. And these reports are bit special/unique because they are driven by an SSAS cube.
Ok so not to waste more time…
Here is the code for doing so:


using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.Reporting.WebForms;

namespace MyWebApp
{
public partial class DummyReportViewer : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
_reportViewer.ProcessingMode = ProcessingMode.Remote;
// Report Server URL
_reportViewer.ServerReport.ReportServerUrl = new Uri(“http://%5Bservername:portnumber%5D/ReportServer/”);
// Report Name
_reportViewer.ServerReport.ReportPath = “/[reportpath]/[rdl_file_name]”;
// set true to show report parameters else false
_reportViewer.ShowParameterPrompts = true;
_reportViewer.ShowPrintButton = true;
// Below code demonstrate the Parameter passing method. User only if you have parameters into the reports.
Microsoft.Reporting.WebForms.ReportParameter[] reportParameterCollection = new Microsoft.Reporting.WebForms.ReportParameter[4];
reportParameterCollection[0] = new ReportParameter(“prmUniversityZone”, @”[DIM Zone].[Zone Hierarchy].[Zone NM].&[All]”);
reportParameterCollection[1] = new ReportParameter(“prmEducationStream”, @”[DIM Education].[Education Hierarchy].[Stream DSC].&[Engineering]”);
reportParameterCollection[2] = new ReportParameter(“prmPeriod”, @”[DIM Time PERIOD].[Period Hierarchy].[Year DSC].&[2009]”);
reportParameterCollection[3] = new ReportParameter(“prmResult”, @”[DIM Result].[Result Hierarchy].[Result NM].&[All]”);

_reportViewer.ServerReport.SetParameters(reportParameterCollection);
_reportViewer.ServerReport.Refresh();
}
}
}
}

Ok so what in case of multiple values for a single parameter. So in that case instead of sending string of parameter value pass an string array of multiple values.
i.e.

//instead of single parameter as:
reportParameterCollection[2] = new ReportParameter("prmPeriod", @"[DIM Time PERIOD].[Period Hierarchy].[Year DSC].&[2009]");

//create an string array of Year and pass it:
string[] years = new string[] { “2008”, “2009”, “2010”, “2011”, “2012” };
reportParameterCollection[2] = new ReportParameter(“prmPeriod”, years);

You may ask how do I extract this information of parameters. The simple is open the report goto parameters, open its property and check for Default Values in it. You will know what is required to be passed to the report parameter.

One more thing this is applicable to ASP.NET as well as SharePoint web part application

Following could be helpful resource for reports related stuff:

 

Categories: General Tags: , , ,

Dynamic and Editable GridView for SharePoint 2010

October 30, 2012 Leave a comment

Hi All,
This post of mine is kind of continuation my effort in developing of generalized utilities (specifically on grid layouts ).
Well here this time I had moved bit ahead and tried to develop an editable dynamic data grid which would be quite closure to what we get in datasheet view of SharePoint list. SharePoint 2010 is the targeted platform for this one.
For now I’m going to upload images of my latest buddy 🙂 Do have a look at it.
webparts custom properties in modal-dailogue

Sending HTML formated email from sql server

August 16, 2012 Leave a comment

Hi Folks,
After long time jolting something worth having glance. In application development we often come across a typical requirement where we are required to build a utility they will perform certain task(s) on periodic basis. One such type of common requirement is to shot mail(s) on periodic basis.
Recently I built one such utility for auto mailer. There were three (3) possible options to achieve this viz:

  1. Schedule an .exe application which will send emails
  2. Write an window service
  3. Create sql job and execute a sproc which will send email

Of these three options, last option has upper hand, as the data that required to be mailed was in database, also the sender email address and receiver email address were available in db and lastly there is no extra installer required since the job is defined in sql server and hence no deployment hiccups.

But the challenge was to build a dynamic HTML formatted email (challenge: because I underestimated send mail sproc of sqlserver).

But then bit of googling cleared my misconception and then I kick started building the auto mailer.

  • The rough layout of the desired html is as below:

Spot Nomination for July 2012

Emp.ID Employee Name Approver Payroll Amount Currency Mode
1 Joe Gracia Mark twain USA 1000 USD Cash
2 Narayan Jadhav Sam Powel USA 1000 USD Cash
3 Manish Patil Jignesh Patel India 4000 INR Cash
4 Amy Wang Lu Sang Taiwan 2000 TD Cash
5 Tsai Wu Sam Mochi Taiwan 2000 TD Cash
6 Juan Marcos Anna Alvaris Spain 1000 EURO Cash
7 Adongo Wangai Tobe Mugambe Kenya 4000 KES Cash
8 Akae Takahashi Chi Itou Japan 2000 YEN Cash
9 Mohit Gupta Ashutosh Singh India 4000 INR Cash

Thanks & Regards,
Payroll Management Team
paymaster@ttk.mbt.com

  • The Logic for the Stored Procedure
  1. Create a temp table and define necessary columns in it
  2. Populate the temp table by inserting the required data into it
  3. Declare two variables viz @xml NVARCHAR(MAX); @body NVARCHAR(MAX);
  4. Extract the data from temp table, cast it to xml string (essentially with html tags in it) and then assign it to @xml variable
  5. Now this @xml variable is having partial, table formatted data of the body tag
  6. Now build the remaining part of the body tag
  7. At concluding part just execute the msdb.dbo.sp_mail_dbmail stored procedure and provide the @body variable to it
  • The complete sql script is as below:
CREATE PROCEDURE [dbo].[SendEmail_Date_AwardType_Location]
 @FromDate DateTime
 , @ToDate DateTime
 , @AwardTypeID Int
 , @LocationName Varchar(50)
AS

BEGIN
 SET NOCOUNT ON;

CREATE TABLE #SpotNomApporval
(
 [EmpID] INT
 ,[EmployeeName] NVARCHAR(150)
 ,[Payroll] NVARCHAR(150)
 ,[ApprovingAuthority] NVARCHAR(150)
 ,[Amount] INT
 ,[Currency] NVARCHAR(150)
 ,[Mode] NVARCHAR(150)
)

INSERT INTO #SpotNomApporval
SELECT [EmpId]
 ,[EmpName] AS [EmployeeName]
 ,[ApprovingAuthority]
 , AI.[GlobalLocation] AS [Payroll]
 ,[Amount]
 ,[Currency]
 ,[Mode]

FROM [AwardInfo] AS AI
 LEFT JOIN [AwardType] AS AT
 ON AI.AwardTypeID = AT.AwardTypeId
 LEFT JOIN [AwardLocation] AS AL
 ON AI.GlobalLocation = AL.LocationName
WHERE AT.AwardTypeId = @AwardTypeID
 AND AL.LocationName = @LocationName
 AND DateofRequisition BETWEEN @FromDate AND @ToDate

DECLARE @xml NVARCHAR(MAX);
DECLARE @body NVARCHAR(MAX);
DECLARE @duration NVARCHAR(100);

SET @xml = CAST(( SELECT [EmpId] AS 'td'
 ,'',[EmployeeName] AS 'td'
 ,'',[ApprovingAuthority] AS 'td'
 ,'',[Payroll] AS 'td'
 ,'',[Amount] AS 'td'
 ,'',[Currency] AS 'td'
 ,'',[Mode] AS 'td'
FROM #SpotNomApporval
FOR XML PATH('tr'), ELEMENTS ) AS NVARCHAR(MAX))

SET @duration = (SELECT Month =
 CASE MONTH(GETDATE())
 WHEN 1 THEN 'January'
 WHEN 2 THEN 'February'
 WHEN 3 THEN 'March'
 WHEN 4 THEN 'April'
 WHEN 5 THEN 'May'
 WHEN 6 THEN 'June'
 WHEN 7 THEN 'July'
 WHEN 8 THEN 'August'
 WHEN 9 THEN 'September'
 WHEN 10 THEN 'Octomber'
 WHEN 11 THEN 'November'
 WHEN 12 THEN 'December'
 END) +' '+ CAST((SELECT "Year" = YEAR(GETDATE())) AS VARCHAR(5))

SET @body ='<html><body><span style="color:#17365d"><H3>Spot Nomination for '+@duration+'</H3></span>
<table border = 1>
<tr>
<td bgcolor="#6B696B"> Emp.ID </td> <td bgcolor="#6B696B"> Employee Name </td> <td bgcolor="#6B696B"> Approver </td>
<td bgcolor="#6B696B"> Payroll </td> <td bgcolor="#6B696B"> Amount </td> <td bgcolor="#6B696B"> Currency </td>
<td bgcolor="#6B696B"> Mode </td></tr>'

SET @body = @body + @xml +'</table></body></html>'
SET @duration = 'Spot Nomination for '+@duration

EXEC msdb.dbo.sp_send_dbmail
@body = @body,
@body_format ='HTML',
@recipients = 'manishrao18@gmail.com',
@subject = @duration

DROP TABLE #SpotNomApporval

END

The more helpful resource can be found at below links:
http://msdn.microsoft.com/en-us/library/ms190307.aspx

http://www.mssqltips.com/sqlservertip/2347/send-email-in-a-tabular-format-using-sql-server-database-mail/

Categories: Sql Server Tags:

Packt’s Microsoft Carnival!

May 15, 2012 Leave a comment

Brighten your May at Packt’s Microsoft Carnival! Exciting discounts on Microsoft books/e-books throughout May 2012!

http://bit.ly/KLN5Ma

Categories: General Tags:

Sharepoint 2010 powershell references

February 2, 2012 Leave a comment
Categories: General Tags: