I have a dropdownlist and it takes names of neighborhood from sql.
I want to show neighborhood's features on screen.
If I choose a neighborhood has been processed before now, It's no problem. My code can show features of its neighborhood.
But if I choose a new neighborhood (nobody adds information about that neighborhood before). There are no different thing on the screen.
I want to show on dropdownlist "New" as text. I defined 'else' status in my code.
How can I solve this problem?
That is my code :
string DurumTespiti = "";
string mahalle = ""; //mahalle means “neighborhood”
ddlMahalle.Visible = true; // it is a dropdownlist
SqlConnection baglanti = new SqlConnection("Data Source = WEBPMT\\ARCSQL;UID=sa;PWD=PMT*1881;DATABASE=ProjeTakip;");
SqlCommand komut = new SqlCommand();
baglanti.Open();
komut.Connection = baglanti;
komut.CommandText = "select * from ProjeTablo";
komut.ExecuteNonQuery();
SqlDataReader dr = komut.ExecuteReader();
while (dr.Read())
{
mahalle = "";
mahalle = dr["mahalle"].ToString();
if (mahalle == ddlMahalle.SelectedValue) // Compare value of dropdownlist and name of neighborhood in sql.
{
Label9.Text = "Mahalle doğru seçildi!";
}
mahalle = "";
}
else
{ // if value of dropdown list couldn’t be find in sql
Label9.Text = "Böyle bir mahalle yok";
}
mahalle = "";
}
dr.Close();
baglanti.Close();
Related
How do I run a raw query in ASP.NET core to return the row count from a table?
Currently, I am doing this and the returned result is -1. I think the return result is based on the number of records affected.
int numberOfRows = await
appDbContext.Database.ExecuteSqlInterpolatedAsync(
$"SELECT CODE FROM [samaster] WHERE CODE={productBrandCode} AND WAREHOUSE={warehouse} ");
Any idea on how to get the count back to numberOfRows variable will be appreciated.
NOTE: The above table is not a model so I need to run a raw query.
Thanks
It is currently not possible to get the query result when using ExecuteSqlInterpolatedAsync. The same applies to any additional LINQ Statements.
You can, however, use the underlying ADO.net Provider:
public IList<IDictionary<string, dynamic>> SelectDynamic(string table)
{
using (var command = Database.GetDbConnection().CreateCommand())
{
command.CommandText = $"SELECT * FROM [{table}]";
command.CommandType = CommandType.Text;
Database.OpenConnection();
using (var result = command.ExecuteReader())
{
var entities = new List<IDictionary<string, dynamic>>();
while (result.Read())
{
var dict = new Dictionary<string, dynamic>();
for (int i = 0; i < result.FieldCount; i++)
{
dict.Add(result.GetName(i), result.GetValue(i));
}
entities.Add(dict);
}
return entities;
}
}
}
Add this to your DbContext Class and Call it with:
using (var context = new MyDbContext()) // Or get it with DI, depends on your application
{
var count = context.SelectDynamic("samaster").Where(d => d["CODE"] == productBrandCode && d["WAREHOUSE"] == warehouse).Count();
}
Beware, however, that this is an expensive operation if you have a lot of rows in your table!
An alternative approach to only fetch the relevant results would be to replace
command.CommandText = $"SELECT * FROM [{table}]";
with
command.CommandText = $"SELECT CODE FROM [samaster] WHERE CODE={productBrandCode} AND WAREHOUSE={warehouse}";
and pass the parameters as function parameters.
public IList<IDictionary<string, dynamic>> SelectDynamic(string productBrandCode, string warehouse)
{...
Also make sure to escape all parameters if they are in any way submitted by user input to prevent SQL Injection Attacks!
There are two common approaches :
A.
int numberOfRows = await appDbContext.Database.ExecuteSqlInterpolatedAsync($"SELECT CODE FROM [samaster] WHERE CODE={productBrandCode} AND WAREHOUSE={warehouse} ").Count();
B.
int numberOfRows = await appDbContext.Database.ExecuteSqlInterpolatedAsync($"SELECT count(*) FROM [samaster] WHERE CODE={productBrandCode} AND WAREHOUSE={warehouse} ").First();
Since nobody gave me the correct answer. I end up using the following.
public async Task<bool> IsAValidProduct(string productBrandCode)
{
int count = 0;
await using DbCommand command = appDbContext.Database.GetDbConnection().CreateCommand();
command.CommandText =
"SELECT COUNT(CODE) FROM [samaster] WHERE CODE=#productBrandCode AND WAREHOUSE=#warehouse ";
command.CommandType = CommandType.Text;
command.Parameters.Add(new SqlParameter("#productBrandCode", SqlDbType.VarChar)
{Value = productBrandCode});
command.Parameters.Add(new SqlParameter("#warehouse", SqlDbType.VarChar)
{Value = warehouse});
await appDbContext.Database.OpenConnectionAsync();
count = (int) await command.ExecuteScalarAsync();
await appDbContext.Database.CloseConnectionAsync();
return count == 1;
}
int c= dbObj.Database.ExecuteSqlRaw(sql); //User this code
public SqlDataReader GetDataReader(List<SqlParameter> parameterValues){
System.Data.SqlClient.SqlConnection cn = new System.Data.SqlClient.SqlConnection();
cn.ConnectionString = SQLConnectionObj.ConnectionString;
cn.Open();
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
cmd.Parameters.AddRange(parameterValues.ToArray());
cmd.Connection = cn;
cmd.CommandText = SelectStatement;
cmd.CommandType = CommandType.Text;
return sReader = cmd.ExecuteReader();
}
When I try to add this for IN condition variable in select query,it fails.
Need to use this only for Fortify fix.Tried with dictionary Sql parameter.It works but increases the issue count up.
Please help me with this.And also if there is anything new which you want to add feel free to add those too.
But the following code works:-
public SqlDataReader GetDataReader(Dictionary<string, string> qParams)
{
SqlCommand SQLCommandObj = new SqlCommand(SelectStatement,
SQLConnectionObj);
string query=SelectStatement;
if (qParams.Count > 0)
{
foreach (string key in qParams.Keys)
{
string value = qParams[key];
SqlParameter par = new SqlParameter();
par.ParameterName = key;
par.Value = value;
SQLCommandObj.Parameters.Add(par);
}
}
foreach(SqlParameter par in SQLCommandObj.Parameters)
{
string key = par.ParameterName;
string value = par.Value as string;
query=query.Replace(key, value);
}
if (qParams.Count > 0)
{
SQLCommandObj.CommandText = "";
SQLCommandObj.CommandText = query;
}
SQLCommandObj.CommandTimeout = CustomCommandTimeout;
return SQLCommandObj.ExecuteReader(CommandBehavior.CloseConnection);
}
I have a C# .net application using the rally 3.0.1 API. When I query task in my system I get 0.0 for time spent when I know they have time against them. Anyone know how to get this? Below is my code:
if (uTasks.Count > 0)
{
Request taskRequest = new Request(resultChild["Tasks"]);
QueryResult TaskQueryResult = restApi.Query(taskRequest);
foreach (var items in TaskQueryResult.Results)
//foreach (var items in uTasks)
{
DataRow dtrow2;
dtrow2 = dt.NewRow();
dtrow2["TaskID"]=items["FormattedID"];
dtrow2["Task Name"] = items["Name"];
if (items["Owner"] != null)
{
var owner = items["Owner"];
String ownerref = owner["_ref"];
var ownerFetch = restApi.GetByReference(ownerref, "Name");
string strTemp = ownerFetch["_refObjectName"];
dtrow2["Owner"] = strTemp.Replace(",", " ");
}
\\else { dtrow2["Owner"] = ""; }
dtrow2["Task-Est"] = items["Estimate"];
dtrow2["Task-ToDo"] = items["ToDo"];
dtrow2["Task-Spent"] = items["TimeSpent"];
dtrow2["ObjectType"] = "T";
dt.Rows.Add(dtrow2);
}
}
It seems like that should work. You may want to make sure you're including the TimeSpent field in your fetch before issuing the request.
taskRequest.Fetch = new List<string>() { "TimeSpent" };
I used the code from http://arranmaclean.wordpress.com/2010/07/20/net-mvc-upload-a-csv-file-to-database-with-bulk-upload/#comment-188 to upload, read and insert to DB the csv file. My problem now is how can I pass the values from the csv file to the specific database table columns.
string Feedback = string.Empty;
string line = string.Empty;
string[] strArray;
DataTable dt = new DataTable();
DataRow row;
Regex r = new Regex(",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))");
StreamReader sr = new StreamReader(fileName);
line = sr.ReadLine();
strArray = r.Split(line);
Array.ForEach(strArray, s => dt.Columns.Add(new DataColumn()));
while ((line = sr.ReadLine()) != null)
{
row = dt.NewRow();
row.ItemArray = r.Split(line);
dt.Rows.Add(row);
}
and ...
private static String ProcessBulkCopy(DataTable dt)
{
string Feedback = string.Empty;
string connString = ConfigurationManager.ConnectionStrings["DataBaseConnectionString"].ConnectionString;
using( SqlConnection conn = new SqlConnection(connString))
{
using (var copy = new SqlBulkCopy(conn))
{
conn.Open();
copy.DestinationTableName = "BulkImportDetails";
copy.BatchSize = dt.Rows.Count;
try
{
copy.WriteToServer(dt);
Feedback = "Upload complete";
}
catch (Exception ex)
{
Feedback = ex.Message;
}
}
}
return Feedback;
}
Below are my sample contents:
08/01/12,05:20:12 AM,243752,,South Lobby3,522557,IN
08/01/12,05:26:03 AM,188816,,North Lobby1,358711,IN
My DB table columns:
empno | date | time
I only need to insert the first three arrays.. (e.g. 08/01/12,05:20:12 AM,243752) and proceed to the next row to insert it again to its specified columns. My csv file doesn't have headers. I saw a code about passing the array values but it requires headers. How can I pass the values even without having a header in my csv file? Please help me guys.. Thank you..
I'm writing C# code to merge multiple libraries within a site collection and applying grouping on them. But grouping doesn't include documents from other sites regardless all share same meta data. Below, Blue box docs are from one site and green box docs are from other site and they don't group together.
Here are my code ,
DataTable dt = new DataTable();
DataRow dr;
DataColumn dc;
SPSite curSite = SPContext.Current.Site;
SPWebCollection subSites = curSite.AllWebs;
dc = new DataColumn("Title", Type.GetType("System.String"));
dt.Columns.Add(dc);
dc = new DataColumn("ReferenceNo", Type.GetType("System.String"));
dt.Columns.Add(dc);
dc = new DataColumn("Domain", Type.GetType("System.String"));
dt.Columns.Add(dc);
dc = new DataColumn("Created", Type.GetType("System.DateTime"));
dt.Columns.Add(dc);
for (int i = 0; i < subSites.Count; i++)
{
SPListCollection lists = subSites[i].Lists;
foreach (SPList list in lists)
{
if (list.Title == "Published Documents")
{
SPQuery myquery = new SPQuery();
//myquery.Query = "<GroupBy><FieldRef Name='Domain' /></GroupBy><OrderBy><FieldRef Name='Created' Ascending='False' /></OrderBy>";
myquery.Query = "<GroupBy><FieldRef Name='Domain' /></GroupBy>";
SPListItemCollection items = list.GetItems(myquery);
foreach (SPListItem item in items)
{
if (item != null)
{
dr = dt.NewRow();
dr["Title"] = item["Title"];
dr["ReferenceNo"] = item["ReferenceNo"];
dr["Domain"] = item["Domain"];
dr["Created"] = item["Created"];
dt.Rows.Add(dr);
}
}
}
}
}
//dt.DefaultView.Sort = "Created DESC";
spGridView.AllowGrouping = true;
spGridView.AllowGroupCollapse = true;
spGridView.GroupField = "Domain";
spGridView.DataSource = dt;
spGridView.DataBind();
Updates:: , Sorting Data Table with Domain fixed the issue..
**dt.DefaultView.Sort = "Domain";**
Rishi's answer:
Sorting Data Table with Domain fixed the issue..
dt.DefaultView.Sort = "Domain";
naveed's comment:
Perfect it worked for me. all goes well just we need to have
dt.DefaultView.Sort = "Your Sorting Attribute";