PDA

View Full Version : استفاده از SQLDependency در ویندوز سرویس



Naghibi
سه شنبه 27 آبان 1393, 11:52 صبح
سلام
من به ویندوز سرویس نوشتم و می خوام از سرویس SQLDependency استفاده کنم تا تغییرات دیتابیس رو بهم اعلام کنه. ولی به یه خطایی برخورددم که نمیدونم چه جوری برطرفش کنم. کسی از دوستان میتونه منو راهنمایی کنه؟
125824

hadi2345
جمعه 30 آبان 1393, 08:10 صبح
با سلام ، اتفاقا من از این روش استفاده میکنم و مشکلی ندارم. فقط کدها رو که مرور میکردم این کدی که ارور میگیره اصلا لازم نیست.

من توابعی که استفاده میکنم رو همین جا کپی میکنم شما میتونی راحت تغییرش بدی و استفاده کنی.

فقط این رو بگم که من تغییرات یک جدول در دیتابیس رو درون گرید نمایش میدم . با هر تغییر ، گرید رفرش میشه و رکورد(های) جدید اضافه میشن.

ابتدا در Form_Load تابع GetNames رو فراخوانی میکنم. کد این تابع :


Public Sub GetNames()

If Not DoesUserHavePermission() Then
Return
End If

connectionString = UNIS_Cnn

Grd_Clocks.DataSource = Nothing

' You must stop the dependency before starting a new one.
' You must start the dependency when creating a new one.
SqlDependency.Stop(connectionString)
SqlDependency.Start(connectionString)

Dim cn As SqlConnection = New SqlConnection(connectionString)

Dim objDA As New SqlDataAdapter
Dim MDT As New DataTable
Dim objCmd As New SqlCommand

Dim MStrSQL As String = "SELECT C_Date, C_Time, L_TID, L_UID, L_Result FROM dbo.tEnter"


objCmd.CommandType = CommandType.Text
objCmd.CommandText = MStrSQL
objCmd.Connection = cn

objDA.SelectCommand = objCmd
objCmd.CommandTimeout = 50

objCmd.Notification = Nothing

Dim dep As SqlDependency = New SqlDependency(objCmd)
AddHandler dep.OnChange, AddressOf dep_onchange

If cn.State = ConnectionState.Closed Then cn.Open()

Try

objDA.Fill(MDT)

Grd_Clocks.DataSource = MDT
Grd_Clocks.RetrieveStructure()

Catch ex As Exception

MsgBox("error")

End Try


End Sub



این هم دو تابع مورد نیاز دیگه :




Private Function DoesUserHavePermission() As Boolean

Try
Dim clientPermission As SqlClientPermission = New SqlClientPermission(Security.Permissions.Permissio nState.Unrestricted)

' this will throw an error if the user does not have the permissions
clientPermission.Demand()

Return True

Catch ex As Exception

Return False

End Try

Return True

End Function




Private Sub dep_onchange(ByVal sender As System.Object, ByVal e As System.Data.SqlClient.SqlNotificationEventArgs)

' this event is run asynchronously so you will need to invoke to run on the UI thread(if required)
If Me.InvokeRequired Then
Grd_Clocks.BeginInvoke(New MethodInvoker(AddressOf GetNames))
Else
GetNames()
End If

' this will remove the event handler since the dependency is only for a single notification
Dim dep As SqlDependency = DirectCast(sender, SqlDependency)
RemoveHandler dep.OnChange, AddressOf dep_onchange

End Sub



اسم گریدم Grd_Clock هست.

موفق باشید.