calling oracle stored procedure from asp.net application - asp.net

in my asp.net application, i am calling a stored procedure (oracle) to get some values from database.
Following is the sp:
create or replace PROCEDURE GetUserData(
--SQLWAYS_EVAL# ARCHAR(100)
UserName IN NVARCHAR2, v_refcur OUT SYS_REFCURSOR)
as
BEGIN
BEGIN --SQLWAYS_EVAL# =#Password;
open v_refcur for SELECT StaffId,
UserName,
Password,
Pin,
LastUpdateId,
LastUpdateDate,
FullName,
PinFailedAttempts,
PinFailedDate
FROM UserData
WHERE UserName = UserName;
END;
RETURN;
END;
Can anyone help me how to call this sp from my asp.net code.

Using ODP, you'll can do something like the following:
make your stored procedure a function that takes the user name in parameter and returns a refcursor
create or replace FUNCTION GetUserData(UserName IN NVARCHAR2) RETURN SYS_REFCURSOR;
and then
using (var connection = new OracleConnection(connectionString))
{
using (var command = new OracleCommand("GetUserData", connection))
{
command.CommandType = CommandType.StoredProcedure;
command.BindByName = true;
// Return value parameter has to be added first !
var returnValueParameter = new OracleParameter();
returnValueParameter.Direction = ParameterDirection.ReturnValue;
returnValueParameter.OracleDbType = ParameterDirection.RefCursor;
command.Parameters.Add(returnValueParameter);
var userNameParameter = command.Parameters.Add("UserName", userName);
returnValueParameter.Direction = ParameterDirection.In;
using (OracleDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
// Read the current record's fields
}
}
}
}

The Microsoft Enterprise Library simplifies the discovery and binding of Oracle Stored Procedures. It is not too difficult to build a Data Access Layer between your Business Objects and the Oracle database. I am more a fan of ORM tools these days like DevExpress's XPO, which in the latest release supports calling stored procedures. However, the Microsoft Entlib is free whereas DevExpress is not.
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Your.BusinessObjects;
namespace DataAccess
{
public class UserDataDAL
{
public static Database dataBase = DatabaseFactory.CreateDatabase(); ///< Use default connection string configured in web.config
public static List<UserInfo> GetData(string userName)
{
List<UserInfo> listOfUserInfo = new List<UserInfo>();
UserInfo userInfo;
DbCommand cmd = dataBase.GetStoredProcCommand("SCHEMA.GETUSERDATA");
dataBase.DiscoverParameters(cmd);
dataBase.SetParameterValue(cmd, "USERNAME", userName);
using (IDataReader dr = dataBase.ExecuteReader(cmd))
{
while (dr.Read())
{
userInfo = new UserInfo();
userInfo.StaffId = dr["STAFFID"] != DBNull.Value ? Convert.ToInt32(dr["STAFFID"]) : 0;
userInfo.UserName = dr["USERNAME"] != DBNull.Value ? Convert.ToString(dr["USERNAME"]) : String.Empty;
userInfo.Password = dr["PASSWORD"] != DBNull.Value ? Convert.ToString(dr["PASSWORD"]) : String.Empty;
userInfo.LastUpdateId = Convert.ToInt32(dr["LASTUPDATEID"]);
userInfo.LastUpdateDate = dr["LASTUPDATEDATE"] != null ? Convert.ToDateTime(dr["LASTUPDATEDATE"]) : new DateTime();
listOfUserInfo.Add(userInfo);
}
}
return listOfUserInfo;
}
}
}
If you only ever expect one row to be returned from the procedure, then you can return the first item in the list if present etc.

Related

IDataReader Unity + SQLite

I'm creating a Unity project (version 2019) + SQLite + VSCode.
I added the appropriate plugins in the project folder but I still have the following error:
Assets \ BancoSQLite.cs (33,17): error CS0433: The type 'IDataReader' exists in both 'System.Data, Version = 4.0.0.0, Culture = neutral, PublicKeyToken = b77a5c561934e089' and 'netstandard, Version =
2.0.0.0.0 , Culture = neutral, PublicKeyToken = cc7b13ffcd2ddd51 '
I did everything but I can't come up with a solution.
Script SQLite
using System.Collections;
using System.Collections.Generic;
using System.Data;
using Mono.Data.SqliteClient;
using UnityEngine;
using UnityEngine.UI;
public class BancoSQLite : MonoBehaviour {
//private IDbConnection connection;
//private IDbCommand command;
//private IDataReader reader;
public InputField ifLogin;
public InputField ifSenha;
public string senha;
public string login;
private string dbName = "URI=file:SQLiteDB.db";
private void Connection () {
Debug.Log("Entrou");
using (var connection = new SqliteConnection (dbName)) {
connection.Open ();
using (var command = connection.CreateCommand ()) {
connection.Open ();
command.CommandText = "CREATE TABLE IF NOT EXISTS usuario (id INTEGER PRIMARY KEY AUTOINCREMENT, login VARCHAR(30), senha VARCHAR(30));";
command.ExecuteNonQuery();
command.CommandText = "SELECT " + ifLogin + " FROM usuario;";
//IDataReader login = command.ExecuteNonQuery();
IDataReader reader = command.ExecuteNonQuery();
Debug.Log(login);
}
}
}
// Start is called before the first frame update
void Start () {
Connection ();
}
// Update is called once per frame
void Update () {
}
}
None of this is for the specific issue in the question, but when you solve that the code will run into these things, too:
select ifLogin from usario is wrong. You need select * from usuario where login = ifLogin. And make sure to use parameterized queries; sooner or later string concatenation for this WILL break your database.
Additionally, if you want to see the results use ExecuteReader(), ExecuteScalar(), or Fill() a dataset/table. ExecuteNonQuery() is for INSERT/UPDATE/DELETE and doesn't give you results for SELECT.

Mono SQLite: System.InvalidCastException: Specified cast is not valid

i am trying to insert this command in a dynamic way in a unity project:
public static string insertPlayerCmd = "INSERT INTO Player (Name) VALUES (?);";
I am using this method on a repository to insert a name into the database:
public AccountContents SaveAccount(string newName)
{
string name = newName;
var transaction = Finder.DB.DatabaseConnection.BeginTransaction();
var command = Finder.DB.DatabaseConnection.CreateCommand();
AccountContents newAccountContents = null;
try
{
command.CommandText = ConstantDbRequests.insertPlayerCmd;
command.Parameters.Add(newName);
var newAccount = command.ExecuteReader();
transaction.Commit();
newAccountContents = new AccountContents(newAccount.GetInt32(0), newAccount.GetString(1));
}
catch (Exception e)
{
Debug.Log(e.ToString());
}
return newAccountContents;
}
the line command.Parameters.Add(newName); throws an invalid cast exception.
I verified my database in SQLite, and the column to insert is of Text type, all the names on the SQL command are writen correctly, but i can't add the parameter to replace the ? wildcard

No mapping exists from object type X to a known managed provider native type error while executing storedProcedure with ServiceStack OrmLite?

This is code:
using (var con = GetWriteConnection())
{
int res = con.Exec(cmd =>
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#Title",Title));
cmd.CommandText = "AddTitle";
return int.Parse(cmd.ExecuteScalar().ToString());
});
return res;
}
there is no Title table.This is complex object. It is serialized to string(nvarchar(MAX)) by ServiceStack.OrmLite.
How can use ServiceStack's serializer?
var str=OrmLiteConfig.DialectProvider.GetQuotedValue(Title, typeof(Title));
str=str.SubString(1,str.Length-2); // (Clearing Quotes)
UPDATE Title.ToJsv() does not work. Because there is "_type" in string.

Remove role and recovery the role in the table

for a mistake. I used a wrong command. I wanted to remove an user' role from the table aspnet_UsersInRoles.
I guess that the command might be
Roles.RemoveUserFromRole(userName, origin_role);
However I used a wrong command mistakenly.
Roles.DeleteRole(origin_role,false);
Originally the table has 4 roles. Now the RoleId in the table only has two,
61572264-4935-461d-9d8c-71f147f28c34
c09f25e6-fd6a-447b-8e0d-eba0cfc94e40
How can I find and recovery them?
Many many thanks.
Hate to say it, but you're hosed. The default ASP.Net providers don't include any sort of auditing or soft-delete. If you have a database backup, you can explore/restore from that.
Below you find the source code for the function you called.
It calls the dbo.aspnet_Roles_DeleteRole stored procedure.
I don't have access to an asp.net membership database at the moment, otherwise I would check for you.
You might want to check what the stored procedure does, but as ssyladin mentioned I doubt you will be able to recover anything (since you sent the throwOnPopulatedRole argument to false).
public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
{
SecUtility.CheckParameter(ref roleName, true, true, true, 256, "roleName");
try {
SqlConnectionHolder holder = null;
try {
holder = SqlConnectionHelper.GetConnection(_sqlConnectionString, true);
CheckSchemaVersion( holder.Connection );
SqlCommand cmd = new SqlCommand("dbo.aspnet_Roles_DeleteRole", holder.Connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandTimeout = CommandTimeout;
SqlParameter p = new SqlParameter("#ReturnValue", SqlDbType.Int);
p.Direction = ParameterDirection.ReturnValue;
cmd.Parameters.Add(p);
cmd.Parameters.Add(CreateInputParam("#ApplicationName", SqlDbType.NVarChar, ApplicationName));
cmd.Parameters.Add(CreateInputParam("#RoleName", SqlDbType.NVarChar, roleName));
cmd.Parameters.Add(CreateInputParam("#DeleteOnlyIfRoleIsEmpty", SqlDbType.Bit, throwOnPopulatedRole ? 1 : 0));
cmd.ExecuteNonQuery();
int returnValue = GetReturnValue(cmd);
if( returnValue == 2 )
{
throw new ProviderException(SR.GetString(SR.Role_is_not_empty));
}
return ( returnValue == 0 );
}
finally
{
if( holder != null )
{
holder.Close();
holder = null;
}
}
}
catch
{
throw;
}
}

Datastructures problem in asp.net/c#

I have a e-commerce web application which allows users to buy software components in my website. I'm retrieving the invoice number and the software component title that was bought by the user from UserTransactionHistory table in sql server. I'm storing them in arraylist with the help of a SoftwareTitles Class
public class SoftwareTitles
{
string softwareTitle;
string invoiceNumber;
public SoftwareTitles(string softwareTitle, string invoiceNumber)
{
this.softwareTitle = softwareTitle;
this.invoiceNumber = invoiceNumber;
}
string InvoiceNumber
{
get
{
return this.invoiceNumber;
}
}
string SoftwareTitle
{
get
{
return this.softwareTitle;
}
}
}
}
And I'm adding this class to arraylist in this manner.
ConnectionToSql con1 = new ConnectionToSql();
string connectionString = con1.ConnectionStringMethod();
SqlConnection sqlConnection = new SqlConnection(connectionString);
SqlCommand cmd2 = new SqlCommand("SelectionOfSoftwareTitles", sqlConnection);
cmd2.CommandType = CommandType.StoredProcedure;
sqlConnection.Open();
SqlDataReader dr2 = cmd2.ExecuteReader();
if (dr2.HasRows)
{
while (dr2.Read())
{
String softwareTitle = (String)dr2[0];
String invoiceNumber = (String)dr2[1];
softwareTitlesArray.Add(new SoftwareTitles(softwareTitle, invoiceNumber));
int i = 0;
}
}
sqlConnection.Close();
dr2.Close();
But when I want to retrieve all the software titles that are associated with a certain Invoice number. I'm not able to do it.
Am i doing it properly ?? Is arraylist appropriate data structure for such operation ?? How should I do it ?
I would personally use a non-generic list object.
To declare:
List<Software> softwareTitles= New List<Software>();
And the object software:
if (dr.HasRows)
{
while (dr.Read())
{
string title = dr["TITLE_COLUMN"];
int invoice = dr["INVOICE_COLUMN"];
Software s = new Software();
s.Title = title;
s.Invoice = invoice;
softwareTitles.add(s);
}
}
and then you can traverse through the list using a simple loop and counter like, softwareTitles(i) or you can even use LINQ to accomplish whatever you want to do.
e.g.
for (i=0; i<softwareTitles.Count;i++)
{
if (softwareTitles[i].Invoice==213)
{
Console.WriteLine(softwareTitles[i].Title);
}
}
Somthing like that. Sorry I am using VB.NET lately, so my C# has become rusty. But it seems correct
Use Generic List Collection to add the Objects and Linq to Query the Records.

Resources