How Can I call Store procedure and a table in the same function in .net core repository? - api

I am making an API using ASP.netCore to fetch data from teradata. I have 2 store procedure on Teradata DB one for encryption one for description. What I want to achieve is when user call the get method to fetch data, my Store procedure should run first and then it should return all table to user(changed as SP).
I have tried a lot but didn't manage to find any way to call store procedure and Select * table together. If I run the only store procedure OR call only select * table it work. I want to call both (SP and select*) so first SP should run and change the data then return the changed data table.
My codes are following.
Codes for GetDataTable
public IEnumerable<myTable> GetData(IConfiguration _configuration)
{
try
{
myTable TableReturn = new myTable();
List<myTable> dataReturn = new List<myTable>();
var connectionString = _configuration.GetConnectionString("TeradataConnectionString");
using (var connection = new TdConnection(connectionString))
{
'Date_Of_Birth', ENCRYPTEDSTRING);";
TdCommand cmd = new TdCommand("SELECT * FROM Project.myTable;", connection) ;
TdCommand Db = (TdCommand)cmd;
Db.Connection = connection;
connection.Open();
TdDataReader reader = Db.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
var newTable = new myTable();
newTable.Employee_Id = (string)reader.GetString(0);
newTable.First_name = (string)reader.GetString(1);
newTable.Last_Name = (string)reader.GetString(2);
newTable.Date_Of_Birth = (string)reader.GetString(3);
newTable.Phone = (string)reader.GetString(4);
newTable.Em_Position = (string)reader.GetString(5);
dataReturn.Add(newTable);
}
}
else
{
Console.WriteLine("no rows found");
}
}
return dataReturn;
}
catch (Exception e)
{
throw new Exception();
}
}
My codes for store procedure are following
public IEnumerable<DecryptedData> DecryptedData(IConfiguration _configuration)
{
// DecryptedData DecryptedReturn = new DecryptedData();
List<DecryptedData> dataReturn = new List<DecryptedData>();
var connectionString = _configuration.GetConnectionString("TeradataConnectionString");
using (var connection = new TdConnection(connectionString))
{
string command = "CALL Project.Decryption(STATUS,'Project' ,'myTable', 'Date_Of_Birth', ENCRYPTEDSTRING);";
TdCommand cmd = new TdCommand(command, connection);
TdCommand Db = (TdCommand)cmd;
Db.Connection = connection;
connection.Open();
TdDataReader reader = Db.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
var DecryptedData = new DecryptedData();
DecryptedData.Date_Of_Birth = reader.GetString(1);
dataReturn.Add(DecryptedData);
Console.WriteLine(dataReturn);
}
}
else
{
Console.WriteLine("no rows found");
}
}
return dataReturn;
}

Related

Azure Logic Apps internal server error 500

Am trying to create a an azure function that is triggered in a Logic Apps,
The functions purpose is to web crawl certain web sites, take the desired information, compare that with a a SQL Server database in Azure, compare if we already have that information if not add it.
My issue is that when ever i run it I get the Server 500 error, I assume its accessing the database that cause. Help?
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log
)
{
log.LogInformation("C# HTTP trigger function processed a request.");
string RequestBody = await new StreamReader(req.Body).ReadToEndAsync();
{
return await CrawlBlog(0, RequestBody);
}
}
private static async Task<IActionResult> CrawlBlog(int Picker, string req)
{
int BlogPicker = Picker;
string TheResult = req;
//Get the url we want to test
var Url = "";
if (BlogPicker == 0)
{
Url = "*********";
}
else if (BlogPicker == 1)
{
Url = "*********";
}
/*
else if (BlogPicker == 2)
{
Url = "https://azure.microsoft.com/en-in/blog/?utm_source=devglan";
}
*/
else
{
TheResult = "False we got a wrong pick";
return (ActionResult)new OkObjectResult
( new {TheResult });
}
var httpClient = new HttpClient();
var html = await httpClient.GetStringAsync(Url);
var htmlDocument = new HtmlDocument();
htmlDocument.LoadHtml(html);
//a list to add all availabel blogs we found
var Blog = new List<BlogStats>();
switch (BlogPicker)
{
case 0:
{
var divs =
htmlDocument.DocumentNode.Descendants("div")
.Where(node => node.GetAttributeValue("class", "").Equals("home_blog_sec_text")).ToList();
foreach (var divo in divs)
{
var Blogo = new BlogStats
{
Summary = divo.Descendants("p").FirstOrDefault().InnerText,
Link = divo.Descendants("a").FirstOrDefault().ChildAttributes("href").FirstOrDefault().Value,
Title = divo.Descendants("a").FirstOrDefault().InnerText
};
Blog.Add(Blogo);
}
break;
}
case 1:
{
var divs =
htmlDocument.DocumentNode.Descendants("div")
.Where(node => node.GetAttributeValue("class", "").Equals("post_header_title two_third last")).ToList();
foreach (var divo in divs)
{
//string TheSummary = "we goofed";
var ThePs = divo.Descendants("p").ToList();
var Blogo = new BlogStats
{
Summary = ThePs[1].GetDirectInnerText(),
Link = divo.Descendants("a").LastOrDefault().ChildAttributes("href").FirstOrDefault().Value,
Title = divo.Descendants("a").FirstOrDefault().InnerText
};
Blog.Add(Blogo);
}
break;
}
}
TheResult = await SqlCheck(Blog[0].Title, Blog[0].Summary, Blog[0].Link); //error 500
return (ActionResult)new OkObjectResult
(
new
{
TheResult
}
);
}
public static async Task<string> SqlCheck(string Tit, string Sumy, string Lin)
{
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = "flygon.database.windows.net";
builder.UserID = "*****";
builder.Password = "********";
builder.InitialCatalog = "torkoal";
System.Data.DataSet ds = new System.Data.DataSet();
SqlConnection connection = new SqlConnection(builder.ConnectionString);
connection.Open();
SqlCommand CheckCommand = new SqlCommand("SELECT * FROM TableBoto WHERE Link = #id3 ", connection);
CheckCommand.Parameters.AddWithValue("#id3", Lin);
SqlDataAdapter dataAdapter = new SqlDataAdapter(CheckCommand);
dataAdapter.Fill(ds);
int i = ds.Tables[0].Rows.Count;
if (i > 0)
{
return $" We got a Duplicates in title : {Tit}";
}
try
{
{
string query = $"insert into TableBoto(Title,Summary,Link) values('{Tit}','{Sumy}','{Lin}');";
SqlCommand command = new SqlCommand(query, connection);
SqlDataReader reader = await command.ExecuteReaderAsync();
reader.Close();
}
}
catch (SqlException)
{
// Console.WriteLine(e.ToString());
}
connection.Close();
return $" Success Ign +{Tit} + Ign {Sumy}+ Ign {Lin} Ign Success SQL ";
}
}
500 HTTP status code is a generic code which means that the server was not able to process the request due to some issues, First step would be to add some exception handling to your function and see if the failure occurs and where it occurs.
On Side note, you should not use HTTP client in the way used in the code, you should not new it up every time your function executes, this client should be static in nature. Refer Manage connections in Azure Functions

Can't use retrieved data from one query into another one?

I need to use a variable (edifcodigo) which assigned value is retrieved from one query to insert it in a table by using other query but there is a error that says this variable is not available in actual context. I'm kind of new in aspnet, could anybody know how to figure this out?
This is the code I have:
//Connect to db
string connetionString = #"myconexionstring";
string sql = "SELECT TOP 1 id_proyecto AS codigo FROM DNN_SCO_PROY_CO_PROYECTO_TBL WHERE nombre_proyecto= '"+ uedif +"'";
//find building code by querying the database
try
{
using (SqlConnection conexion = new SqlConnection(connetionString))
{
conexion.Open();
using (SqlCommand query = new SqlCommand(sql, conexion))
{
SqlDataReader result = query.ExecuteReader();
while (result.Read())
{
string edifcodigo = result["codigo"].ToString();
}
}
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
//Save referer friend
try
{
using (SqlConnection conn = new SqlConnection(connetionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("DNN_SVI_SCO_DATOS_RECOMIENDA_AMIGO_SP", conn))
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.Add("#DRA_PROYECTO_CLIENTE", System.Data.SqlDbType.VarChar).Value = edifcodigo; ;
}
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
That's because you declared the variable inside a different code block. Every time you open a curly bracket, you open a new code block. Every time you close the curly bracket, you close the current code block. Each code block have it's own scope - it can access variables declared in the surrounding code block, but not variables declared in "sibling" code blocks.
Also, please read about parameterized queries and how they protect you from SQL injection, and change your queries accordingly.
Also, you don't need to close the connection between the two commands, and you can reuse a single command instance in this case. Here is an improved version of your code:
//Connect to db
var connetionString = #"myconexionstring";
var sql = "SELECT TOP 1 id_proyecto AS codigo FROM DNN_SCO_PROY_CO_PROYECTO_TBL WHERE nombre_proyecto = #nombre_proyecto";
//find building code by querying the database
try
{
using (var conexion = new SqlConnection(connetionString))
{
conexion.Open();
using (var cmd = new SqlCommand(sql, conexion))
{
cmd.Parameters.Add("#nombre_proyecto", SqlDbType.NVarChar).Value = uedif;
var edifcodigo = cmd.ExecuteScalar();
//Save referer friend
cmd.Parameters.Clear();
cmd.CommandText = "DNN_SVI_SCO_DATOS_RECOMIENDA_AMIGO_SP";
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.Add("#DRA_PROYECTO_CLIENTE", System.Data.SqlDbType.VarChar).Value = edifcodigo; ;
}
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
You are declaring the string variable inside your while loop, it loses scope once you exit the while loop, move it's declaration above with:
string connetionString = #"myconexionstring";
string sql = "SELECT TOP 1 id_proyecto AS codigo FROM DNN_SCO_PROY_CO_PROYECTO_TBL WHERE nombre_proyecto= '"+ uedif +"'";
string edifcodigo = "";
You are trying to use a variable that declared in another scope. edifcodigo should be declared in the parent scope of both try blocks.
//Connect to db
string connetionString = #"myconexionstring";
string sql = "SELECT TOP 1 id_proyecto AS codigo FROM DNN_SCO_PROY_CO_PROYECTO_TBL WHERE nombre_proyecto= '"+ uedif +"'";
string edifcodigo=""; // YOU SHOULD DECLARE edifcodigo HERE
and than rest of code will come
//find building code by querying the database
try
{
using (SqlConnection conexion = new SqlConnection(connetionString))
{
conexion.Open();
using (SqlCommand query = new SqlCommand(sql, conexion))
{
SqlDataReader result = query.ExecuteReader();
while (result.Read())
{
edifcodigo = result["codigo"].ToString();
}
}
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
//Save referrer friend
try
{
using (SqlConnection conn = new SqlConnection(connetionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("DNN_SVI_SCO_DATOS_RECOMIENDA_AMIGO_SP", conn))
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.Add("#DRA_PROYECTO_CLIENTE", System.Data.SqlDbType.VarChar).Value = edifcodigo; ;
}
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}

Monitor multiple tables related or non-related with sqldependency and signalr

I am trying to monitor multiple tables using signalR. These tables are related, but I need all columns from all tables for display purposes. I have seen SQldependcy on one table. How to implement it for multiple tables? Is this the right way to implement sqldependecy and signalr for multiple tables? In the database there are different tables with each having the ForiegnKey master--->submaster--->detail. Please suggest!
var masterpc = new List<master_Table>();
var submaster = new List<submaster_Table>();
var detail = new List<detail_Table>();
using (SqlConnection connection = new SqlConnection(regularConnectionString))
{
using (SqlCommand command = new SqlCommand(commandText, connection))
{
connection.Open();
//var dependency = new SqlDependency(command);
//dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
// NOTE: You have to execute the command, or the notification will never fire.
var reader = command.ExecuteReader();
while (reader.Read())
{
masterpc.Add(item: new master_Table
{
MasterKeyId = (int)reader["MasterKeyId"],
Master_Name = (string)reader["Master_Name"],
Master_IP = reader["Master_IP"] != DBNull.Value ? (string)reader["Master_IP"] : "",
Master_Valid = (bool)reader["Master_Valid"],
});
count++;
}
masterViewModel.masterpc_info = masterpc;
}
}
count = 0;
using (SqlConnection connection = new SqlConnection(regularConnectionString))
{
commandText = "select * from submaster where master_Valid=1 and masterKeyId in(select masterKeyId from masterpc_table where id=24) ";
using (SqlCommand command = new SqlCommand(commandText, connection))
{
connection.Open();
//var dependency = new SqlDependency(command);
//dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
// NOTE: You have to execute the command, or the notification will never fire.
var reader = command.ExecuteReader();
while (reader.Read())
{
submaster.Add(item: new submaster_table
{
SubmasterKeyId = (int)reader["SubmasterKeyId"],
submaster_Type = (string)reader["submaster_Type"],
submaster_SN = reader["submaster_SN"] != DBNull.Value ? (string)reader["submaster_SN"] : "",
masterPCKeyId = (int)reader["masterPCKeyId"],
});
count++;
}
masterconfigViewModel.submasterinfo = submaster;
}
}
using (SqlConnection connection = new SqlConnection(regularConnectionString))
{
commandText = "select * from detail where submasterKeyId in(select submasterkeyid from masterpc_table where id=24) ";
using (SqlCommand command = new SqlCommand(commandText, connection))
{
connection.Open();
var dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
// NOTE: You have to execute the command, or the notification will never fire.
var reader = command.ExecuteReader();
while (reader.Read())
{
detail.Add(item: new detail_table
{
detailkeyid = (int)reader["detailkeyid"],
detail_Type = (string)reader["detail_Type"],
detail_status = reader["detail_status"] != DBNull.Value ? (string)reader["detail_status"] : "",
submasterkeyid = (int)reader["submasterkeyid"],
});
count++;
}
masterconfigViewModel.detailinfo = detail;
}
}
This might be little late to answer, but you might think the following option suitable for you.
Project known as SqlDependencyEx
https://github.com/dyatchenko/ServiceBrokerListener
How to use for multiple tables
All you need to do is to create multiple listeners with different
identities as shown below:
var listener1 = new SqlDependencyEx(connectionString, "YourDatabase", "YourTable1", identity: 1);
var listener2 = new SqlDependencyEx(connectionString, "YourDatabase", "YourTable2", identity: 2);

Loading data from SQL Server into C# application

I have some problem accessing my data from a SQL Server database via C# application. I have a small project to make and I can't go further because my data is loading in. I try to load it in a DataGridView.
Here are some code examples:
public List<Country> GetCountryList()
{
string query = "SELECT * FROM Orszag", error = string.Empty;
SqlDataReader rdr = ExecuteReader(query, ref error);
List<Country> countryList = new List<Country>();
if (error == "OK")
{
while (rdr.Read())
{
Country item = new Country();
item.CountryId = Convert.ToInt32(rdr[0]);
item.CountryName = rdr[1].ToString();
countryList.Add(item);
}
}
CloseDataReader(rdr);
return countryList;
}
This is where I put my data in a list
private void FillDgvGames()
{
dgvGames.Rows.Clear();
List<Country> CountryList = m_Country.GetCountryList();
foreach (Country item in CountryList)
{
dgvGames.Rows.Add(item.CountryId,item.CountryName);
}
}
And this is where I retrieve it ... I have to make the same thing with 8 more tables but this is the simplest and I thought it's easier this way.... if someone can help me I'd appreciate it ...
PS:
This is the execute reader
protected SqlDataReader ExecuteReader(string query, ref string errorMessage)
{
try
{
OpenConnection();
SqlCommand cmd = new SqlCommand(query, m_Connection);
SqlDataReader rdr = cmd.ExecuteReader();
errorMessage = "OK";
return rdr;
}
catch (SqlException e)
{
errorMessage = e.Message;
CloseConnection();
return null;
}
}
And this is the connection string
protected string m_ConnectionString = "Data Source=SpD-PC;Initial Catalog=master;Integrated Security=SSPI";
Are you setting the data source of your DataGridView?
dgvGames.DataSource = CountryList;

how to enable SQL Application Role via Entity Framework

I'm now developing big government application with entity framework. at first i have one problem about enable SQL application role. with ado.net I'm using below code:
SqlCommand cmd = new SqlCommand("sys.sp_setapprole");
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = _sqlConn;
SqlParameter paramAppRoleName = new SqlParameter();
paramAppRoleName.Direction = ParameterDirection.Input;
paramAppRoleName.ParameterName = "#rolename";
paramAppRoleName.Value = "AppRole";
cmd.Parameters.Add(paramAppRoleName);
SqlParameter paramAppRolePwd = new SqlParameter();
paramAppRolePwd.Direction = ParameterDirection.Input;
paramAppRolePwd.ParameterName = "#password";
paramAppRolePwd.Value = "123456";
cmd.Parameters.Add(paramAppRolePwd);
SqlParameter paramCreateCookie = new SqlParameter();
paramCreateCookie.Direction = ParameterDirection.Input;
paramCreateCookie.ParameterName = "#fCreateCookie";
paramCreateCookie.DbType = DbType.Boolean;
paramCreateCookie.Value = 1;
cmd.Parameters.Add(paramCreateCookie);
SqlParameter paramEncrypt = new SqlParameter();
paramEncrypt.Direction = ParameterDirection.Input;
paramEncrypt.ParameterName = "#encrypt";
paramEncrypt.Value = "none";
cmd.Parameters.Add(paramEncrypt);
SqlParameter paramEnableCookie = new SqlParameter();
paramEnableCookie.ParameterName = "#cookie";
paramEnableCookie.DbType = DbType.Binary;
paramEnableCookie.Direction = ParameterDirection.Output;
paramEnableCookie.Size = 1000;
cmd.Parameters.Add(paramEnableCookie);
try
{
cmd.ExecuteNonQuery();
SqlParameter outVal = cmd.Parameters["#cookie"];
// Store the enabled cookie so that approle can be disabled with the cookie.
_appRoleEnableCookie = (byte[]) outVal.Value;
}
catch (Exception ex)
{
result = false;
msg = "Could not execute enable approle proc." + Environment.NewLine + ex.Message;
}
But no matter how much I searched I could not find a way to implement on EF.
Another question is: how to Add Application Role to Entity data model designer?
I'm using the below code for execute parameter with EF:
AEntities ar = new AEntities();
DbConnection con = ar.Connection;
con.Open();
msg = "";
bool result = true;
DbCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
var d = new DbParameter[]{
new SqlParameter{ ParameterName="#r", Value ="AppRole",Direction = ParameterDirection.Input}
, new SqlParameter{ ParameterName="#p", Value ="123456",Direction = ParameterDirection.Input}
};
string sql = "EXEC " + procName + " #rolename=#r,#password=#p";
var s = ar.ExecuteStoreCommand(sql, d);
When run ExecuteStoreCommand this line return error:
Application roles can only be activated at the ad hoc level.
I do it the following way (assuming Database First):
I create the DbContext from the db and call it MyEntitiesBase
I inherit from MyEntitiesBase to create MyEntities with the following code:
public partial class MyEntities : MyEntitiesBase
{
private byte[] appRoleCookie;
private void SetAppRole()
{
try
{
appRoleCookie = Database.SqlQuery<byte[]>(
#"
DECLARE #cookie VARBINARY(8000)
DECLARE #r INT
EXEC sp_setapprole 'user', 'pass', #fCreateCookie = true, #cookie = #cookie OUTPUT
SELECT #cookie").First();
}
catch
{
throw new AuthenticationException();
}
}
private void UnSetAppRole()
{
bool failed = Database.SqlQuery<bool>("DECLARE #result BIT; EXEC #result = sp_unsetapprole #cookie = " + appRoleCookie.ToHexadecimalString() + "; SELECT #result").First();
if (failed)
throw new SecurityException();
}
public MyEntities() : base()
{
Database.Connection.Open();
SetAppRole();
}
private bool disposed = false;
protected override void Dispose(bool disposing)
{
if (disposed)
return;
UnSetAppRole();
Database.Connection.Close();
disposed = true;
base.Dispose(disposing);
}
}
Where ToHexadecimalString is an extension method for IEnumerable<byte>, as follows:
public static class BytesExtensions
{
public static string ToHexadecimalString(this IEnumerable<byte> bytes)
{
return "0x" + string.Concat(bytes.Select(b => b.ToString("X2")));
}
}
And that's it. Works with connection pooling on and everything. You just use this inherited version instead of the one generated by EF.
Basically what you are doing is calling a stored procedure.
Entity Framework has functionality to excute stored procedures. Here is an explaination with a video: http://msdn.microsoft.com/en-us/data/gg699321.aspx
If your scrol down to the section "Using Import Functions to Map Stored Procedures" you will find the part that is relevant for you.