Getting the Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON' - asp.net

I just setup my old pc to run SQL Server and VisualSVN. I have a laptop and another pc that i need to work on a website and that is why i setup subversion and sql server on a seperate pc. I have set up VisualSVN and ToirtoiseSVN but im getting SQL Server Problems below is how im connecting to the DB:
Imports API.Database
Public Class DatabaseHelper
Private _SqlServer As SQLServer
Public Sub New()
End Sub
Public ReadOnly Property SqlServer() As SQLServer
Get
If Me._SqlServer Is Nothing Then
Me._SqlServer = New API.Database.SQLServer("192.168.1.3", "sa", "xxxxx", "xxxxxx_xxxxxx_xxxxxx")
End If
Return Me._SqlServer
End Get
End Property
End Class
Public Sub New(ByVal server As String, ByVal username As String, ByVal password As String, ByVal database As String)
If server = "" Then
server = "(local)"
//server = "localhost"
End If
If username = "" Then
username = "sa"
End If
Dim connectionString As String = String.Format("Data Source={0};Initial Catalog={3};Integrated Security=True;Persist Security Info=False;User ID={1};Password={2};", server, username, password, database)
//''''''Dim connectionString As String = String.Format("Data Source={0};Initial Catalog={3};User ID={1};Password={2};", server, username, password, database)
//''Dim connectionString As String = ConfigurationManager.ConnectionStrings("chatterconnectionstring").ConnectionString
Try
Me._SQLConnection = New SqlConnection(connectionString)
Me._SQLConnection.Open()
Catch ex As Exception
If True Then
Throw ex
End If
End Try
End Sub
I have read a few articles and found that becuase i am running the SQL Server on another location and my web project on an IIS in another location this is why i am getting permission problems but how do i fix this?
I am using SQL Server 2008 Express R2 and Visual Studio 2008.

Try setting Integrated Security=false in your connection string

Related

WordPress login VB.NET

I am trying to create a Visual Basic code to verify the correctness of the wordpress login information
The original topic is here: Wordpress HttpWebrequest vb.net
Now the code gives a good result if the data is correct
But it gives an error if the data is wrong, I want to create an ( if )condition so that if the data is correct it gives an ( ok )message and if it is wrong it gives a message without errors or stops
the code :
Imports CookComputing.XmlRpc
<XmlRpcUrl("localhost/demo2/xmlrpc.php")>
Public Interface createContact
<CookComputing.XmlRpc.XmlRpcMethod("blogger.getUserInfo")>
Function GandiContact(ByVal city As String, ByVal apikey As String, ByVal s As String, ByVal params As XmlRpcStruct) As XmlRpcStruct
End Interface
Public Class Form1
Public clientProtocol As XmlRpcClientProtocol
Private Sub IpAddress()
Dim params As New XmlRpcStruct
Dim proxy = XmlRpcProxyGen.Create(Of createContact)()
clientProtocol = CType(proxy, XmlRpcClientProtocol)
clientProtocol.Expect100Continue = True
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
Try
Dim response = proxy.GandiContact("1", "USERNAME", "PASSWORD", params)
TxtResult.Text = "USERNAME" & " : " & "PASSWORD"
MsgBox("ok")
Catch ex As Exception
End Try
End Sub

SQL Server connection remains open, even after closing

I have a website that is designed to multi-tiered. My code works, but I have noticed that the larger my app becomes, the more SQL database connections start to stack up and remain open. This eventually causes this error:
System.InvalidOperationException: 'Timeout expired. The timeout
period elapsed prior to obtaining a connection from the pool. This
may have occurred because all pooled connections were in use and max
pool size was reached.'
My code is split into 3 layers. They are:
Application layer. Every time it wants to CRUD, is calls the Business Layer.
Business Layer - does business logic. When it wants to interface with the MS SQL db, it connects via ConnectionAdapter layer.
The ConnectionAdapter inherits from a SqlConnectionAdapter class and does the actual db interactions.
The following is pseudo code for each:
Application
My application may call the business layer multiple times. Particularly when doing AJAX requests. An example would be like:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
Dim dp As New DataProxy
Dim listOfObs As New List(Of MyObject)
dim someId as integer = 1
Try
If Not Page.IsPostBack Then
listOfObs = dp.ExampleReadFuncion(someId)
End If
Catch ex As Exception
Throw
Finally
dp.dispose()
dp = Nothing
SetMenue()
End Try
End Sub
DatatProxy (business layer)
Public Class DataProxy
Dim scConAdapter As New ConnectionAdapter
Public Sub New()
Try
scConAdapter.Connect()
Catch ex As Exception
Throw
End Try
End Sub
Public Sub dispose()
scConAdapter.Dispose()
End Sub
Private Shared Sub Main()
End Sub
Public Function ExampleReadFuncion(ByVal someId As Integer) As List(Of MyObject)
Dim successFactor As LogStatusEnum = LogStatusEnum.INFO
Dim newEx As Exception = Nothing
Dim conn As New ConnectionAdapter
Dim myObj As ActivityMarker
Dim listOfObs As New List(Of MyObject)
Dim dr As SqlDataReader = Nothing
Try
successFactor = LogStatusEnum.INFO
conn.Connect()
dr = conn.ExampleReadFuncion(someId)
Using dr
If (dr.HasRows = True) Then
While dr.Read
myObj = New myObj
myObj.Marker_Id = dr.Item("id")
myObj.Acitvity_Id = dr.Item("someValue")
listOfObs.Add(myObj)
End While
End If
End Using
Return listOfObs
Catch ex As Exception
successFactor = LogStatusEnum.ERRORS
Throw
Finally
dr.Close()
dr = Nothing
conn.Dispose()
conn = Nothing
End Try
End Function
End class
ConnectionAdapter
Public Class ConnectionAdapter
Inherits SqlConnectionAdapter
Public Sub New()
End Sub
Public Function ExampleReadFuncion(ByVal someId As Integer) As SqlDataReader
Try
Dim dr As SqlDataReader = Nothing
Dim selectString As New StringBuilder
Dim cmd As SqlCommand = Nothing
Try
cmd = CreateCommand()
selectString.Append("SELECT * " & vbCrLf)
selectString.Append("FROM " & vbCrLf)
selectString.Append("dbo.mytable " & vbCrLf)
selectString.Append("WHERE " & vbCrLf)
selectString.Append("id = #SOME_ID " & vbCrLf)
With cmd
.CommandType = CommandType.Text
.CommandText = selectString.ToString
.Parameters.Add("#SOME_ID", SqlDbType.Int).Value = someId
dr = .ExecuteReader
End With
Catch ex As Exception
Throw
Finally
cmd.Dispose()
End Try
Return dr
Catch ex As Exception
Throw ex
End Try
End Function
end class
SqlConnectionAdapter
Public MustInherit Class SqlConnectionAdapter
Protected CurrentTransaction As SqlTransaction
Public Property db As SqlConnection
Public Property Password As String
Public Property TNSName As String
Public Property User As String
Public Property DBName As String
Public Property PortNumber As Integer
Public Overridable Sub Dispose()
Try
If Not CurrentTransaction Is Nothing Then
CurrentTransaction.Commit()
End If
Catch ex As Exception
Throw
Finally
If Not db Is Nothing Then
db.Close()
db.Dispose()
db = Nothing
End If
End Try
End Sub
Public Overridable Sub Connect()
Try
Dim appSettings = ConfigurationManager.AppSettings
If (appSettings("releaseVersion") = "DEBUG") Then
Connect(appSettings("db_sqlHost"), appSettings("db_sqlDb"))
Else
Connect(appSettings("db_sqlHost"), appSettings("db_sqlPort"), appSettings("db_sqlDb"), appSettings("db_sqlUser"), appSettings("db_sqlPassword"))
End If
Catch ex As Exception
Throw
End Try
End Sub
Public Sub Connect(ByVal GetServername As String, ByVal GetDatabaseName As String)
Try
TNSName = GetServername
DBName = GetDatabaseName
db = New SqlConnection
db = SqlConnectionUtilities.GetConnection(GetServername, GetDatabaseName)
Catch ex As Exception
Throw
End Try
End Sub
Public Sub Connect(ByVal GetServerName As String, ByVal GetPort As Long, ByVal GetDatabase As String, ByVal GetUsername As String, ByVal Getpassword As String)
Try
User = GetUsername
Password = Getpassword
PortNumber = GetPort
DBName = GetDatabase
TNSName = GetServerName
db = New SqlConnection
db = SqlConnectionUtilities.GetConnection(GetServerName, GetPort, GetDatabase, GetUsername, Getpassword)
Catch ex As Exception
Throw
End Try
End Sub
Protected Function CreateCommand() As SqlCommand
Dim ret As SqlCommand = Nothing
Try
ret = db.CreateCommand
If Not CurrentTransaction Is Nothing Then
ret.Transaction = CurrentTransaction
End If
Catch ex As Exception
Throw
Finally
End Try
Return ret
End Function
Public Sub BeginTransaction()
If CurrentTransaction Is Nothing Then
CurrentTransaction = db.BeginTransaction
End If
End Sub
Public Sub CommitTransaction()
If Not CurrentTransaction Is Nothing Then
CurrentTransaction.Commit()
CurrentTransaction.Dispose()
CurrentTransaction = Nothing
End If
End Sub
Public Sub RollbackTransaction()
If Not CurrentTransaction Is Nothing Then
CurrentTransaction.Rollback()
CurrentTransaction.Dispose()
CurrentTransaction = Nothing
End If
End Sub
Protected Overrides Sub Finalize()
MyBase.Finalize()
End Sub
End Class
Utilities class
Public Class SqlConnectionUtilities
Public Shared Property connectionString As String
Public Shared Function GetConnection(ByVal ServerName As String, ByVal Port As String, ByVal Database As String, ByVal username As String, ByVal password As String) As SqlConnection
Dim connString As New StringBuilder
Dim con As SqlConnection
Try
connString.Append("Server=tcp:" & ServerName & "," & Port & ";")
connString.Append("Initial Catalog = " & Database & "; Persist Security Info=False;")
connString.Append("User ID = " & username & ";")
connString.Append("Password = " & password & ";")
connString.Append("MultipleActiveResultSets = False;")
connString.Append("Encrypt = True;TrustServerCertificate=False;Connection Timeout=30;")
connectionString = connString.ToString
con = New SqlConnection(connString.ToString)
con.Open()
Return con
Catch ex As Exception
Throw
End Try
End Function
Public Shared Function GetConnection(ByVal Servername As String, ByVal DatabaseName As String) As SqlConnection
Dim ConnectString As String
Dim con As SqlConnection
Try
ConnectString = "Data Source=" & Servername & ";Initial Catalog=" & DatabaseName & ";Integrated Security=True"
connectionString = ConnectString
con = New SqlConnection(ConnectString)
con.Open()
Return con
Catch ex As Exception
Throw
End Try
End Function
End class
I can tell that connections are remaining open by running this SQL statement:
SELECT
DB_NAME(dbid) as DBName,
COUNT(dbid) as NumberOfConnections,
loginame as LoginName
FROM
sys.sysprocesses
WHERE
dbid > 0
GROUP BY
dbid, loginame
I set up break points when my DataProxy class is called. I run the SQL code and can see a new connection is opened. Then, I run the code again when I dispose of the DataProxy class and I can see the connection remains. This will build up until it hits 101 connections, then it causes the above error. How am I not handling the connections correctly?
System.InvalidOperationException: 'Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.'
How am I not handling the connections correctly?
You are "leaking" connections. IE you have some code path that opens a SqlConnection, and doesn't Close/Dispose it. The SqlConnection remains open and is sitting on the managed heap. Eventually it will be GC'd and its Finalizer will close the connection. But if you leak 100 connections before that happens, you get this error.
So you need to ensure that your SqlConnections are always closed using a USING block, or are managed by some other object that's closed with a USING block.
Note that if you are returning a SqlDataReader from a function, there's a special CommandBehavior that will close the SqlConnection when the SqlDataReader is closed.
No, even this code not work and it wait a few minutes to remove sql connection from sql server.
using (var conn = new SqlConnection(connStr))
{
conn.Open();
conn.Close();
}
GC.Collect();
GC.WaitForPendingFinalizers();

AppPool identity instead of Current User only when Impersonating from Class Library (dll)

We have a class library of some common methods we use throughout multiple web apps and we are having an issue with our Impersonation class. When using impersonation with LogonUser in each individual application, Environment.UserName returns the user who is using the application. But when we call it within our class library's impersonation using block, it returns as the AppPool identity.
Returns username of client:
Declare Function LogonUser Lib "advapi32.dll" (ByVal lpszUsername As String, ByVal lpszDomain As String, ByVal lpszPassword As String, ByVal dwLogonType As Integer, ByVal dwLogonProvider As Integer, ByRef phToken As IntPtr) As Integer
If (LogonUser(Config.AdminUser, Config.AdminDomain, Config.AdminPassword, 9, 0, token) <> 0) Then
Dim newIdentity As WindowsIdentity = New WindowsIdentity(token)
Using impersonatedUser As WindowsImpersonationContext = newIdentity.Impersonate()
name = Environment.UserName
End Using
End If
Returns app pool username:
Imports Class.Library
Using admin As New Impersonation
name = Environment.UserName
End Using
HttpContext.Current.User.Identity.Name seems to return the username we are looking for but we cannot see why Environment.UserName works effectively when on the server, but only when it doesn't use our custom class library's dll reference. Here is a look at our impersonation class:
Public Class Impersonation : Implements IDisposable
Private impersonationContext As WindowsImpersonationContext = Nothing
Declare Auto Function LogonUser Lib "advapi32.dll" (ByVal lpszUsername As String, ByVal lpszDomain As String, ByVal lpszPassword As String, ByVal dwLogonType As Integer, ByVal dwLogonProvider As Integer, ByRef phToken As IntPtr) As Integer
Declare Auto Function RevertToSelf Lib "advapi32.dll" () As Boolean
Declare Auto Function CloseHandle Lib "kernel32.dll" (ByVal handle As IntPtr) As Boolean
Declare Auto Function DuplicateToken Lib "advapi32.dll" (ByVal hToken As IntPtr, ByVal impersonationLevel As Integer, ByRef hNewToken As IntPtr) As Integer
Private Shared newIdentity As WindowsIdentity
Private Shared token As New IntPtr(0)
Public Sub New(Optional ByVal userName As String = "", Optional ByVal password As String = "", Optional ByVal domainName As String = Config.AdminDomain)
If userName = "" Then
userName = Config.AdminUser
End If
If password = "" Then
password = Config.AdminPassword
End If
Dim logonType As Integer = 9
impersonationContext = ImpersonateUser(userName, domainName, password, logonType)
End Sub
Private Sub Undo()
If impersonationContext IsNot Nothing Then
impersonationContext.Undo()
End If
End Sub
Private Shared Function ImpersonateUser(ByVal userName As String, ByVal domain As String, ByVal password As String, ByVal logonType As Integer) As WindowsImpersonationContext
Dim res As WindowsImpersonationContext = Nothing
Dim tempWindowsIdentity As WindowsIdentity = Nothing
Dim token As IntPtr = IntPtr.Zero
Dim tokenDuplicate As IntPtr = IntPtr.Zero
Try
If (RevertToSelf()) Then
If LogonUser(userName, domain, password, logonType, 0, token) Then
If DuplicateToken(token, 2, tokenDuplicate) <> 0 Then
tempWindowsIdentity = New WindowsIdentity(tokenDuplicate)
Return tempWindowsIdentity.Impersonate()
Else
Throw New Win32Exception(Marshal.GetLastWin32Error())
End If
Else
Throw New Win32Exception(Marshal.GetLastWin32Error())
End If
Else
Throw New Win32Exception(Marshal.GetLastWin32Error())
End If
Finally
If token <> IntPtr.Zero Then
CloseHandle(token)
End If
If tokenDuplicate <> IntPtr.Zero Then
CloseHandle(tokenDuplicate)
End If
End Try
Return res
End Function
Private disposedValue As Boolean = False
Protected Overridable Sub Dispose(ByVal disposing As Boolean)
If Not Me.disposedValue Then
Undo()
End If
Me.disposedValue = True
End Sub
Public Sub Dispose() Implements IDisposable.Dispose
Dispose(True)
GC.SuppressFinalize(Me)
End Sub
End Class
I have a feeling that it has something to do with the dll file being on the server and when we use the using block, Environment.UserName gets the username from where the process is running on the server. But I can't see why it would work initially when creating a New WindowsIdentity() within the method that uses the impersonation not when we reference it from our dll since they are both running on the server.
Essentially, HttpContext.Current.User.Identity.Name has become an issue for us when we are running things locally and trying to debug issues that arise. We would like, 1. an answer to why this is happening for knowledge purposes and 2. a possible resolution if their even is any beyond HttpContext.Current.User.Identity.Name. (answers in VB or C# are welcomed.)
I resolved my issue by creating a new method in my class library:
Public Shared Function Current() As String
If Not HttpContext.Current.Request.IsLocal Then
Dim id As String = HttpContext.Current.User.Identity.Name
Return id.Substring(4)
Else
Return Environment.UserName
End If
End Function
If the code is run on the server, it uses HttpContext to pull the domain\username. Then I substringed out the domain (our domain is only three chars).
If it is run locally, I return Environment.UserName
I call this string within my web app by simply referencing the class and method (Employees.Current)

Getting SQL Server error: "There is already an object named '<my table>' in the database. " when table is NOT in database

In my Visual Basic 2013 ASP.NET web application project running on Windows 7 Pro, I get this error every time I run it.
If I drop my table before running it, my app creates table, but I get error.
If table exists before running it, app tries to create table, ignores error and continues, but I get error.
The Page_Load function steps through as expected, without error, to the end.
And then the error occurs.
Imports System.Data.SqlClient
Public Class WebForm2
Inherits System.Web.UI.Page
Private ConnectionString As String = "Integrated Security=SSPI;" + "Initial Catalog=;" + "Data Source=localhost;"
Private reader As SqlDataReader = Nothing
Private conn As SqlConnection = Nothing
Private cmd As SqlCommand = Nothing
Private sql As String = Nothing
Public Const DEBUG_DEFAULT_CLIENT_ID = "NATIONS_BURGERS"
Public Const DEBUG_DEFAULT_JOB_ID = "FRY_COOK_2014_07_05"
Public client_ID
Public job_ID
Public client_job_table
' InitializeS the job application page.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
' Initialize data:
client_ID = DEBUG_DEFAULT_CLIENT_ID
job_ID = DEBUG_DEFAULT_JOB_ID
client_job_table = client_ID + "_" + job_ID
' App selects client job table :
Dim command_successful =
ExecuteSQLStmt(" select * from " + client_job_table)
' Create table if it doesn't exist:
If Not command_successful Then
ExecuteSQLStmt("CREATE TABLE " + client_job_table + _
"(" + _
"FIRST_NAME varchar(255)," + _
"LAST_NAME varchar(255)," + _
"PHONE varchar(255)" + _
");")
End If
set_22_button.Visible = GridView1.Visible
set_333_button.Visible = GridView1.Visible
End Sub
' Sends sql command to ehires database.
Private Function ExecuteSQLStmt(ByVal sql As String)
' Open the connection
ConnectionString = "Data Source=<my IP>;Initial Catalog=<my database name>;Persist Security Info=True;User ID=Doug;Password=ThankYou!!"
Dim connection As New SqlConnection(ConnectionString)
connection.ConnectionString = ConnectionString
connection.Open()
cmd = New SqlCommand(sql, connection)
Dim command_successful = True
On Error Resume Next
cmd.ExecuteNonQuery()
If Err.Number Then
command_successful = False
Dim reason = Err.Description
Else
command_successful = True
End If
connection.Close()
Return command_successful
End Function 'ExecuteSQLStmt
Your connection string doesn't specify the catalog name (the database name) so your query is executed against the "MASTER" database. If you look there probably you will find the table that you think is not present
Private ConnectionString As String = #"Integrated Security=SSPI;" & _
"Initial Catalog=.....database name here;" & _
"Data Source=localhost;"
The problem was that I was using a GridView UI control to look at the table, but the GridView was not being updated, so never showed that table was already there.
Problem solved by updating GridView.

File Permissions Error using load balancers

I have a problem with logging. I have a class I use to log events, in my ASP.net application, to a text file. The class seems to work fine. Complications arise, though, because we are using a load balancer. We run our app on two servers. If one server fails, the load balancer will switch the web application to the other server. I can also direct the browser to specify which server to view the application on.
The problem is that when I go to one server, the application can log just fine. But if i try to switch to the other server, I get this error:
Exception Details: System.UnauthorizedAccessException: Access to the path '\myServer-qa\plantshare\someFolder\myApp\Logs\2012_12_14.txt' is denied.
ASP.NET is not authorized to access the requested resource. Consider
granting access rights to the resource to the ASP.NET request
identity. ASP.NET has a base process identity (typically
{MACHINE}\ASPNET on IIS 5 or Network Service on IIS 6) that is used if
the application is not impersonating. If the application is
impersonating via , the identity will be
the anonymous user (typically IUSR_MACHINENAME) or the authenticated
request user.
To grant ASP.NET access to a file, right-click the file in Explorer,
choose "Properties" and select the Security tab. Click "Add" to add
the appropriate user or group. Highlight the ASP.NET account, and
check the boxes for the desired access.
If i delete the file, which ever server creates it first will be fine but the other will fail. If i check the files permissions only the server that created it will have permission. Is this an issue with my code or IIS? Also, We use windows authentication. Here is the class I use to write:
Imports System.Net
Imports System.IO
Public Class logger
Private Shared _thisInstance As logger
Private Shared InstanceLock As New Object
Private Shared FileLock As New Object
Private _path As String
Public Property path() As String
Get
Return _path
End Get
Set(ByVal value As String)
_path = value
End Set
End Property
Protected Sub New(ByVal path As String)
Me.path = path
End Sub
Public Shared Function GetSingleton(ByVal path As String) As logger
SyncLock InstanceLock
If _thisInstance Is Nothing Then
_thisInstance = New logger(path)
End If
End SyncLock
Return _thisInstance
End Function
Private Function checkDir(ByVal path As String) As Boolean
Dim dir As New DirectoryInfo(path)
Dim exist As Boolean = True
If Not dir.Exists Then
Try
dir.Create()
Catch ex As Exception
exist = False
End Try
End If
Return exist
End Function
Private Function checkFile(ByVal path As String) As Boolean
Dim myFile As New FileInfo(path)
Dim exist As Boolean = True
Dim objWriter As IO.StreamWriter
Dim fs As FileStream
If Not myFile.Exists Then
Try
fs = New FileStream(path, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.ReadWrite)
objWriter = New System.IO.StreamWriter(fs)
objWriter.Close()
objWriter.Dispose()
fs.Close()
fs.Dispose()
Catch ex As Exception
exist = False
Finally
End Try
End If
Return exist
End Function
'updates file
Public Sub Logger(ByVal filePath As String, ByVal Message As String, ByVal title As String, Optional ByVal stkTrace As String = "")
Dim sw As StreamWriter
Dim fs As FileStream
Dim path As String
Dim now As DateTime = DateTime.Now
Dim today As String
today = Date.Now.ToString("yyy/MM/dd")
path = Me.path & today.Replace("/", "_") & ".txt"
If checkFile(path) Then
SyncLock FileLock
fs = New FileStream(path, FileMode.Append)
sw = New StreamWriter(fs)
Try
sw.WriteLine("Title: " & title)
sw.WriteLine("Message: " & Message)
sw.WriteLine("StackTrace: " & stkTrace)
sw.WriteLine("Date/Time: " & now.ToString("yyyy/MM/dd HH:mm:ss"))
sw.WriteLine("================================================")
sw.Flush()
Catch ex As Exception
Throw
Finally
sw.Close()
fs.Close()
sw.Dispose()
fs.Dispose()
End Try
End SyncLock
End If
End Sub
End Class

Resources