System.IO.IOException Eror - Process Can not access file to Read... - vb.net

My website uses adatabase for geoLocating the clients country.
Here is my error code:
System.IO.IOException
Inner Exception:
The process cannot access the file 'C:\*****\******\wwwroot\GEO2db\GeoLite2-Country.mmdb' because it is being used by another process.
And Here is the code that I run to get the country from the database (it is called in my master page):
Public Function GetGeoIPCountry() As String
If HttpContext.Current.Request.IsLocal Then
Return ""
End If
Dim ip As String = HttpContext.Current.Request.ServerVariables("REMOTE_ADDR")
Dim FileWithPath As String = HttpContext.Current.Server.MapPath("~") & "GEO2db\GeoLite2-Country.mmdb"
Dim reader = New DatabaseReader(FileWithPath)
Dim Om = reader.Omni(ip)
Dim country As String = Om.Country.Name
reader.Dispose()
Return country
End Function

Related

how to get windows version for remote computer using code

I'm developing small app using visual studio 2013, VB to scan range of IP addresses in same network
my app will take IP's and return
Ping status (True or False)
Computer Name
MAC address
and all OK
my question is if i need to get remote computer windows (xp or 7 or 8 )
using IP address or computer name how i can do that?
Dim osVer As String
osVer = System.Environment.OSVersion.ToString
Finally I used system management as below
(after importing System.Management)
I used two Functions
first one to connect remote Computer then collect data
Private Function tryConnect(SystemName As String)
Try
Dim ComputerConnection As New System.Management.ConnectionOptions
' to add user name and password
'ComputerConnection.Username = "UserName"
'ComputerConnection.Password = "Password"
With ComputerConnection
.Impersonation = System.Management.ImpersonationLevel.Impersonate
.Authentication = System.Management.AuthenticationLevel.Packet
End With
'connect to WMI
MyMgtScope = New System.Management.ManagementScope("\\" & SystemName & "\root\CIMV2", ComputerConnection)
MyMgtScope.Connect()
Return MyMgtScope.IsConnected
Catch ex As Exception
Return False
End Try
End Function
private sub GetOsdata()
if tryConnect(remoteComputerName) = False then Exit Sub ' or show some message
Dim MyMgtScope As System.Management.ManagementScope
Dim MyObjSearcher As System.Management.ManagementObjectSearcher
Dim MyColl As System.Management.ManagementObjectCollection
Dim MyObj As System.Management.ManagementObject
Dim ComputerOSVersion , ComputerOSServiceBack ,OSbit As String
MyObjSearcher = New System.Management.ManagementObjectSearcher(MyMgtScope.Path.ToString, "Select * FROM Win32_OperatingSystem")
' Execute the query
MyColl = MyObjSearcher.Get
For Each MyObj In MyColl
ComputerOSVersion = MyObj.GetPropertyValue("Caption").ToString
ComputerOSServiceBack = MyObj.GetPropertyValue("ServicePackMajorVersion").ToString
OSbit = MyObj.GetPropertyValue("OSArchitecture").ToString
Next
MyObjSearcher = Nothing
MyColl = Nothing
End Sub
Using wClient As New WebClient
dim myip as string = wClient.DownloadString("http://tools.feron.it/php/ip.php")
End Using
maybe help for find ip easly. good luck

VB.NET Return Form Object using Form Name

I'm basically writing a custom Error Logging Form for one of my applications because users cannot be trusted to report the errors to me.
I am obtaining the Form Name using the 'MethodBase' Object and then getting the DeclaringType Name.
Dim st As StackTrace = New StackTrace()
Dim sf As StackFrame = st.GetFrame(1)
Dim mb As MethodBase = sf.GetMethod()
Dim dt As String = mb.DeclaringType.Name
How can I then use this to obtain the Form Object so I can pass this to my 'screenshot method' that screenshots the particular form referenced.
Public Sub SaveAsImage(frm As Form)
'Dim fileName As String = "sth.png"
'define fileName
Dim format As ImageFormat = ImageFormat.Png
Dim image = New Bitmap(frm.Width, frm.Height)
Using g As Graphics = Graphics.FromImage(image)
g.CopyFromScreen(frm.Location, New Point(0, 0), frm.Size)
End Using
image.Save(_LogPath & Date.Now.ToString("ddMMyyyy") & ".png", format)
End Sub
I posted the same solution to a similar question. Try this:
Dim frm = Application.OpenForms.Item(dt)

query an exchange distribution list

I'm trying to find some code that I can use in vb.net 4.0 to query the our exchange 2013 server. It will be housed on a web server and that server does not have outlook installed on it. Looks like I need to use EWS to do this but I've tried a lot of code snippets and still have not been able to figure this out. The distribution list i'm trying to query is in the public folders/Office Contacts. I've tried examples that use nesting to go through the public folder seen there is no deep traversal but I'm not doing something right there. I am not posting code because i'm not sure it would help. I was hoping someone has already done this and would give me some nuggest of info to get me started.
The examples I've found do not query the distribution list but rather add to it. It's not that I haven't tried... I've got hundreds of lines of code from different places that I've tried and tried to learn from.. but i'm not getting it done. Anyway.. help would be great.
Sorry about not posting any code.. I actually thought I deleted this post.. but i'll post the code that is now working for me. This code does a query to the public folder and then grabs some of the data about each contact in that contact list.
Public Sub MS()
Dim oTheListS As New List(Of TheList)
Dim service As New ExchangeService(ExchangeVersion.Exchange2010_SP1)
service.Credentials = New WebCredentials("userid", "password")
service.AutodiscoverUrl("email#address")
'Get Public Folder
Dim sf As SearchFilter = New SearchFilter.IsEqualTo(FolderSchema.DisplayName, "Office Contacts")
Dim rrRes As FindFoldersResults = service.FindFolders(WellKnownFolderName.PublicFoldersRoot, sf, New FolderView(1))
Dim OfficeContacts As Folder = rrRes.Folders(0)
'Find the Distribution List
Dim dlSearch As SearchFilter = New SearchFilter.IsEqualTo(ContactGroupSchema.DisplayName, "Merit Board")
Dim ivItemView As New ItemView(1)
Dim fiResults As FindItemsResults(Of Item) = OfficeContacts.FindItems(dlSearch, ivItemView)
If fiResults.Items.Count = 1 Then
'Enumeate Members
Dim cg As ContactGroup = DirectCast(fiResults.Items(0), ContactGroup)
cg.Load()
For Each gm As GroupMember In cg.Members
Dim o As New TheList
o = MS2(gm.AddressInformation.Address)
oTheListS.Add(o)
'Dim o As New TheList
'Dim ncCol As NameResolutionCollection = service.ResolveName(gm.AddressInformation.Address, ResolveNameSearchLocation.ContactsOnly, True)
'With o
' .Name = gm.AddressInformation.Name
' .Email = gm.AddressInformation.Address
'End With
'oTheListS.Add(o)
Next
End If
End Sub
Public Function MS2(pEmail As String) As TheList
Dim o As New TheList
Dim service As New ExchangeService(ExchangeVersion.Exchange2010_SP1)
service.Credentials = New WebCredentials("userid", "password")
service.AutodiscoverUrl("email#address")
Dim sf As SearchFilter = New SearchFilter.IsEqualTo(FolderSchema.DisplayName, "Office Contacts")
Dim rrRes As FindFoldersResults = service.FindFolders(WellKnownFolderName.PublicFoldersRoot, sf, New FolderView(1))
Dim OfficeContacts As Folder = rrRes.Folders(0)
'Find the Distribution List
Dim dlSearch As SearchFilter = New SearchFilter.IsEqualTo(ContactSchema.EmailAddress1, pEmail)
Dim ivItemView As New ItemView(1)
Dim fiResults As FindItemsResults(Of Item) = OfficeContacts.FindItems(dlSearch, ivItemView)
If fiResults.Items.Count = 1 Then
Dim con As Contact = fiResults.Items(0)
'Dim ncCol As NameResolutionCollection = service.ResolveName(gm.AddressInformation.Address, ResolveNameSearchLocation.ContactsOnly, True)
With o
If con.DisplayName IsNot Nothing Then
.Name = con.DisplayName
End If
Dim em As New EmailAddress
If con.EmailAddresses.TryGetValue(EmailAddressKey.EmailAddress1, em) = True Then
.Email = con.EmailAddresses(EmailAddressKey.EmailAddress1).ToString
End If
If con.JobTitle IsNot Nothing Then
.Title = con.JobTitle
End If
Dim phy As New PhysicalAddressEntry
If con.PhysicalAddresses.TryGetValue(PhysicalAddressKey.Business, phy) = True Then
.Address = con.PhysicalAddresses(PhysicalAddressKey.Business)
End If
If con.PhoneNumbers.TryGetValue(PhoneNumberKey.BusinessPhone, String.Empty) = True Then
.PhoneBusiness = con.PhoneNumbers(PhoneNumberKey.BusinessPhone)
End If
If con.PhoneNumbers.TryGetValue(PhoneNumberKey.MobilePhone, String.Empty) = True Then
.PhoneMobile = con.PhoneNumbers(PhoneNumberKey.MobilePhone)
End If
If con.CompanyName IsNot Nothing Then
.Comapny = con.CompanyName
End If
End With
End If
Return o
End Function
Public Class TheList
Public Property Name As String
Public Property Email As String
Public Property PhoneMobile As String
Public Property PhoneBusiness As String
Public Property Comapny As String
Public Property Title As String
Public Property Address As PhysicalAddressEntry
End Class
I just got it working so I haven't started to refine it yet.. but hopefully this will help someone else as I didn't find any code that did this

CovrageInfo.CreateFromFile is giving an error

I have replicated the code from the example to collect the result for code coverage from Here except that my code is vb.net
Here is my code
Imports Microsoft.VisualStudio.Coverage.Analysis
Module Module1
Sub Main()
Using info As CoverageInfo = CoverageInfo.CreateFromFile("C:MyFile\data.coverage")
Dim lines As New List(Of BlockLineRange)()
For Each [module] As ICoverageModule In info.Modules
Dim coverageBuffer As Byte() = [module].GetCoverageBuffer(Nothing)
Using reader As ISymbolReader = [module].Symbols.CreateReader()
Dim methodId As UInteger = 0
Dim MethodName As String = ""
Dim undecoratedMethodName As String = ""
Dim ClassName As String = ""
Dim NameSpaceName As String = ""
lines.Clear()
While reader.GetNextMethod(methodId, MethodName, undecoratedMethodName, ClassName, NameSpaceName, lines)
Dim stats As CoverageStatistics = CoverageInfo.GetMethodStatistics(coverageBuffer, lines)
Console.WriteLine("Method {0}{1}{2}{3}{4} has:" & NameSpaceName & ClassName & undecoratedMethodName)
Console.WriteLine(" blocks covered are {0}", stats.BlocksCovered)
End While
End Using
Next
End Using
End Sub
End Module
When I run this on the line for CreateFromFile i get a ImageNotFoundException
Image File "C:\SomeAddress\MyServer\UnitTest.dll" could not be found
I have already as per instructions added the neccessary dlls to my project copied and the other 2 as references.
And yet another tumbleweed moment....
Basically the problem was that folder containing my coverage file also had to contains all the dlls used within that assembely that tests were ran on in order to create that object.
hope this helps you if you ever stumbled over this issuen :)

Why do I get parameter not supplied error while using stored procedure in script component?

Problem:
Trying to create an SSIS job using SQL Server 2005 BIDS. Job includes a Script Task and an Email Task. The script task fails at the last step and gets this error:
Failed to open a rowset. Details: ADO Error Code: 0x Source: Microsoft
OLE DB Provider for SQL Server Description: Procedure or function
'usp_xtal_InHouse_Penetration_Summary' expects parameter '#DateStart',
which was not supplied.
SQL State: 42000 Native Error: Failed to open a rowset. Error in File
C:\DOCUME~1\TEMP~1.SUM\LOCALS~1\Temp\1\auto_Inhouse_Leads_Penetration
{5DA4C113-6AFC-4EB2-94E8-7D0F12E03C52}.rpt: Failed to open a rowset.
I believe the issue is due to the report being called is running off a Stored procedure and I'm not sure if the report will actually pass the params to the SP. The reason I think this is because the error is a SQL error stating the very first param it is looking for is not being supplied. The SP is only looking for the params being declared in this script and the script is declaring, setting, and loading the params in the exact same order as the SP.
We have other reports running running off similar SSIS jobs but none of them are using a SP.
Any thoughts would be appreciated.
The following script I am providing has several msgbox()'s at various places checking to see if variables are being loaded correctly and that the script executes to that point. It fails with the above mentioned error at the last one.
Public Class ScriptMain
Public Sub Main()
'
Dim CrystalReportViewer1 As New CrystalDecisions.Windows.Forms.CrystalReportViewer
Dim DiskOpts1 As New CrystalDecisions.Shared.DiskFileDestinationOptions
Dim myExportOptions1 As New CrystalDecisions.Shared.ExportOptions
DiskOpts1.DiskFileName = "\\10.200.0.7\c$\Jobs\Arrivals\WeeklyInhousePenetrationReport.pdf"
myExportOptions1.ExportFormatType = myExportOptions1.ExportFormatType.PortableDocFormat
myExportOptions1.ExportDestinationType = CrystalDecisions.Shared.ExportDestinationType.DiskFile
myExportOptions1.ExportDestinationOptions = DiskOpts1
' Verify the path to the Crystal Report's .RPT file:
Dim strReportPath1 As String = "\\10.200.0.7\c$\Jobs\Arrivals\auto_Inhouse_Leads_Penetration.rpt"
If Not System.IO.File.Exists(strReportPath1) Then
Throw (New Exception("Unable to locate report file:" & _
vbCrLf & strReportPath1))
End If
' Load the Crystal report's .RPT file:
Dim cr1 As New CrystalDecisions.CrystalReports.Engine.ReportDocument
'Dim ParamVal1 As New ParameterDiscreteValue
'Dim ParamVal2 As New ParameterDiscreteValue
Dim ParamVal3 As New ParameterDiscreteValue
Dim ParamVal4 As New ParameterDiscreteValue
Dim ParamVal5 As New ParameterDiscreteValue
cr1.Load(strReportPath1)
'Set the logon credentials of the main report---change these values
LogonToDatabase(cr1.Database.Tables, "SomeInstance", "SomeUserName", "SomePassword")
'ParamVal1.Value = 2
'ParamVal2.Value = False
ParamVal3.Value = DateAdd(DateInterval.Day, -15, Date.Today)
ParamVal4.Value = DateAdd(DateInterval.Day, -8, Date.Today)
ParamVal5.Value = "All"
MsgBox(ParamVal3.Value, , "Param 3") 'Good to here
'cr1.SetParameterValue("param_SiteID", ParamVal1)
'cr1.SetParameterValue("param_Detail", ParamVal2)
cr1.SetParameterValue("DateStart", ParamVal3)
cr1.SetParameterValue("DateEnd", ParamVal3)
cr1.SetParameterValue("Agent", ParamVal3)
MsgBox(ParamVal4.Value, , "ParamVal4") 'Good to here
' Set the CrystalReportViewer's appearance and set the ReportSource:
' This may not be needed but I kept them anyhow
CrystalReportViewer1.ShowRefreshButton = False
CrystalReportViewer1.ShowCloseButton = False
CrystalReportViewer1.ShowGroupTreeButton = False
CrystalReportViewer1.ReportSource = cr1
MsgBox(ParamVal5.Value, , "ParamVal5") 'Good to here
cr1.Export(myExportOptions1) ' Failing at this step
MsgBox(ParamVal3.Value, , "ParamVal3") 'Never gets here
'
Dts.TaskResult = Dts.Results.Success
End Sub
Private Sub LogonToDatabase(ByVal ReportTables As CrystalDecisions.CrystalReports.Engine.Tables, ByVal ServerName As String, ByVal UserId As String, ByVal Password As String)
' To Supply Logon Information to each and every Tables used in the Report
Dim myTable As CrystalDecisions.CrystalReports.Engine.Table
Dim myConnectionInfo As New CrystalDecisions.Shared.ConnectionInfo()
Dim myLogonInfo As New CrystalDecisions.Shared.TableLogOnInfo()
myConnectionInfo.UserID = UserId
myConnectionInfo.Password = Password
myConnectionInfo.ServerName = ServerName
myLogonInfo.ConnectionInfo = myConnectionInfo
For Each myTable In ReportTables
myTable.ApplyLogOnInfo(myLogonInfo)
Next
End Sub
End Class