How to change decimal separator in ExecuteReader c# - c#

How to change decimal separator in string, e.g. in mnoz_obj item the returned value is 24,000 and I need to have 24.000. The values are from database to JSON.
I tried ToString(new CultureInfo etc.) but this doesn't work. I expect that myString.Replace(",",".") is not correct way to do it.
public static string getDoklad()
{
var dbCon = ConfigurationManager.ConnectionStrings["myConn"].ConnectionString;
string[] fileArguments = Environment.GetCommandLineArgs();
List<ZebraPolozky> zebraPolozky = new List<ZebraPolozky>();
using (var cn = new OdbcConnection(dbCon))
{
OdbcCommand cmd = cn.CreateCommand();
cmd.CommandText = "SELECT * FROM cis06zebrap";
cn.Open();
using (var reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
ZebraPolozky zebraPolozka = new ZebraPolozky
{
doklad = reader["doklad"].ToString(),
sklad = reader["sklad"].ToString(),
reg = reader["reg"].ToString(),
mnoz_obj = reader["mnoz_obj"].ToString(),
mnoz_vyd = reader["mnoz_vyd"].ToString(),
kc_pce = reader["kc_pce"].ToString(),
sarze = reader["sarze"].ToString(),
datspo = reader["datspo"].ToString(),
veb = reader["veb"].ToString(),
poc2 = reader["poc2"].ToString(),
pvp06pk = reader["pvp06pk"].ToString(),
znacky = reader["znacky"].ToString(),
stav = reader["stav"].ToString(),
//prac = reader["prac"].ToString(),
//exp = reader["exp"].ToString()
};
zebraPolozky.Add(zebraPolozka);
}
}
}
cn.Close();
}
//var collw = new { polozky = zebraPolozky };
var jsonString = JsonConvert.SerializeObject(zebraPolozky);
return jsonString;
}
{
"doklad": "568375",
"sklad": "901",
"reg": "185121",
"mnoz_obj": "24,000",
"mnoz_vyd": "0,000",
"kc_pce": "240,72",
"sarze": "",
"datspo": "",
"veb": "24,00",
"poc2": "1",
"pvp06pk": "116783437",
"znacky": "R1902",
"stav": "0"
}

OdbcDataReader gives the value in its native format as stated in the doc.
You should then be able to cast it and use the overload of .ToString() you need.
Try something like:
((decimal)reader["mnoz_obj"]).ToString("N2")

Related

Overwriting of variable in SqlDataReader while-loop

I have read some threads that seem to be similar to this but can't find the fix for my issue, I've not used stack overflow much so pls bear with me
I have a while loop using an SqlDataReader which is pulling information from a DB and putting it into a List for Development Requests as below
public ListOfDevelopmentRequestsModel GetDevRequests(List<SelectListItem> evaluators)
{
SqlCommand cmd = new SqlCommand(StoredProcedures.DevRequests.GetDevRequests, Conn);
cmd.CommandType = CommandType.StoredProcedure;
ListOfDevelopmentRequestsModel ListOfDevRequests = new ListOfDevelopmentRequestsModel();
Conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
DateTime requestDate = Convert.ToDateTime(reader["DateCreated"].ToString());
string requestorFirstName = reader["Staff First Name"].ToString();
string requestorLastName = reader["Staff Last Name"].ToString();
string requestorEmailAddress = reader["Staff Email"].ToString();
string solutionName = reader["SolutionName"].ToString();
string solutionDescription = reader["SoultionDescription"].ToString();
string solutionElementName = reader["SolutionElementName"].ToString();
string solutionElementDescription = reader["SolutionElementDescription"].ToString();
string itemToChange = reader["ItemChange"].ToString();
string changeDetails = reader["ChangeDetail"].ToString();
List<SelectListItem> evaluatorList = new List<SelectListItem>(DisplayCurrentEvaluator(evaluators, evaluator));
DevelopmentRequestModel DevRequest = new DevelopmentRequestModel
{
RequestDate = requestDate,
RequestorName = $"{requestorFirstName} {requestorLastName}",
RequestorEmailAddress = requestorEmailAddress,
SolutionName = solutionName,
SolutionDescription = solutionDescription,
SolutionElementName = solutionElementName,
SolutionElementDescription = solutionElementDescription,
ItemToChange = itemToChange,
ChangeDetails = changeDetails,
AccordionHeading = $"{(changeID.PadLeft(4, '0'))} - {requestorFirstName} {requestorLastName} - {itemToChange}"
};
ListOfDevRequests.DevelopmentRequests.Add(DevRequest);
}
Conn.Close();
return ListOfDevRequests;
}
I also have a List for getting Evaluators of the requests
public static List<SelectListItem> GetEvaluators()
{
List<SelectListItem> evaluators = new List<SelectListItem>();
SqlCommand cmd = new SqlCommand(StoredProcedures.DevRequests.GetEvaluators, Conn);
cmd.CommandType = CommandType.StoredProcedure;
Conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
evaluators.Add(
new SelectListItem
{
Text = reader["Staff Name"].ToString(),
Value = reader["Staff Code"].ToString(),
});
}
Conn.Close();
return evaluators;
}
Finally I have a List that will pass the above Evaluators List in and the Evaluator that was pulled from the DB: string evaluator = reader["Evaluator"].ToString(); and will set the default value of the select list based on whether the Evaluator name matches the Text value, and set it as the selected select list item.
public List<SelectListItem> DisplayCurrentEvaluator(List<SelectListItem> evaluators, string evaluator)
{
foreach (var item in evaluators)
{
if (item.Text == evaluator)
{
item.Selected = true;
}
else
{
item.Selected = false;
}
}
return evaluators;
}
The issue is that the first item in the loop has the Evaluator "Bill" and "Bill" is selected, and works fine, however the second item in the loop is "John", and when it sets "John" to selected, it replaces "Bill" as the selected value in the first item with "John"
The code has ended up a mess as I have tried multiple different ways to fix but I'm stumped and would appreciate help.
Sorry if the post is formatted poorly to read, I can try to reformat and provide more information if requested.
Cheers
EDITED CODE:
GetDevRequests()
public ListOfDevelopmentRequestsModel GetDevRequests(List<SelectListItem> evaluators)
{
SqlCommand cmd = new SqlCommand(StoredProcedures.DevRequests.GetDevRequests, Conn);
cmd.CommandType = CommandType.StoredProcedure;
ListOfDevelopmentRequestsModel ListOfDevRequests = new ListOfDevelopmentRequestsModel();
Conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
List<SelectListItem> evaluatorList = new List<SelectListItem>();
while (reader.Read())
{
string changeID = reader["ChangeID"].ToString();
string evaluator = reader["Evaluator"].ToString();
string status = reader["Status"].ToString();
string priority = reader["Priority"].ToString();
string eliteID = reader["RequestorID"].ToString();
DateTime requestDate = Convert.ToDateTime(reader["DateCreated"].ToString());
string requestorFirstName = reader["Staff First Name"].ToString();
string requestorLastName = reader["Staff Last Name"].ToString();
string requestorEmailAddress = reader["Staff Email"].ToString();
string solutionName = reader["SolutionName"].ToString();
string solutionDescription = reader["SoultionDescription"].ToString();
string solutionElementName = reader["SolutionElementName"].ToString();
string solutionElementDescription = reader["SolutionElementDescription"].ToString();
string itemToChange = reader["ItemChange"].ToString();
string changeDetails = reader["ChangeDetail"].ToString();
evaluatorList = DisplayCurrentEvaluator(evaluators, evaluator);
DevelopmentRequestModel DevRequest = new DevelopmentRequestModel
{
ChangeID = (changeID.PadLeft(4, '0')),
Evaluator = evaluator,
Evaluators = evaluatorList,
Status = status,
Priority = priority,
EliteID = eliteID,
RequestDate = requestDate,
RequestorName = $"{requestorFirstName} {requestorLastName}",
RequestorEmailAddress = requestorEmailAddress,
SolutionName = solutionName,
SolutionDescription = solutionDescription,
SolutionElementName = solutionElementName,
SolutionElementDescription = solutionElementDescription,
ItemToChange = itemToChange,
ChangeDetails = changeDetails,
AccordionHeading = $"{(changeID.PadLeft(4, '0'))} - {requestorFirstName} {requestorLastName} - {itemToChange}"
};
ListOfDevRequests.DevelopmentRequests.Add(DevRequest);
}
Conn.Close();
return ListOfDevRequests;
}
DisplayCurrentEvaluator()
public List<SelectListItem> DisplayCurrentEvaluator(List<SelectListItem> selectListItems, string selectListDefaultItem)
{
foreach (var item in selectListItems)
{
item.Selected = item.Text == selectListDefaultItem;
}
return selectListItems;
}
The problem is in this line:
List<SelectListItem> evaluatorList = new List<SelectListItem>(DisplayCurrentEvaluator(evaluators, evaluator));
First, this can also be written as
List<SelectListItem> evaluatorList = DisplayCurrentEvaluator(evaluators, evaluator);
Your DisplayCurrentEvaluator already returns a correct list, so there is no need to copy it into a new one.
But this is a minor point as you don't use that evaluatorList as far as I can see. In every iteration of that while-loop you are creating a new one (which probably isn't what you want) and then you forget about it. I also don't see where evaluator is set, but that is probably in code you didn't show.
So you will need to generate this list once, outside the loop and keep it (probably in a class-level field or property).
And an extra tip, that DisplayCurrentEvaluator method can also be written as
public List<SelectListItem> DisplayCurrentEvaluator(List<SelectListItem> evaluators, string evaluator)
{
foreach (var item in evaluators)
{
item.Selected = item.Text == evaluator;
}
return evaluators;
}
EDIT after code was shown that set evaluator and used the resulting evaluatorList
Your DisplayCurrentEvaluator updates the original evaluators list and returns it. This effectively results in every evaluatorList pointing to the same list, where the last update wins. So make sure you return a new list.
public List<SelectListItem> DisplayCurrentEvaluator(List<SelectListItem> evaluators, string evaluator)
{
var result = new List<SelectListItem>(evaluators.Count);
foreach (var item in evaluators)
{
result.Add(new SelectListItem { Text = item.Text, Value = item.Value, Selected= item.Text == evaluator};
}
return result;
}
Additionally, declare the evaluatorList (only) inside of the loop.
var evaluatorList = DisplayCurrentEvaluator(evaluators, evaluator);

in C# assigning a array name to Json array

I have an Json array that looks like this:
[{"ticketAmount":5,"state":"Active"},{"ticketAmount":6,"state":"Closed"},{"ticketAmount":1,"state":"Resolve"}]
I want it to to get is an array that contains a assigned variable and then the Json, it should look like this(basically giving the array name):
"items":[{"ticketAmount":5,"state":"Active"},{"ticketAmount":6,"state":"Closed"},{"ticketAmount":1,"state":"Resolve"}]
My code:
public class EntityUserClosed
{
public int ticketAmount { get; set; }
public string loggedDate { get; set; }
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void GetUserClosedTickets()
{
var entites = new List<EntityUserClosed>();
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("Select LoggedBy, count(ID) as ticketAmount from Tickets WHERE LoggedDate >=dateadd(day,datediff(day,0,GetDate())- 30,0) AND State = '3' group by LoggedBy"))
{
var ticketAmount = 0;
var loggedBy = string.Empty;
cmd.Connection = con;
con.Open();
var reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
ticketAmount = (int)reader["ticketAmount"];
//Convert to JSON format
loggedBy = reader["LoggedBy"].ToString();
var entity = new EntityUserClosed
{
ticketAmount = ticketAmount,
loggedDate = loggedBy,
};
entites.Add(entity);
}
}
var json = serializer.Serialize(entites);
this.Context.Response.ContentType = "application/json; charset=utf-8";
var test = json.Replace("\\", "");
this.Context.Response.Write(test);
}
}
}
I have tried a few solutions such as:
var entity = new List<EntityUserClosed>()
but not sure how that would work.
Thanks
Simply change your serialization code as follows....
var json = serializer.Serialize(new {items=entites} );
BTW: items:[...] is not a valid json, it should be {items:[...]}

Get data from SQL datebase and return as string

Need help to get the 1st row record and return record as string in the << >> after while() loop.
There are a lot of columns in one row, I'm having a problem to declare it as string st? like usually string st = new string() please help to correct it
Thanks
public string Get_aodIdeal(string SubmittedBy)
{
String errMsg = "";
Guid? rguid = null;
int isOnContract = 0;
int isFreeMM = 0;
string _FileName;
DateTime InstallDateTime = DateTime.Now;
string FileDate = ToYYYYMMDD(DateTime.Now);
errMsg = "Unknown Error.";
SqlConnection conn = null; SqlCommand cmd = null;
string st = null;
conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["iDeal"].ConnectionString);
cmd = new SqlCommand();
string SQL = "select TOP 1 * from table1 Order by SubmittedOn desc";
SqlDataAdapter sqd = new SqlDataAdapter(SQL, conn);
cmd.CommandTimeout = 1200;
conn.Open();
SqlDataReader sqr;
//sqd.SelectCommand.Parameters.Add("#Submitted", SqlDbType.Int).Value = PostID;
sqr = sqd.SelectCommand.ExecuteReader();
while (sqr.Read())
st = new string{
rguid = cmd.Parameters["#rguid"].Value as Guid?,
ridno = int.Parse(sqr["ridno"].ToString()),
SubmittedOn= DateTime.Parse(sqr["SubmittedOn"].ToString()),
SubmittingHost = sqr["SubmittingHost"].ToString(),
ServiceAgreementNo = sqr["ServiceAgreementNo"].ToString(),
DocumentID = sqr["DocumentID"].ToString(),
Source = sqr["Source"].ToString(),
FileName = sqr["FileName"].ToString(),
FileType = sqr["FileType"].ToString(),
FileDate = DateTime.Parse(sqr["FileDate"].ToString()),
InstallTime = DateTime.Parse(sqr["InstallTime"].ToString()),
CalenderCode = cmd.Parameters["CalenderCode"].Value as Guid,
isFreeMM = bool.Parse(sqr["isFreeMM"].ToString()),
isOnContract = bool.Parse(sqr["isOnContract"].ToString()),
isProcessed = bool.Parse(sqr["isProcessed"].ToString()),
ProcessedByFullName = sqr["ProcessedByFullName"].ToString(),
isDelete = bool.Parse(sqr["isDelete"].ToString()),
version = int.Parse(sqr["Version"].ToString()),
LastUpdatedBy = DateTime.Parse(sqr["LastUpdatedBy"].ToString()),
LastUpdatedOn = DateTime.Parse(sqr["LastUpdatedOn"].ToString()),
shopGuid = sqr["shopGuid"].ToString(),
MacID = sqr["MacID"].ToString(),
MSISDN = sqr["MSISDN"].ToString()
}
You can use a StringBuilder for this purpose as like the following:
StringBuilder strBuilder= new StringBuilder();
while (sqr.Read())
{
strBuilder.AppendFormat("PostID : {0}{1}",sqr["PostID"].ToString(),Environment.NewLine);
strBuilder.AppendFormat("dateposted : {0}{1}",sqr["dateposted"].ToString(),Environment.NewLine);
// And so on Build your string
}
Finally the strBuilder.ToString() will give you the required string. But More smarter way is Create a Class with necessary properties and an Overrided .ToString method for display the output.
Let AodIdeal be a class with an overrided ToString() method. And Let me defined it like the following :
public class AodIdeal
{
public int PostID { get; set; }
public string dateposted { get; set; }
public string Source { get; set; }
// Rest of properties here
public override string ToString()
{
StringBuilder ObjectStringBuilder = new StringBuilder();
ObjectStringBuilder.AppendFormat("PostID : {0}{1}", PostID, Environment.NewLine);
ObjectStringBuilder.AppendFormat("dateposted : {0}{1}",dateposted, Environment.NewLine);
ObjectStringBuilder.AppendFormat("Source : {0}{1}", Source, Environment.NewLine);
// and so on
return ObjectStringBuilder.ToString();
}
}
Then you can create an object of the class(let it be objAodIdeal), and make use of its properties instead for the local variables. And finally objAodIdeal.ToString() will give you the required output.
Example usage
AodIdeal objAodIdeal= new AodIdeal();
while (sqr.Read())
{
objAodIdeal.PostID = int.Parse(sqr["PostID"].ToString());
objAodIdeal.dateposted= sqr["dateposted"].ToString();
// assign rest of properties
}
string requiredString= objAodIdeal.ToString();

Code to Insert Image into SQL Server

I want to insert an image into the SQL Server database from my Windows Forms application.
This question looks like it was trying to ask what I wanted to find out, but it was closed:
Insert image into SQL Server
Here is the code I used to do that.
Modify this code as needed for the table that you are going to use by viewing the design of your database in Microsoft Management Studio:
public static void InsertImage(int inventoryID, int businessID, FileInfo file, string sqlConnection)
{
var list = new List<byte>();
using (var stream = file.Open(FileMode.Open))
{
var data = new byte[stream.Length];
stream.Read(data, 0, data.Length);
list.AddRange(data);
}
var bmp = System.Drawing.Image.FromFile(file.FullName, true);
using (var conn = new SqlConnection(sqlConnection))
{
conn.Open();
var imageId = -1;
var sqlSelect = "SELECT [ImageId] FROM [dbo].[ImageTable] WHERE [InventoryId]=#InventoryId;";
using (var cmd = new SqlCommand(sqlSelect, conn))
{
cmd.Parameters.Add("#InventoryId", System.Data.SqlDbType.Int).Value = inventoryID;
using (var r = cmd.ExecuteReader())
{
if (r.Read())
{
var o = r["ImageId"];
if ((o != null) && (o != DBNull.Value))
{
imageId = (int)o;
}
}
}
}
if (imageId == -1)
{
var sqlCmd = "INSERT INTO [dbo].[ImageTable] " +
"([InventoryId], [ImageFileName], [ImageSize], [ImageWidth], [ImageHeight], [ImageBytes]) " +
"VALUES " +
"(#InventoryId, #ImageFileName, #ImageSize, #ImageWidth, #ImageHeight, #ImageBytes); ";
using (var cmd = new SqlCommand(sqlCmd, conn))
{
cmd.Parameters.Add("#InventoryId", System.Data.SqlDbType.Int).Value = inventoryID;
cmd.Parameters.Add("#ImageFileName", System.Data.SqlDbType.VarChar, 255).Value = file.Name;
cmd.Parameters.Add("#ImageSize", System.Data.SqlDbType.Int).Value = list.Count;
cmd.Parameters.Add("#ImageWidth", System.Data.SqlDbType.SmallInt).Value = bmp.Width;
cmd.Parameters.Add("#ImageHeight", System.Data.SqlDbType.SmallInt).Value = bmp.Height;
cmd.Parameters.Add("#ImageBytes", System.Data.SqlDbType.VarBinary, -1).Value = list.ToArray();
cmd.ExecuteNonQuery();
}
}
}
}
To run/test the code, I created this helper method:
public static string[] GetImages(string fullFolderPath, string searchPattern)
{
var list = new List<String>();
if (Directory.Exists(fullFolderPath))
{
if (String.IsNullOrEmpty(searchPattern))
{
searchPattern = "*.jpg";
}
var dir = new DirectoryInfo(fullFolderPath);
var files = dir.GetFiles(searchPattern);
for (int i = 0; i < files.Length; i++)
{
InsertImage(i + 1, 1, files[i], _sqlConnection);
list.Add(files[i].FullName);
}
}
return list.ToArray();
}
Now, running it from my Console Application is a simple, single call:
static void Main(string[] args)
{
var list = GetImages(#"C:\inetpub\wwwroot\Ads", "*.jpg");
}

How can get result from OleDbDataReader with C# method

How can return this from method ????
this is important for me
thank
this is my method :
public static dynamic GetFactorProperties(int factornumber)
{
using (var db = new OleDbConnection(cs))
{
db.Open();
var cmd = new OleDbCommand("SELECT * FROM FactorList WHERE FactorNumber = #0", db);
cmd.Parameters.AddWithValue("#0", factornumber);
var result = cmd.ExecuteReader();
if(result.Read())
{
return result ;
}
else
{
return ProperiesObject();
}
}
}
and this is my ExpandoObject()
public static dynamic ProperiesObject()
{
dynamic obj = new ExpandoObject();
obj.FactorDate = string.Empty;
obj.FactorNumber = string.Empty;
obj.CustomerName = string.Empty;
obj.FactorPrice = string.Empty;
obj.Discount = string.Empty;
return obj;
}
and this is read from method source :
var result = Program.GetFactorProperties(factornumber);
TXTDate.Text = result.FactorDate;
TXTFactorNumber.Text = result.FactorNumber;
TXTCustomerName.Text = result.CustomerName;
TXTFactorParice.Text = result.FactorPrice;
TXTDiscount.Text = result.Discount;
Method should look like this:
public static dynamic GetFactorProperties(int factornumber)
{
using (var db = new OleDbConnection(cs))
{
db.Open();
var cmd = new OleDbCommand("SELECT * FROM FactorList WHERE FactorNumber = #0", db);
cmd.Parameters.AddWithValue("#0", factornumber);
var result = cmd.ExecuteReader();
if(result.Read())
{
dynamic obj = new ExpandoObject();
obj.FactorDate = result.GetString(0);
obj.FactorNumber = result.GetString(1);
// ...
return obj;
}
else
{
return ProperiesObject();
}
}
}
GetString accepts number of column, from which you want to get value

Categories