Error while starting the server in a server-client program - vb.net

Im working on a server-client program in Visual Studio 2015. Here im getting an error saying that the socketException was unhandled. The error is near 'Server.Start()'. The rest of the code is not displaying any error hence didnt post it.
Imports System.IO
Imports System.Net
Imports System.Net.Sockets
Imports System.Threading
Public Class TCPControl
Public Event MessageReceived(sender As TCPControl, Data As String)
' SERVER CONFIG
Public ServerIP As IPAddress = IPAddress.Parse("10.0.0.253")
Public ServerPort As Integer = 64555
Public Server As TcpListener
Private CommThread As Thread
Public IsListening As Boolean = True
' CLIENTS
Private Client As TcpClient
Private ClientData As StreamReader
Public Sub New()
Server = New TcpListener(ServerIP, ServerPort)
Server.Start()
CommThread = New Thread(New ThreadStart(AddressOf Listening))
CommThread.Start()
End Sub

Related

vb TCP client application breaks trying to read server response

Can anyone tell me why my code freezes up at "Return sockReader.ReadLine()"? Thank you. I'm trying to get information back from my Raspberry Pi server when I send a command using "Public Sub Send" and the code is getting stuck.
Imports System.Net
Imports System.Net.Sockets
Imports System.IO
Public Class TCPControl
Public sock As TcpClient
Public DataStream As StreamWriter
Public DataGet As TcpListener
Private netStream As NetworkStream
Private sockReader As StreamReader
Public Sub New(Host As String, Port As Integer)
' CLIENT
sock = New TcpClient(Host, Port)
netStream = sock.GetStream()
sockReader = New StreamReader(netStream)
DataStream = New StreamWriter(sock.GetStream)
Dim localAddr As IPAddress = IPAddress.Parse("172.16.2.104")
DataGet = New TcpListener(localAddr, 6969)
End Sub
Public Sub Send(Data As String)
DataStream.Write(Data & vbCrLf)
DataStream.Flush()
End Sub
Public Function Receive()
Dim howMany As Integer = sock.Available()
If netStream.DataAvailable Then
Return sockReader.ReadLine()
End If
Return howMany
End Function
End Class

What am I doing wrong, calling a rest api

I am new to .Net (any help will be greatly appreciated) and I am trying to implement this class to write to a rest api. All it does is pass in some data and does a postAsJsonAsync to the service.
It was written in C# and converted to VB.net to be added into a VB.net application solution.
It works once and then fails on the second call to it, when it initialises another instance of Uri.
Exception thrown: 'System.InvalidOperationException' in System.Net.Http.dllequest."}{"This instance has already started one or more requests. Properties can only be modified before sending the first request."}
Code here:
Imports System.Collections.Generic
Imports System.Configuration
Imports System.Linq
Imports System.Text
Imports System.Threading.Tasks
Imports System.Net.Http
Imports System.Net.Http.Headers
Namespace Logging
Public Class LogMessage
Public Property Application As String
Public Property Area As String
Public Property Activity As String
Public Property Description As String
Public Property User As String
End Class
Public Class ActionLogging
Public Shared Client As New HttpClient()
Public Shared Function AddToActionLog(Activity As String, Description As String, User As String)
Dim message = New LogMessage() With { _
.Activity = Activity, _
.Description = Description, _
.User = User, _
.Application = ConfigurationManager.AppSettings("Application"), _
.Area = ConfigurationManager.AppSettings("Area") _
}
If Run(message) IsNot Nothing
Run(message).Wait()
End If
End Function
Public Shared Function CreateMessage(message As LogMessage) As Uri
Dim task = Client.PostAsJsonAsync("Action", message)
task.Wait()
Dim response As HttpResponseMessage = task.Result
response.EnsureSuccessStatusCode()
Return response.Headers.Location
End Function
Public Shared Function Run(message As LogMessage) As Task
Client.BaseAddress = new Uri(ConfigurationManager.AppSettings("RestAPIServer"))
Client.DefaultRequestHeaders.Accept.Clear()
Client.DefaultRequestHeaders.Accept.Add(New MediaTypeWithQualityHeaderValue("application/json"))
CreateMessage(message)
End Function
End Class
End Namespace
Imports System.Configuration
Imports System.Threading.Tasks
Imports System.Net.Http
Imports System.Net.Http.Headers
Namespace Logging
Public Class LogMessage
Public Property Application As String
Public Property Area As String
Public Property Activity As String
Public Property Description As String
Public Property User As String
End Class
Public Class ActionLogging
Private ReadOnly Shared Client As New HttpClient() With {.BaseAddress = new Uri(ConfigurationManager.AppSettings("RestAPIServer"))}
public Sub New()
Client.DefaultRequestHeaders.Accept.Clear()
Client.DefaultRequestHeaders.Accept.Add(New MediaTypeWithQualityHeaderValue("application/json"))
End Sub
Public Shared Function AddToActionLog(activity As String, description As String, user As String)
Dim message = New LogMessage() With { _
.Activity = Activity, _
.Description = Description, _
.User = User, _
.Application = ConfigurationManager.AppSettings("Application"), _
.Area = ConfigurationManager.AppSettings("Area") _
}
SendMessage(message)
End Function
Private Shared Sub SendMessage(message As LogMessage)
Dim task = Client.PostAsJsonAsync("Action", message)
task.Wait()
Dim response As HttpResponseMessage = task.Result
response.EnsureSuccessStatusCode()
End Sub
End Class
End Namespace

Strange 'Dispose' Error when calling with 'Using' or directly calling 'DIspose'

I have this code which works:
Option Strict On
Imports System
Imports System.IO
Imports System.ServiceModel
Imports System.ServiceModel.Description
...
Private Property Channel As IWSOServiceContract
Public Sub SomeMethod(ByVal url As String)
Using ChlFactory As ChannelFactory(Of IWSOServiceContract) = New ChannelFactory(Of IWSOServiceContract)(New WebHttpBinding(), url)
ChlFactory.Endpoint.Behaviors.Add(New WebHttpBehavior())
Channel = ChlFactory.CreateChannel()
End Using
End Sub
...
But then when I refactor it to:
Option Strict On
Imports System
Imports System.IO
Imports System.ServiceModel
Imports System.ServiceModel.Description
...
Private Property ChlFactory As ChannelFactory(Of IWSOServiceContract)
Private Property Channel As IWSOServiceContract
Public Sub SomeMethod(ByVal url As String)
ChlFactory = New ChannelFactory(Of IWSOServiceContract)(New WebHttpBinding(), url)
ChlFactory.Endpoint.Behaviors.Add(New WebHttpBehavior())
Channel = ChlFactory.CreateChannel()
ChlFactory.Dispose() '<-- ERROR HERE BUT HOW DID USING WORK BEFORE?
End Sub
...
Am completely at a loss without any explanation of why there is an error "Dispose is not a member of ChannelFactory" in the second method but not in the first method?
That's because ChannelFactory implements IDisposable.Dispose explicitly. You'd have to cast it to IDisposable to call Dispose.
Using statement is smart enough to do the casting for you.

Windows service unable write into event log

I have created the following report service but I am unable to log any thing in the EventLog. In the project settings I have set App Type as windows Service and Startup project as SUB Main... Can any one please suggest whats wrong with the code
Program.vb
Imports System.ServiceProcess
Namespace ReportingService
Public Class Program
Private Sub New()
End Sub
''' <summary>The main entry point for the application.</summary>
Private Shared Sub Main(args As String())
Dim ServicesToRun As ServiceBase()
ServicesToRun = New ServiceBase() {
New ReportingImmediate()
}
ServiceBase.Run(ServicesToRun)
End Sub
End Class
End Namespace
ReportService.vb
Imports System.ServiceProcess
Imports System.Timers
Imports System.Configuration
Public Class ReportingImmediate
Inherits ServiceBase
#Region "Members"
Private ReadOnly time As Timer
Private ReadOnly rptHelper As ReportingHelper
Private ReadOnly timeInterval As String
#End Region
Public Sub New()
' Initialize Logs
InitializeComponent()
' Initialize other components
time = New Timer()
timeInterval = ConfigurationManager.AppSettings("ImmediateReRunInterval") '10000
time.Interval = Integer.Parse(timeInterval)
AddHandler time.Elapsed, AddressOf TimeElapsed
rptHelper = New ReportingHelper()
End Sub
#Region "Timer Event"
''' <summary>time Elapsed</summary>
''' <param name="sender">The object that raised the event sender</param>
''' <param name="e">Event data passed to the handler e</param>
Private Sub TimeElapsed(sender As Object, e As ElapsedEventArgs)
time.Enabled = False
rptHelper.WriteToEventLog("Logging Report Service")
' Enable the Timer
time.Enabled = True
time.Interval = Integer.Parse(timeInterval)
End Sub
#End Region
#Region "Service Events"
''' <summary>On Start</summary>
''' <param name="args">Arguments</param>
Protected Overrides Sub OnStart(args As String())
time.Enabled = True
End Sub
''' <summary>On Stop</summary>
Protected Overrides Sub OnStop()
time.Enabled = False
End Sub
#End Region
End Class
ReportHelper.vb
Imports System.Data.OleDb
Imports System.Configuration
Imports System.Threading.Tasks
Imports System.IO
Imports System.IO.Packaging
Imports System.Text
Imports System.Net.Mail
Imports System.Net
Public Class ReportingHelper
Public Function WriteToEventLog(ByVal entry As String, Optional ByVal appName As String = "ReportingService", Optional ByVal eventType As _
EventLogEntryType = EventLogEntryType.Information, Optional ByVal logName As String = "RepotingServiceImmediate") As Boolean
Dim objEventLog As New EventLog
Try
'Register the Application as an Event Source
If Not EventLog.SourceExists(appName) Then
EventLog.CreateEventSource(appName, logName)
End If
'log the entry
objEventLog.Source = appName
objEventLog.WriteEntry(entry, eventType)
Return True
Catch Ex As Exception
Return False
End Try
End Function
End Class
Your service will not be able to EventLog.CreateEventSource because it does not run as an administrator (ref: the Note in the Remarks section of EventLog.CreateEventSource Method):
To create an event source in Windows Vista and later or Windows Server 2003, you must have administrative privileges.
The reason for this requirement is that all event logs, including security, must be searched to determine whether the event source is unique. Starting with Windows Vista, users do not have permission to access the security log; therefore, a SecurityException is thrown.
As you should not run your service as an administrator, the solution is to write a small program which you run with Administrator privileges to create the event source.
The Try...Catch in DWPReportingHelper.WriteToEventLog may be hiding an error from you.

how can i use ActiveDirectory

I have an active Directory (window) on the server ..and i want to connect it with my web pages..
this is my vb code:
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Data
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.DirectoryServices ' cannot be found '
Imports System.Runtime.InteropServices
Imports System.Configuration
Imports System.Data.SqlClient
Partial Class Default3
Inherits System.Web.UI.Page
Public Function IsADUser(ByVal UserName As [String], ByVal Password As [String]) As [Boolean]
Dim entry As New DirectoryEntry()
entry.Username = UserName
entry.Password = Password
Dim searcher As New DirectorySearcher(entry)
searcher.Filter = "(objectclass=user)"
Dim Authentecated As [Boolean] = False
Try
searcher.FindOne()
Authentecated = True
Catch ex As COMException
Authentecated = False
End Try
Return (Authentecated)
End Function
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
End Class
The ASP.NET Membership supports Active Directory as well. Check it out:
http://msdn.microsoft.com/en-us/library/ms998360.aspx
To use Active Directory manually, you should add System.DirectoryServices.dll as a reference before.