Wednesday, September 21, 2016

Populating ComboBox from SQl ResultSet

querystring = "Select AccomodationName from MST_ONSITEACCOMMODATION where CityName=" & Chr(39) & cityname & Chr(39)
                    conn.ConnectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Data Source=.;Initial Catalog=Test;"
                    conn.Open
                    rst.Open querystring, conn, adOpenStatic
                    With ComboBox7
                                .Clear
                                    Do While Not rst.EOF
                                       .AddItem rst![AccomodationName]
                                                   
                                        rst.MoveNext
                                    Loop
                    End With
                                       
                    rst.Close
                    conn.Close
                    querystring = vbNullString
                    Set rst = Nothing
                    Set conn = Nothing

Sunday, September 11, 2016

Extract Data Using Select Query in VBA

Option Explicit

Dim conn As New ADODB.Connection, querystring As String, blockname As String, hadoopblockrowcount As Long
Dim rst As New ADODB.Recordset

Sub extractData()
blockname = Application.InputBox("Please Mention Block Name to be Created")
querystring = "Select t1.Cid,t1.CName,t1.PSName,t1.StDuration,t2.CourseExamId from MST_COURSE t1"
querystring = querystring & " join LNK_COURSE_EXAM t2 on t1.CId=t2.courseid"
querystring = querystring & " where t1.CId in(Select distinct CourseId from Lnk_COURSE_VENDOR where VendorId=32)and PSName is not null"
querystring = querystring & " Union Select t1.Cid, t1.CName,t1.PSName,t1.StDuration,null from MST_COURSE t1"
querystring = querystring & " where t1.CId in(Select distinct CourseId from Lnk_COURSE_VENDOR where VendorId=32)and PSName is not null;"

hadoopblockrowcount = 3
Application.ScreenUpdating = False
    conn.ConnectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Data Source=.;Initial Catalog=CourseMasterDB;"
    conn.Open
    rst.Open querystring, conn, adOpenStatic
    Do While Not rst.EOF
    hadoopblockrowcount = hadoopblockrowcount + 1
    ThisWorkbook.Sheets(1).Range("A" & (hadoopblockrowcount)) = rst.Fields(0).Value
    ThisWorkbook.Sheets(1).Range("B" & (hadoopblockrowcount)) = rst.Fields(1).Value
    ThisWorkbook.Sheets(1).Range("C" & (hadoopblockrowcount)) = rst.Fields(2).Value
                If (rst.Fields(4).Value <> vbNullString) Then
                        ThisWorkbook.Sheets(1).Range("E" & (hadoopblockrowcount)) = "Y"
                Else
                        ThisWorkbook.Sheets(1).Range("E" & (hadoopblockrowcount)) = "N"
                End If
    ThisWorkbook.Sheets(1).Range("G" & (hadoopblockrowcount)) = rst.Fields(3).Value
        rst.MoveNext
    Loop
   
    rst.Close
    conn.Close
    Set rst = Nothing
    Set conn = Nothing
   
End Sub

Wednesday, August 31, 2016

Trim Entire Column in VBA

Sub TrimCol()
    Dim r As Range
    Set r = Intersect(Range("A1").EntireColumn, ActiveSheet.UsedRange)
    r.Value = Evaluate("IF(ROW(" & r.Address & "),IF(" & r.Address & "<>"""",TRIM(" & r.Address & "),""""))")
End Sub

Copy Range to Array

Dim myArray()
Sub copyRange2Array()
myArray = ThisWorkbook.Sheets(1).Range("A1:A4").Value
For i = 1 To UBound(myArray)
    MsgBox myArray(i, 1)
Next
End Sub

Tuesday, August 9, 2016

Finding Next Blank Row no in VBA

Sub test()
Dim myrng As Range
Set myrng = Range(ThisWorkbook.Sheets(1).Range("A1").Offset(0, 0), ThisWorkbook.Sheets(1).Range("A1").Offset(0, 0).End(xlDown))
MsgBox myrng.Rows.Count + 1
End Sub

Thursday, July 28, 2016

VBA code for autofilter on the basis of Color

keywordsmasterfile.Sheets(1).Range("A2:B2").AutoFilter field:=1, Criteria1:=RGB(204, 153, 255), Operator:=xlFilterCellColor

Saturday, June 25, 2016

Types of Cursor in MSSQL

SQL Server Different Types of Cursors

           
A Cursor allow us to retrieve data from a result set in singleton fashion means row by row. Cursor are required when we need to update records in a database table one row at a time. I have already explained the basic of cursor.
A Cursor impacts the performance of the SQL Server since it uses the SQL Server instances' memory, reduce concurrency, decrease network bandwidth and lock resources. Hence it is mandatory to understand the cursor types and its functions so that you can use suitable cursor according to your needs.
You should avoid the use of cursor. Basically you should use cursor alternatives like as WHILE loop, sub queries, Temporary tables and Table variables. We should use cursor in that case when there is no option except cursor.

Friday, June 17, 2016

Install Window Service Programmitcally

You can do it all in one executable. To pass installation parameters, you will need to derive classes System.ServiceProcess.ServiceProcessInstaller and System.ServiceProcess.ServiceInstaller. You only need to implement constructors of your classes.

Installation and uninstallation will be done by System.Configuration.Install.AssemblyInstaller. This class should use the assembly where the classes based on ServiceProcessInstaller and ServiceInstaller are implemented; the implementation will be found in your assembly automatically (which would create a hard-to-detect failure if you have a bug in the implementation). Not too bad though.

Finally, start/stop, etc. are handled by your service code which you create deriving the class System.ServiceProcess.ServiceBase. Triggering this actions is done by Service Controller. To do it programmatically you should use the class System.ServiceProcess.ServiceController.

You need to have a good reading of MSDN on the topics around the classes I listed above, which is well illustrated by code samples. This information is easy to find, a bit harder to understand the work flow and what happens in which process. (A Windows Service process is always a separate one; it takes another process to run installation and Service Controller part.) You can use all this like a cookbook, but I suggest you thoroughly understand it; in this case you won't have any problems.

You can even try to implement it all in one application as I did, but you still need to run it in at least two different processes: one would work in the Windows Service mode, another is must be interactive mode, which can be anything else, such as UI, Console or just invisible batch-mode application.

Important! You code can test System.Environment.UserInteractive during run time to calculate is currently running code is run as Windows Service or not.

Add Installer for Window Service

In the service project do the following:
  1. In the solution explorer double click your services .cs file. It should bring up a screen that is all gray and talks about dragging stuff from the toolbox.
  2. Then right click on the gray area and select add installer. This will add an installer project file to your project.
  3. Then you will have 2 components on the design view of the ProjectInstaller.cs (serviceProcessInstaller1 and serviceInstaller1). You should then setup the properties as you need such as service name and user that it should run as.

Start window Servicesin C#.Net

Develop & Install window Service in C#

Sunday, June 12, 2016

Looping through resutset in Table Valued Function

Database CASKoenigDB

alter function [dbo].[getFullMonthforRC](@TrainerID int,@CourseSDate datetime,@CourseEDate datetime,@LocationId int,@weekendstatus varchar(30),@courselist nvarchar(max)) 
returns  @TableofDates table(TrainerID int not null,trngdate datetime not null,locationid int not null) 
Begin 
declare @trnid int 
declare @lnid int 
Declare @startDate datetime 
declare @weekendbatch varchar(30)
Declare @interestedCourses nvarchar(max)
Declare @excluddates  datetime  
Declare @dateval  datetime
Declare @Count int
Declare @Loopcount int
Declare @endDate datetime
set @trnid=@TrainerID 
set @startDate=@CourseSDate 
 
set @endDate=@CourseEDate 
set @lnid=@LocationId 
set @weekendbatch=@weekendstatus 
set @interestedCourses=@courselist
  While (@startDate<=@endDate) begin
  if exists(Select  cast (ExcludedDate as nvarchar(max))  from TRAN_EXCLUDEDAY where InterestedCourseId=@interestedCourses)
  begin
  --counting total records
   Select @Count=count(*) from dbo.Split ( (Select  cast (ExcludedDate as nvarchar(max))  from TRAN_EXCLUDEDAY where InterestedCourseId=@interestedCourses),';')
   Set @Loopcount=1
   While  @Loopcount<=@Count
   begin
    Select @dateval=items from( Select *,ROW_NUMBER()over(Order by items)ID from dbo.Split ( (Select  cast (ExcludedDate as nvarchar(max))  from TRAN_EXCLUDEDAY where InterestedCourseId=@interestedCourses),';') ) RC where ID=@Loopcount 
   
    Set @Loopcount=@Loopcount+1
    if (@dateval=@startDate)  begin
      
       set @startDate=DATEADD(DAY, 1, @startDate)
    end
   
   end
   if  (@startDate<=@endDate) begin
     --print @startDate
     INSERT INTO @TableOfDates(TrainerID,trngdate,locationid) VALUES (@trnid,@startDate,@lnid) 
     set @startDate=DATEADD(DAY, 1, @startDate)
   end
  end
  else if not exists(Select  cast (ExcludedDate as nvarchar(max))  from TRAN_EXCLUDEDAY where InterestedCourseId=@interestedCourses )begin 
    --print @startDate
    INSERT INTO @TableOfDates(TrainerID,trngdate,locationid) VALUES (@trnid,@startDate,@lnid) 
    set @startDate=DATEADD(DAY, 1, @startDate)
  end 
end   
  
return 
End 

Saturday, June 11, 2016

Looping through resultset without using cursor

Database:CasKoenigDB

Declare @dateval as datetime

Declare @Count int

Declare @Loopcount int

Select IDENTITY(int, 1,1) ID,items into #Temp from dbo.Split ( (Select cast (ExcludedDate as nvarchar(max)) from TRAN_EXCLUDEDAY where InterestedCourseId=1707),';')

Select @Count=@@ROWCOUNT

Set @Loopcount=1

While @Loopcount<=@Count

begin

Select @dateval=items from #Temp where ID=@Loopcount

Set @Loopcount=@Loopcount+1

print @dateval



end
 
Drop table #Temp