Accessing SQL Server database from multiple webpages through asp.net - asp.net

I am a new developer.
I have a problem of creating a website that needs to access one user account and retrieve all his information in that database through different webpages like one page for viewing his profile data; another page to view the exams that he already created ... etc.
What I did was for each single aspx page I had to create a new object and connect to the SQL Server database from that object which I feel there's something wrong with that.
The question is there any way that I can define the database object only once and make it accessible from different webpages in the same website and execute SQL queries from that object and retrieve data?
Thanks

We use this implementation using MVC...maybe you could adapt it to your needs:
clsConnectionManager
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Data.SqlClient
Imports System.Web.Configuration
Imports System.Data
Public Class clsConnectionManager
Implements IDisposable
<ThreadStatic> _
Private Shared pSqlConnection As SqlConnection
Private Shared pConnectionString As String
Public Shared ReadOnly Property Connection() As SqlConnection
Get
If pSqlConnection Is Nothing Then
pConnectionString = WebConfigurationManager.ConnectionStrings("DefaultConnection").ConnectionString
pSqlConnection = New SqlConnection(pConnectionString)
pSqlConnection.Open()
End If
If pSqlConnection.State = ConnectionState.Closed Then
pSqlConnection.Open()
End If
Return pSqlConnection
End Get
End Property
Public Sub Dispose() Implements System.IDisposable.Dispose
If pSqlConnection IsNot Nothing Then
pSqlConnection.Close()
End If
End Sub
End Class
Web.config
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=localhost;Initial Catalog=yourDBName;User ID=YourDBUserName;Password=YourUserPassword" providerName="System.Data.SqlClient" />
</connectionStrings>
Use
Inside your classes you could do something like this:
Public Sub dbGetAll()
Try
Using New clsConnectionManager()
Using lObjSQLCommand = New SqlClient.SqlCommand("StoredProcedureName", clsConnectionManager.Connection)
lObjSQLCommand.CommandType = CommandType.StoredProcedure
Using lObjSqlDataReader As SqlClient.SqlDataReader = lObjSQLCommand.ExecuteReader()
Do While lObjSqlDataReader.Read()
/*Read rows...*/
Loop
End Using
End Using
End Using
Catch ex As Exception
Throw ex
End Try
End Sub

You can define the connection settings in the web.config file and access the same in your.aspx page.
Refer http://www.connectionstrings.com/store-connection-string-in-webconfig/

Related

Serilog is missing log file entries for my ASP VB.NET web project

The following code works fine for one user on the web site.
However as soon an multiple users start logging in simultaneously, Serilog starts missing log file entries. Anybody know what I am missing please?
Public Class cLogger
Public Shared gSerilogger As ILogger = Nothing
Public Shared gblSeriLock As New Object
Public Shared Sub DoSerilog(ByVal sLogMessage As String)
SyncLock gblSeriLock
If gSerilogger Is Nothing Then
gSerilogger = New LoggerConfiguration().WriteTo.Console().WriteTo.File("d:\Logfiles\SERI.log").CreateLogger()
End If
gSerilogger.Information(sLogMessage)
End SyncLock
End Sub
End Class
Usage example:
cLogger.DoSerilog("Test")

Crystal Report over ASP.Net runtime data source change

Got a script to run crystal report over ASP.Net, export and send to email.
If I use the current database without applying logon everything works but if I change datasource (same database structure but different server) at runtime then the issue below.
Crystal 2008 runtime
ERROR:System.Runtime.InteropServices.COMException (0x80042018): The
table %1 does not exist in the document. at
CrystalDecisions.ReportAppServer.Controllers.DatabaseControllerClass.VerifyTableConnectivity(Object
Table) at
CrystalDecisions.CrystalReports.Engine.Table.TestConnectivity() at
ScriptCodeClass.ApplyLogon(ReportDocument cr, ConnectionInfo ci) at
ScriptCodeClass.Logon(ReportDocument cr, String server, String db,
String id, String pass) at ScriptCodeClass.FunCreatePDFView(String
lsHeader, String lsReportType, String msDatabaseUserId, String
msDatabasePassword)
this code can change authentication but not data source/server, wondering if need a reference or to import.
Imports System.Collections
Imports System.Data
Imports T1.Tb.Data
Imports System.IO
Imports System.Net
Imports System.Net.Mail
Imports T1.Tb
Imports T1.TB.Public
Imports CrystalDecisions.CrystalReports.Engine.ReportDocument
Imports CrystalDecisions.ReportSource
Imports System.Configuration
Imports System.Data.SqlClient
Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.Shared
References CrystalDecisions.CrystalReports.Engine
References CrystalDecisions.Shared
References System.Web.Services
References System.Data
References T1.Tb.dll
References T1.TB.Public
References T1.P1.dll
References T1.P1.Public
References T1.Tb.Fun
public shared function Logon(cr as ReportDocument, server as string, db as string, id as string, pass as string) as Boolean
'Use this to change the database logon info for a crystal report
dim ci as ConnectionInfo = new ConnectionInfo()
dim subObj as SubreportObject
ci.ServerName = server
ci.DatabaseName = db
ci.UserID = id
ci.Password = pass
if ApplyLogon(cr, ci) then
for each obj as ReportObject in cr.ReportDefinition.ReportObjects
If (obj.Kind = ReportObjectKind.SubreportObject) Then
// if typeof obj.Kind.GetType() is CrystalDecisions.Shared.ReportObjectKind then
subObj = ctype(obj, SubreportObject)
if not ApplyLogon(cr.OpenSubreport(subObj.SubreportName), ci) then
return(false)
end if
end if
next
Logon = True
end if
end function
private shared function ApplyLogon(cr as ReportDocument, ci as ConnectionInfo ) as Boolean
dim li as TableLogOnInfo
dim success as Boolean
for each tbl as Table in cr.Database.Tables
li = tbl.LogOnInfo
li.ConnectionInfo = ci
tbl.ApplyLogOnInfo(li)
'check if logon was successful
'if TestConnectivity returns false, check logon credentials
if tbl.TestConnectivity() then
'drop fully qualified table location
if tbl.Location.IndexOf(".") > 0 then
tbl.Location = tbl.Location.Substring(tbl.Location.LastIndexOf(".") + 1)
else
tbl.Location = tbl.Location 'THIS IS LINE LEFT OUT IN ALL SAMPLES I SAW
end if
else
success = false
exit for
end if
success = True
next
end function
try to build the query as string in code first then pass its results to crystal reports to have the report and send it by email.
steps:
1) build a query string.
2) execute that string and fill a datatable inside a dataset with the results
3) use that dataset / datatable to generate the report in crystal reports
You have several choices:
Add Key(s) in web.config as follow :
<add key="ServerName" value=""/> Name Or IP Address
<add key="DataBaseName" value=""/> Database Name
<add key="DatabaseUser" value=""/>User Name
<add key="DatabasePassword" value=""/>Password
and call these keys in your reportviewer on load or on your event as :
Dim SERVER_NAME As String = ConfigurationManager.AppSettings("ServerName").ToString()
Dim DATABASE_NAME As String = ConfigurationManager.AppSettings("DataBaseName").ToString()
Dim DatabaseUser As String = ConfigurationManager.AppSettings("DatabaseUser").ToString()
Dim DatabasePassword As String = ConfigurationManager.AppSettings("DatabasePassword").ToString()
add your code and login to DB
CrystalReportViewer.SetDatabaseLogon(DatabaseUser, DatabasePassword, SERVER_NAME, DATABASE_NAME)
then add your datasource:
CrystalReportViewer.SetDataSource
Or you can pass it directly through your viewer as follow:
CrystalReportViewer.SetDatabaseLogon("sa", "123", "Your_Server", "YourDB")

Switching databases with LINQ to SQL with proper authentication

I'm writing an ASP.NET (VS2013) web app that uses LINQ to SQL. The datacontext is created via the graphical interface and it works great. I need to switch from DEV to INT and then to PROD programmatically.
sounds simple and after reading many, many postings I'm super frustrated.
When I switch to DEV it works because the connection already exists. when I switch to INT it fails but NOT because the authentication but because the the Store Procedure doesn't exist... that makes NO sense...
can anyone please help me with tested statements??? (i already tried lots of "I think...")
----WP_LINQ2SQLDB.DESIGNER.VB----
Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Data.Linq
Imports System.Data.Linq.Mapping
Imports System.Linq
Imports System.Linq.Expressions
Imports System.Reflection
<Global.System.Data.Linq.Mapping.DatabaseAttribute(Name:="WorkOrder")> _
Partial Public NotInheritable Class WP_LinQ2SQLDataContext
Inherits System.Data.Linq.DataContext
Private Shared mappingSource As System.Data.Linq.Mapping.MappingSource = New AttributeMappingSource()
#Region "Extensibility Method Definitions"
Partial Private Sub OnCreated()
End Sub
#End Region
Public Sub New()
MyBase.New("", mappingSource)
OnCreated()
End Sub
Public Sub New(ByVal connection As String)
MyBase.New(connection, mappingSource)
OnCreated()
End Sub
etc...
----WP_LINQ2SQLDB.VB----
Inherits System.Data.Linq.DataContext
Private Sub OnCreated()
Dim connectionStr As String = Nothing
Select Case My.Settings.DB_to_Use
Case "DEV"
Case "INT"
connectionStr = "Data Source=SERVER\DBINST;Initial Catalog=CAT_Order;Integrated Security=True;"
Case "PRD"
End Select
Dim DB_TUAcct = My.Settings.DB_TUAcct
Dim DB_TUPwd = My.Settings.DB_TUPwd
connectionStr = connectionStr + "User ID=Domain\blah" + DB_TUAcct.ToUpper + ";Password=" + My.Settings.DB_TUPwd + ";"
----DEFAULT.VB----
' I've tried...
Dim dc As WP_LinQ2SQLDataContext = New WP_LinQ2SQLDataContext(temp)
Dim dc As WP_LinQ2SQLDataContext = New WP_LinQ2SQLDataContext(builder.ConnectionString)
' building a connection string from sql builder
Dim builder2 As IDbConnection = New SqlClient.SqlConnection(temp)
dc.Connection.ConnectionString = builder.ConnectionString
BUT at the end of the day, I cannot make the LINQ to fail because the connection string is bad... and I dont know to fix...

restrict access to doc files asp.net

i have a folder in my asp.net app conatining doc files that can be accessed only (dowwload) by a certain type of connected users(admin account or permitted other accounts)
how can i do that?
any ideas?
thanks in advance.
The App_Data folder in .NET is protected, and therefore ideal for this very purpose. I normally put sensitive files in here then have a page "ViewDoc.aspx" that performs the security checks and then sends the file to the user (using Response.Write).
Put sensitive files outside of web site root, so they can not be accessed by URL.
After that, use this HttpHandler (written in VB.NET) to serve files:
Public NotInheritable Class FileHandler
Implements IHttpHandler
Public ReadOnly Property IsReusable() As Boolean Implements System.Web.IHttpHandler.IsReusable
Get
Return False
End Get
End Property
Public Sub ProcessRequest(ByVal context As System.Web.HttpContext) Implements System.Web.IHttpHandler.ProcessRequest
If Not String.IsNullOrEmpty(context.Request.QueryString("FileName")) Then
Dim fileName As String = context.Request.QueryString("FileName")
Try
Dim filesPath As String = "D:\TheFiles\"
Dim fileInfo As New IO.FileInfo(filesPath & fileName)
If fileInfo.Exists Then
Dim fileExt As String = fileInfo.Extension.Remove(0, 1).ToUpperInvariant
If fileExt = "JPG" Then
context.Response.ContentType = "image/jpeg"
Else
context.Response.ContentType = "image/" & fileExt
End If
context.Response.TransmitFile(fileInfo.FullName)
End If
Catch ex As Exception
End Try
End If
End Sub
End Class
and register this handler in your web.config like this:
<httpHandlers>
<add verb="*" path="secfile.axd" type="MyApp.FileHandler, MyApp" validate="false"/>
</httpHandlers>
use like this:
<a href="secfile.axd?pic=sample.jpg" />
Remember adding your file types to handler and change response.contenttype by type of your file.
Using a handler is not the only way, you can use context.Response.TransmitFile(fileInfo.FullName) in your aspx file.
A simple way to do this is to NOT put these documents inside a folder of your ASP.NET app and instead, put it somewhere else in the file system that can't be accessed directly from the browser. Then programmatically, you can serve the file to the user if s/he's authorized to do so.

Update SINGLE field of a table in Access db

How do you update a single field in an Access database using an asp.net website in VisualStudio08. Assuming that the connection has been established, give step to step instructions of what to do in the design view.
Here is a console app that shows you how to use ADO.NET to update an Access DB.
An alternate is to use Linq.
You could add a method to your CodeBehind that does something like this, and call it from your OnClick event handler.
Option Explicit On
Option Strict On
Imports System
Imports System.Data
Imports System.Data.OleDb
Public Class Program
Public Shared Sub Main()
Dim connectionString As String = GetConnectionString()
Dim queryString As String = _
"UPDATE Categories Set CategoryName = 'ABC' WHERE CategoryID = 1;"
Using connection As New OleDbConnection(connectionString)
Dim command As OleDbCommand = connection.CreateCommand()
command.CommandText = queryString
Try
connection.Open()
Dim rowsAffected As Integer = command.ExecuteNonQuery()
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Using
End Sub
Private Shared Function GetConnectionString() As String
' To avoid storing the connection string in your code,
' you can retrieve it from a configuration file.
' Assumes Northwind.mdb is located in c:\Data folder.
Return "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" _
& "c:\Data\Northwind.mdb;User Id=admin;Password=;"
End Function
End Class
Assuming you want this done on some postback event like a button click, you need to (this is from memory, I don't have it in front of me!):
click on the button, show its properties, then the events tab.
double-click in the OnClick space to create a new event handler (or enter a name directly)
In the event handler in the code window, invoke some SQL something like
update table set field=value where field2=identifier
(or you could use the LINQ equivalent) Where table, field, field2, value and identifier should be replaced with specific names to suit your database.
You could create a SqlCommand::ExecuteNonQuery instance to run the SQL.

Resources