dataSet = clsDb.MailData("SELECT * FROM CM_Mail cm WHERE cm.[ActualTime] < '" + DateTimeOffset.UtcNow + "' ", CommandType.Text);
DataTable datatablepending = (from ds in dataSet.Tables[0].AsEnumerable() where ds.Field<string>("Status") == MailStatus.Pending.ToString() select ds).CopyToDataTable();
DataTable datatableInprogress = (from ds in dataSet.Tables[0].AsEnumerable() where ds.Field<string>("Status") == MailStatus.Inprogress.ToString() select ds).CopyToDataTable();
if (datatablepending.Rows.Count != 0)
{
for (int i = 0; i < datatablepending.Rows.Count; i++)
{
dataSet = clsDb.MailData("UPDATE CM_Mail SET [Status] = '" + updateStatus + "',LastProccessedTime = '" + DateTimeOffset.UtcNow.ToString() + "' WHERE Id='" + datatablepending.Rows[i]["Id"].ToString() + "'", CommandType.Text);
}
}
if (datatableInprogress.Rows.Count != 0)
{
for (int i = 0; i < datatableInprogress.Rows.Count; i++)
{
dataSet = clsDb.MailData("UPDATE CM_Mail SET [Status] = '" + updateStatus + "',SentTime = '" + DateTimeOffset.UtcNow + "',LastProccessedTime = '" + DateTimeOffset.UtcNow.ToString() + "' WHERE Id='" + datatableInprogress.Rows[i]["Id"].ToString() + "'", CommandType.Text);
}
}
When I try to do this datatableInprogress may not have any rows all the time. At run time, I get an exception saying "no datasource". Why? And what should I do to fix this issue?
Just clone DataTable structure if there is no rows for your condition:
var pendingRows =
dataSet.Tables[0].AsEnumerable()
.Where(r => r.Field<string>("Status") == MailStatus.Pending.ToString());
DataTable datatablepending = pendingRows.Any() ? pendingRows.CopyToDataTable() :
dataSet.Tables[0].Clone();
BTW why you need DataTable? You can get ids!
var pendingIds =
from r in dataSet.Tables[0].AsEnumerable()
where r.Field<string>("Status") == MailStatus.Pending.ToString()
select r.Field<int>("Id");
Sorry, I don't know why are you assigning dataSet in a loop, but here is code which reproduces yours:
string updateStringFormat =
"UPDATE CM_Mail SET [Status] = '{0}',LastProccessedTime = '{1}' WHERE Id='{2}'";
foreach(var id in pendingIds)
{
var commandText = String.Format(updateStringFormat, updateStatus, DateTimeOffset.UtcNow, id);
dataSet = clsDb.MailData(commandText, CommandType.Text);
}
Related
We used to write code in .Net Framework for DataTable filtering on server side.
This was the old code where HttpContext.Request was working fine. Now in .Net 6 how we can establish the same search and get HttpContext as well in any controller or model class from jquery.
This function is static and I am stuck in HttpContext.Request line where this is throwing exception "Httpcontext does not exist" even if we use IHttpContextAccessor here. How can we access that variable as that is defined in Program.cs.
public static DataTable FilterTable(DataTable dt, ref int Fcount, JQPM p)
{
p.sColumnslist = p.sColumns.Split(',');
string Fstring = ""; Int32 intVal = 0;
if (!string.IsNullOrEmpty(p.sSearch))
{
string[] Arr = p.sSearch.Trim().Split(' ');
for (int i = 0; i < Arr.Length; i++)
{
if (Arr[i] != "")
{
Fstring = "0=1 ";
for (int j = 0; j < p.sColumnslist.Length; j++)
{
if (Convert.ToBoolean(System.Web.HttpContext.Request["bSearchable_" + j]))
{
if (dt.Columns[p.sColumnslist[j]].DataType.Name == "String")
{
Fstring += " or " + p.sColumnslist[j] + " LIKE '%" + Arr[i] + "%'";
}
else if (dt.Columns[p.sColumnslist[j]].DataType.Name == "DateTime")
{
Fstring += " or " + p.sColumnslist[j] + "Format LIKE '%" + Arr[i] + "%'";
}
else
{
if (Int32.TryParse(Arr[i], out intVal))
{
Fstring += " or " + p.sColumnslist[j] + " = " + intVal;
}
}
}
}
//Fstring += " PartyName LIKE '%" + Arr[i] + "%'";
//if (Int32.TryParse(Arr[i], out intVal))
//{
// Fstring += " or SaleVoucherNo = " + intVal;
//}
//Fstring += " or SaleDateFormat LIKE '%" + Arr[i] + "%'";
//dt = GetDatatable(dt, Fstring, ref Fcount, p); Fstring = "";
dt = SearchDatatable(dt, Fstring, ref Fcount, p); Fstring = "";
}
}
}
//else
//{
//dt = GetDatatable(dt, Fstring, ref Fcount, p);
dt = GetDatatable(dt, ref Fcount, p);
//}
return dt;
}
System.Web.HttpContext has changed to Microsoft.AspNetCore.Http.HttpContext; you will need to pass the instance of this from where HttpContext is available into this function.
public static DataTable FilterTable(DataTable dt, ref int Fcount, JQPM p)
becomes
public static DataTable FilterTable(Microsoft.AspNetCore.Http.HttpContext httpContext, DataTable dt, ref int Fcount, JQPM p)
If you are retrieving "bSearchable_" + j from the QueryString and it will only contain that key once you can then use
httpContext.Request.Query["bSearchable_" + j].ToString();
where httpContext is the instance you pass in.
See:
https://learn.microsoft.com/en-us/aspnet/core/migration/http-modules?view=aspnetcore-6.0#migrating-to-the-new-httpcontext
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/http-context?view=aspnetcore-6.0
Good day,
I had a request to create a SSIS package that would output an SQL table to an Excel file. I had no problem creating this. However, the client came back asking that they wanted to be able to output the SQL table content to an existing Excel file in a new worksheet. If the worksheet does not exists in my following script, it is being created. However, it just goes back in the loop and fail because now it exists.
Here is my code:
public void Main()
{
string datetime = DateTime.Now.ToString("yyyyMMddHHmmss");
try
{
//Declare Variables
string ExcelFileName = Dts.Variables["$Package::ExcelFileName"].Value.ToString();
string FolderPath = Dts.Variables["$Package::FolderPath"].Value.ToString();
string TableName = Dts.Variables["$Package::SQLTableName"].Value.ToString();
string SchemaName = Dts.Variables["$Package::SQLTableSchema"].Value.ToString();
string SheetName = Dts.Variables["$Package::SheetName"].Value.ToString();
string lastChar = FolderPath.Substring(FolderPath.Length - 1);
string currentTab;
DataTable ExcelFileTabs;
//Validate format of FolderPath
if (lastChar != "\\")
{
FolderPath = FolderPath + "\\";
}
string FullExcelFilePath = FolderPath + ExcelFileName + ".xlsx";
OleDbConnection Excel_OLE_Con = new OleDbConnection();
OleDbCommand Excel_OLE_Cmd = new OleDbCommand();
//Construct ConnectionString for Excel
string connstring = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + FullExcelFilePath + ";" + "Extended Properties=\"Excel 12.0 Xml;HDR=YES;\"";
//USE ADO.NET Connection from SSIS Package to get data from table
SqlConnection myADONETConnection = new SqlConnection();
myADONETConnection = (SqlConnection)(Dts.Connections["ADO_DBConnection"].AcquireConnection(Dts.Transaction) as SqlConnection);
//Load Data into DataTable from SQL ServerTable
// Assumes that connection is a valid SqlConnection object.
string queryString = "SELECT * from " + SchemaName + "." + TableName;
SqlDataAdapter adapter = new SqlDataAdapter(queryString, myADONETConnection);
DataSet ds = new DataSet();
adapter.Fill(ds);
//Get Header Columns
string TableColumns = "";
// Get the Column List from Data Table so can create Excel Sheet with Header
foreach (DataTable table in ds.Tables)
{
foreach (DataColumn column in table.Columns)
{
TableColumns += column + "],[";
}
}
// Replace most right comma from Columnlist
TableColumns = ("[" + TableColumns.Replace(",", " Text,").TrimEnd(','));
TableColumns = TableColumns.Remove(TableColumns.Length - 2);
//Use OLE DB Connection and Create Excel Sheet
Excel_OLE_Con.ConnectionString = connstring;
Excel_OLE_Con.Open();
Excel_OLE_Cmd.Connection = Excel_OLE_Con;
// Verify if file exists
if (File.Exists(FullExcelFilePath))
{
//Verify if the sheet exists
foreach (DataTable table in ds.Tables)
{
ExcelFileTabs = Excel_OLE_Con.GetSchema("Tables");
foreach (DataRow excelTable in ExcelFileTabs.Rows)
{
currentTab = excelTable["TABLE_NAME"].ToString();
if (currentTab == SheetName)
{
// Create Log File for Errors
using (StreamWriter sw = File.CreateText(Dts.Variables["$Package::FolderPath"].Value.ToString() + "\\" + Dts.Variables["$Package::ExcelFileName"].Value.ToString() + "_" + datetime + ".log"))
{
sw.WriteLine("The sheet " + SheetName + " that your are trying to create in " + FullExcelFilePath + " already exists.");
sw.WriteLine("Please enter another sheet name or delete the Excel file and try again.");
}
Excel_OLE_Con.Close();
Dts.TaskResult = (int)ScriptResults.Failure;
}
else
{
// Create the worksheet in the existing Excel file
Excel_OLE_Cmd.CommandText = "Create table " + SheetName + " (" + TableColumns + ")";
Excel_OLE_Cmd.ExecuteNonQuery();
}
}
}
}
else
{
Excel_OLE_Cmd.CommandText = "Create table " + SheetName + " (" + TableColumns + ")";
Excel_OLE_Cmd.ExecuteNonQuery();
}
//Write Data to Excel Sheet from DataTable dynamically
foreach (DataTable table in ds.Tables)
{
ExcelFileTabs = Excel_OLE_Con.GetSchema("Tables");
foreach (DataRow excelTable in ExcelFileTabs.Rows)
{
String sqlCommandInsert = "";
String sqlCommandValue = "";
foreach (DataColumn dataColumn in table.Columns)
{
sqlCommandValue += dataColumn + "],[";
}
sqlCommandValue = "[" + sqlCommandValue.TrimEnd(',');
sqlCommandValue = sqlCommandValue.Remove(sqlCommandValue.Length - 2);
sqlCommandInsert = "INSERT into " + SheetName + "(" + sqlCommandValue.TrimEnd(',') + ") VALUES(";
int columnCount = table.Columns.Count;
foreach (DataRow row in table.Rows)
{
string columnvalues = "";
for (int i = 0; i < columnCount; i++)
{
int index = table.Rows.IndexOf(row);
columnvalues += "'" + table.Rows[index].ItemArray[i] + "',";
}
columnvalues = columnvalues.TrimEnd(',');
var command = sqlCommandInsert + columnvalues + ")";
Excel_OLE_Cmd.CommandText = command;
Excel_OLE_Cmd.ExecuteNonQuery();
}
Excel_OLE_Con.Close();
Dts.TaskResult = (int)ScriptResults.Success;
}
}
}
catch (Exception exception)
{
// Create Log File for Errors
using (StreamWriter sw = File.CreateText(Dts.Variables["$Package::FolderPath"].Value.ToString() + "\\" + Dts.Variables["$Package::ExcelFileName"].Value.ToString() + "_" + datetime + ".log"))
{
sw.WriteLine(exception.ToString());
Dts.TaskResult = (int)ScriptResults.Failure;
}
}
}
Can somebody please help me with this ? I am pretty new to C#, and English is not my primary language. Please let me know if this is not clear enough.
Thanks in advance for you time :-)
Mylene
You know when you are trying to find the solution way to fare when it is just in front of you ?
My code, before wanting to catch the error if the user was trying to add a worksheet that already exists, already was trowing an exception in those cases...
public void Main()
{
string datetime = DateTime.Now.ToString("yyyyMMddHHmmss");
try
{
//Declare Variables
string ExcelFileName = Dts.Variables["$Package::ExcelFileName"].Value.ToString();
string FolderPath = Dts.Variables["$Package::FolderPath"].Value.ToString();
string TableName = Dts.Variables["$Package::SQLTableName"].Value.ToString();
string SchemaName = Dts.Variables["$Package::SQLTableSchema"].Value.ToString();
string SheetName = Dts.Variables["$Package::SheetName"].Value.ToString();
ExcelFileName = ExcelFileName + "_" + datetime;
string lastChar = FolderPath.Substring(FolderPath.Length - 1);
//Validate format of FolderPath
if (lastChar != "\\")
{
FolderPath = FolderPath + "\\";
}
OleDbConnection Excel_OLE_Con = new OleDbConnection();
OleDbCommand Excel_OLE_Cmd = new OleDbCommand();
//Construct ConnectionString for Excel
string connstring = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + FolderPath + ExcelFileName
+ ";" + "Extended Properties=\"Excel 12.0 Xml;HDR=YES;\"";
//USE ADO.NET Connection from SSIS Package to get data from table
SqlConnection myADONETConnection = new SqlConnection();
myADONETConnection = (SqlConnection)(Dts.Connections["ADO_DBConnection"].AcquireConnection(Dts.Transaction) as SqlConnection);
//Load Data into DataTable from SQL ServerTable
// Assumes that connection is a valid SqlConnection object.
string queryString = "SELECT * from " + SchemaName + "." + TableName;
SqlDataAdapter adapter = new SqlDataAdapter(queryString, myADONETConnection);
DataSet ds = new DataSet();
adapter.Fill(ds);
//Get Header Columns
string TableColumns = "";
// Get the Column List from Data Table so can create Excel Sheet with Header
foreach (DataTable table in ds.Tables)
{
foreach (DataColumn column in table.Columns)
{
TableColumns += column + "],[";
}
}
// Replace most right comma from Columnlist
TableColumns = ("[" + TableColumns.Replace(",", " Text,").TrimEnd(','));
TableColumns = TableColumns.Remove(TableColumns.Length - 2);
//Use OLE DB Connection and Create Excel Sheet
Excel_OLE_Con.ConnectionString = connstring;
Excel_OLE_Con.Open();
Excel_OLE_Cmd.Connection = Excel_OLE_Con;
Excel_OLE_Cmd.CommandText = "Create table " + SheetName + " (" + TableColumns + ")";
Excel_OLE_Cmd.ExecuteNonQuery();
//Write Data to Excel Sheet from DataTable dynamically
foreach (DataTable table in ds.Tables)
{
String sqlCommandInsert = "";
String sqlCommandValue = "";
foreach (DataColumn dataColumn in table.Columns)
{
sqlCommandValue += dataColumn + "],[";
}
sqlCommandValue = "[" + sqlCommandValue.TrimEnd(',');
sqlCommandValue = sqlCommandValue.Remove(sqlCommandValue.Length - 2);
sqlCommandInsert = "INSERT into " + SheetName + "(" + sqlCommandValue.TrimEnd(',') + ") VALUES(";
int columnCount = table.Columns.Count;
foreach (DataRow row in table.Rows)
{
string columnvalues = "";
for (int i = 0; i < columnCount; i++)
{
int index = table.Rows.IndexOf(row);
columnvalues += "'" + table.Rows[index].ItemArray[i] + "',";
}
columnvalues = columnvalues.TrimEnd(',');
var command = sqlCommandInsert + columnvalues + ")";
Excel_OLE_Cmd.CommandText = command;
Excel_OLE_Cmd.ExecuteNonQuery();
}
}
Excel_OLE_Con.Close();
Dts.TaskResult = (int)ScriptResults.Success;
}
catch (Exception exception)
{
// Create Log File for Errors
using (StreamWriter sw = File.CreateText(Dts.Variables["$Package::FolderPath"].Value.ToString() + "\\" + Dts.Variables["$Package::ExcelFileName"].Value.ToString() + datetime + ".log"))
{
sw.WriteLine(exception.ToString());
Dts.TaskResult = (int)ScriptResults.Failure;
}
}
}
}
}
Error log :
System.Data.OleDb.OleDbException (0x80040E14): Table 'Test9' already exists.
at System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResult hr)
at System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object& executeResult)
at System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult)
at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method)
at System.Data.OleDb.OleDbCommand.ExecuteNonQuery()
at ST_a21007570143466693913591932c30b7.ScriptMain.Main()
Problem resolved.
Code:
for (int i = 1; i < butonsayisi; i++)
{
int buttonvalue = 1;
var buttonmenu = new Button
{
HeightRequest = 100,
WidthRequest = 100,
Margin = 5,
CornerRadius = 15,
BackgroundColor = Color.FromRgb(192,192,192),
};
buttonmenu.Clicked += butonmenu;
butonlar.Children.Add(buttonmenu);
if (baglanti.State.ToString() == "Open")
{
}
else
{
baglanti.Open();
}
SqlCommand getir = new SqlCommand("select * from butonlar where id = '" + i.ToString() + "'", baglanti);
SqlDataReader oku = getir.ExecuteReader();
while (oku.Read())
{
buttonmenu.Text = oku.GetValue(1).ToString();
baglanti.Close();
break;
}
async void butonmenu(object o, EventArgs args)
{
baglanti.Open();
SqlCommand getirici = new SqlCommand("select * from butonlar where id = '" + buttonvalue.ToString() + "'", baglanti);
SqlDataReader okuyucu = getirici.ExecuteReader();
while (okuyucu.Read())
{
butonadi = okuyucu.GetValue(2).ToString();
baglanti.Close();
break;
}
await DisplayAlert("Alert","Deneme " + butonadi,"OK");
buttonvalue++;
}
}
I have to reach the right buttonvalue.
butonsayisi counts how much row I have in database, this is how I create buttons and after that I edit the name of buttons with buttonmenu.Text = oku.GetValue(1).ToString(); in index 1 I have the the name of buttons.
So in index 2 I have another table name. When I press the button, I have to get the right table name. With this method I use, I am taking another button's index 2.
await DisplayAlert("Alert","Deneme " + butonadi,"OK"); is just for testing.
i did it guys!
simply i did;
SqlCommand getirici = new SqlCommand("select * from butonlar where butonadi = '" + buttonmenu.Text + "'", baglanti);
SqlDataReader okuyucu = getirici.ExecuteReader();
while (okuyucu.Read())
{
butonadi = okuyucu.GetValue(2).ToString();
baglanti.Close();
break;
}
i used to get the value from id now i get from name of button so it works!
I have a Customer Table and a Address Table (customer_id, address_forename, address_surname, address_street, address_city, address_zip,
address_storedtime) where customer_id as a foreign key.
One customer can have several address.
Now I am trying to get only the last entered address using LINQ as bellow which should allow me put the address in a string and return that:
CODE:
var customerAddress = (from c in myDB.address
where (c.customer_id == customerId)
select new
{
c.customer_id,
c.address_forename,
c.address_surname,
c.address_street,
c.address_city,
c.address_zip,
c.address_storedtime
}).GroupBy(g => new
{
Customer = .customer_id,
Address = g.address_forename + " " + g.address_surname + " " + g.address_street + " " + g.address_city + " " + g.address_zip
}).Select(g => new
{
g.Key.Customer,
g.Key.Address,
StoredTime = g.Max(x => x.address_storedtime)
}).Disinct();/*First();*/
string result = "";
foreach (var ad in customerAddress)
{
if (ad.Address != null)
{
result = ad.Address;
}
break;
}
return result;
I am getting same address string for different addresses in DB for the Customer whereas I am trying to get only one.
Since you're already filtering by customer id, the grouping clause isn't necessary. You should be able to just order the results for the customer descending and project the address much more simply.
var customerAddress = (from c in myDB.address
where (c.customer_id == customerId)
orderby c.address_storedtime descending
select c.address_forename + " " + c.address_surname + " " + c.address_street + " " + c.address_city + " " + c.address_zip)
.FirstOrDefault();
Replace your foreach by
var result =
customerAdress.Any(ad => ad.Address != null)
? customerAdress.Last(ad => ad.Address != null).Address
: default(string);
HI all i am Building A string Which looks like this
[Anil Kumar K,Niharika,Raghu,/4,0,0,/3,0,0,/1,1,1,/1,0,0,]
i am building this string with this data
public JsonResult ResourceBugReports()
{
int projectid;
int Releasphaseid;
projectid = 16;
Releasphaseid = 1;
var ResourceReports = db.ExecuteStoreQuery<ResourceModel>("ResourceBugReports #ProjectId,#ReleasePhaseId", new SqlParameter("#ProjectId", projectid), new SqlParameter("#ReleasePhaseId", Releasphaseid)).ToList();
DataSet ds = new DataSet();
var model1 = new WeeklyBugCount
{
Resources = ResourceReports
};
foreach (var row in model1.Resources)
{
ResourceName1 = ResourceName1 + row.EmployeeName + ",";
}
foreach (var row in model1.Resources)
{
BugsCount = BugsCount + row.Assignedbugs + ",";
}
foreach (var row in model1.Resources)
{
BugsCount1 = BugsCount1+ row.Closedbugs + ",";
}
foreach (var row in model1.Resources)
{
Bugscount2 = Bugscount2 + row.Fixedbugs + "," ;
}
foreach (var row in model1.Resources)
{
BugsCount3 = BugsCount3 + row.Reopenedbugs + ",";
}
ComboinedString = ResourceName1 + "/" + BugsCount + "/" + BugsCount1 + "/" + Bugscount2 + "/" + BugsCount3;
return Json(ComboinedString, JsonRequestBehavior.AllowGet);
}
my
ComboinedString =[Anil Kumar K,Niharika,Raghu,/4,0,0,/3,0,0,/1,1,1,/1,0,0,]
but i want this string
ComboinedString =[Anil Kumar K,Niharika,Raghu/4,0,0/3,0,0,/1,1,1/1,0,0]
i want to remove this "," before the "/" in this strin or replace it..can any one help me
Add this statement
I hope it will help you
String CombinedString1 = CombinedString.Replace(",/", "/");
A simple solution is a search and replace on the string replacing ",/" with "/".
A better solution is, rather than using a for() loop and appending a comma at the end of each value, is use String.Join(). For example, replace:
foreach (var row in model1.Resources)
{
ResourceName1 = ResourceName1 + row.EmployeeName + ",";
}
with
ResourceName1 = string.Join(",", model1.Resources.ToArray())
This will remove the trailing comma.
A simple solution would be to use String.EndsWith() function i.e.
string str = "ksjf,sjsfj,sfs,";
if (str.EndsWith(","))
{
str = str.Remove(str.Length - 1);
}
Off the top of my head, you could try to replace with a simple regular expression:
string input = "dsgd,sdgsdg,dsgsdg,sdg,";
string output = Regex.Replace(input, ",$", "");
//output: "dsgd,sdgsdg,dsgsdg,sdg"
#user1542652's solution is simple and works just as well.