Cannot assign to GetDropDownValues because it is a method group? - c#

I have a question regarding the code below, am trying to get the dropdown values from a generic query, passing the field and table name. I am getting the error Cannot assign to GetDropDownValues because it is a method group and not sure how to resolve? Can anyone shed some light? Thanks in advance...
public static DataTable GetDropDownValues(string pstrConString_Mfg, string pstrTableName, string pstrFieldName, string pstrField = "")
{
string strSQL;
DataTable dtRetTable;
try
{
strSQL = "SELECT DISTINCT " + pstrFieldName;
if (pstrField != "")
{
strSQL = strSQL + " , " + pstrField;
}
strSQL = strSQL + " FROM " + pstrTableName + " ORDER BY " + pstrFieldName;
dtRetTable = ExecuteDataTable(pstrConString_Mfg, CommandType.Text, strSQL);
if (dtRetTable != null)
{
if ((dtRetTable.Rows.Count == 0))
{
GetDropDownValues = new DataTable(); <--error
}
else
{
dtRetTable.BeginLoadData();
dtRetTable.Rows.InsertAt(dtRetTable.NewRow, 0);
dtRetTable.EndLoadData();
dtRetTable.AcceptChanges();
GetDropDownValues = dtRetTable;
}
}
else
{
GetDropDownValues = new DataTable();
}
}
catch (Exception ex)
{
throw ex;
}
}
--==================================================
Also am getting error on line ' dtRetTable.Rows.InsertAt(dtRetTable.NewRow, 0);'
cannot convert from 'method group' to 'DataRow'. I am assuming it is related to above error?

Where you wrote GetDropDownValues = dtRetTable; and GetDropDownValues = new DataTable(); looks like older Visual Basic (also Visual Basic for Applications, VBA) syntax for having a function return a value.
With C# (and C, C++, Java, JavaScript and a lot of others) you need to return a value and not assign it to the function name.
Do this instead:
return dtRetTable;
and
new DataTable();
Edit to address your other question...
For the error on the line dtRetTable.Rows.InsertAt(dtRetTable.NewRow, 0) doing as #Ed Plunkett suggested will fix this problem. As you said you are converting older code to work in C#, it will be easy to forget to add the trailing brackets () as required by C# but the error message you get of method group - Well, I've only ever seen it when I forget to put the brackets in, so it will be easier for you to understand what is going on.
And finally, do not catch Exceptions unless you intend to do something about the exception there and then. You should always catch the Exception in your Interface methods so you can show a nicer message to your users and prevent the app from crashing out.
Where you wrote throw ex;, it would be better to just write throw or if you are willing, remove the try/catch block entirely. When you throw ex you will destroy the correct StackTrace which is essential for debugging and figuring out what the problem is. There is lots of information (and a lot more in-depth) on this in StackOverflow as well as the rest of the Web.
Happy translating, and remember we love to help those who make an attempt to help themselves first.

Related

SQLite showing "Insufficient Parameters supplied to the command" despite having enough parameters

I have the following SQLite table.
CREATE TABLE "Ingredient_Detailed" (
"DETAILED_INGREDIENT_ID" TEXT,
"INGREDIENT_CODE" INTEGER NOT NULL,
"BRAND" TEXT NOT NULL,
"INGREDIENT_SOURCE" TEXT NOT NULL,
"UNIT_PRICE" REAL NOT NULL DEFAULT 0,
"AMOUNT_IN_UNIT" REAL NOT NULL DEFAULT 0,
"MINIMUM_PRICE_PER_UNIT" REAL NOT NULL DEFAULT 0,
"QUALITY" INTEGER NOT NULL DEFAULT 1,
"UNITS_AVAILABLE" INTEGER NOT NULL DEFAULT 0,
FOREIGN KEY("INGREDIENT_CODE") REFERENCES "Ingredient"("CODE"),
PRIMARY KEY("DETAILED_INGREDIENT_ID")
)
I have a C# application where I am trying to insert records into this table with the following method:
public int SaveDetailedIngredient(DetailedIngredient pDetailedIngredient)
{
try
{
using (var conn = new SQLiteConnection(GetConnectionString()))
{
var saveDetailedIngredientCommand = new SQLiteCommand("INSERT INTO INGREDIENT_DETAILED (DETAILED_INGREDIENT_ID, " +
"INGREDIENT_CODE, BRAND, INGREDIENT_SOURCE, UNIT_PRICE, AMOUNT_IN_UNIT, " +
"MINIMUM_PRICE_PER_UNIT, QUALITY, UNITS_AVAILABLE) " +
"VALUES ($pDetailedIngredientId, $pCode, $pBrand, $pSource, $pUnitPrice, $pAmountInUnit, $pPricePerUnit, $pQuality, $pUnitsAvailable)", conn);
pDetailedIngredient.DetailedIngredientCode = pDetailedIngredient.Code + "-" + pDetailedIngredient.Brand + "-" + pDetailedIngredient.IngredientSource;
saveDetailedIngredientCommand.Parameters.AddWithValue("pDetailedIngredientId", pDetailedIngredient.DetailedIngredientCode);
saveDetailedIngredientCommand.Parameters.AddWithValue("pCode", pDetailedIngredient.Code);
saveDetailedIngredientCommand.Parameters.AddWithValue("pBrand", pDetailedIngredient.Brand.Trim().ToUpper());
saveDetailedIngredientCommand.Parameters.AddWithValue("pSource", pDetailedIngredient.IngredientSource.Trim().ToUpper());
saveDetailedIngredientCommand.Parameters.AddWithValue("pUnitPrice,", pDetailedIngredient.UnitPrice);
saveDetailedIngredientCommand.Parameters.AddWithValue("pAmountInUnit", pDetailedIngredient.AmountInUnit);
saveDetailedIngredientCommand.Parameters.AddWithValue("pPricePerUnit", pDetailedIngredient.MinimumUnitPrice);
saveDetailedIngredientCommand.Parameters.AddWithValue("pQuality", pDetailedIngredient.Quality);
saveDetailedIngredientCommand.Parameters.AddWithValue("pUnitsAvailable", pDetailedIngredient.UnitsAvailable);
conn.Open();
return saveDetailedIngredientCommand.ExecuteNonQuery();
}
}
catch (SQLiteException sqlEx)
{
Console.WriteLine(sqlEx.Message);
Console.WriteLine(sqlEx.ErrorCode);
throw sqlEx;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw ex;
}
}
Despite indicating 9 fields and supplying 9 parameters, SQLite throws an exception saying "Unknown Error: Insufficient Parameters Supplied to Command".
I copy and pasted the name of the parameters to make sure there's no typo in them, yet it still throws the error.
I debugged the application during the method executing and the supplied pDetailedIngredient has all the necessary attribute values assigned, and I can see that each of the parameters in the command is being assigned correctly.
I have several other methods for inserting data into other tables, all follow the same structure, so I doubt that this is related to the way my method is written.
Am I missing something here? It doesn't feel like this is the right error.
I honestly wish I had a good answer as to “WHY” this is happening. I can only assume that the “AddWithValue” is doing something I am not aware of. However, after a some back and forth I would ask you to try this and see if it works for you as it did for me.
Is what I changed is by adding the parameters as shown below. This consistently worked with some testing and only failed as expected when the id was duplicated. Please let me know if this helps as I am with you in a sense that on the surface, your code looks good to me.
saveDetailedIngredientCommand.Parameters.Add("pDetailedIngredientId", DbType.String).Value = pDetailedIngredient.DetailedIngredientCode;
saveDetailedIngredientCommand.Parameters.Add("pCode", DbType.Int32).Value = pDetailedIngredient.Code;
saveDetailedIngredientCommand.Parameters.Add("pBrand", DbType.String).Value = pDetailedIngredient.Brand.Trim().ToUpper();
saveDetailedIngredientCommand.Parameters.Add("pSource", DbType.String).Value = pDetailedIngredient.IngredientSource.Trim().ToUpper();
saveDetailedIngredientCommand.Parameters.Add("pUnitPrice", DbType.Decimal).Value = pDetailedIngredient.UnitPrice;
saveDetailedIngredientCommand.Parameters.Add("pAmountInUnit", DbType.Decimal).Value = pDetailedIngredient.AmountInUnit;
saveDetailedIngredientCommand.Parameters.Add("pPricePerUnit", DbType.Decimal).Value = pDetailedIngredient.MinimumUnitPrice;
saveDetailedIngredientCommand.Parameters.Add("pQuality", DbType.Int32).Value = pDetailedIngredient.Quality;
saveDetailedIngredientCommand.Parameters.Add("pUnitsAvailable", DbType.Int32).Value = pDetailedIngredient.UnitsAvailable;
Let me know if this does not work for you and I will remove it.
Another potential cause of "Insufficient Parameters Supplied to Command" error
If you use an approach similar to the following for entering data into a SQLite DB programmatically:
create a class w/needed properties
instantiate class and populate the instance
save instance to DB
the class property name and DB column name must match (excluding case-sensitivity).
Example (I use NuGet Dapper so exact syntax may differ):
public class StartState
{
public string Phase { get; set; }
public string ArgText { get; set; }
public string startTime { get; set; }
}
// in winforms form.cs
private static void SaveStartState()
{
StartState model = new StartState();
{
model.Phase = Terms.Status;
model.ArgText = _tsarg;
model.startTime = starttTime4DB;
DBconnects.SaveState(model);
}
}
// in DBconnects.cs
public static void SaveState(StartState model)
{
using (var dbc = new SQLiteConnection(Connections.SQLiteDB()))
{
dbc.Execute($"insert into {DBtbl.State}(" +
"phase,argText,startTime)" +
" values(" +
"#phase,#argText,#startTime)"
, model);
}
}
// DB Definition
CREATE TABLE 'StartState' (
phase TEXT NOT NULL PRIMARY KEY,
argText TEXT,
startTime TEXT
);

Read Text File, Update Fields C# and WPF

I am trying to basically create config files. A text file will hold something like:
Name::Adam
Location::Washington
I am trying to grab the first part as the field name (i.e. Name.Text would update the TextBox) then put the second part to that Text. Just not sure where to go or what the best way to build this is. The code below is incomplete because I can't figure out how to update the textboxes.
Thanks for the help!
private void clickImportConfig_ItemClick(object sender, DevExpress.Xpf.Bars.ItemClickEventArgs e)
{
Stream myStream = null;
string fieldUpdate = string.Empty;
string fieldUpdateTo = string.Empty;
try
{
using (myStream)
{
string[] lines = File.ReadAllLines(#"c:\\config.txt");
foreach (string s in lines)
{
var splitted = Regex.Split(s, "::");
fieldUpdate = splitted[0].ToString();
fieldUpdateTo = splitted[1].ToString();
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
I think this is what you're looking for:
private void clickImportConfig_ItemClick(object sender, DevExpress.Xpf.Bars.ItemClickEventArgs e)
{
Stream myStream = null;
string fieldUpdate = string.Empty;
string fieldUpdateTo = string.Empty;
try
{
using (myStream)
{
string[] lines = File.ReadAllLines(#"c:\\config.txt");
foreach (string s in lines)
{
string[] splitted = s.Split(new string[] { "::" }, StringSplitOptions.RemoveEmptyEntries);
fieldUpdate = splitted[0].ToString();
fieldUpdateTo = splitted[1].ToString();
// TextBox textBox = (TextBox)this.FindName(fieldUpdate);
// Or
TextBox textBox = this.FindName(fieldUpdate) as TextBox;
// See below for an explanation
if (textBox != null) // FindName returns null if nothing is found with that name
{
textBox.Text = fieldUpdateTo;
}
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
As insane_developer pointed out, you will be better off using the String.Split method (s being the string in this case so written as s.Split()) instead of Regex.Split. It will give you the benefit of removing any empty results from the array. It may also have better performance as Regex is capable of a lot more complicated things, but I haven't tested that so I could be wrong.
You can use the FindName(string name) method to find an element with the specified name. This method returns null if nothing is found and an object if the element is found. This object will need to be cast to the type you are expecting (I.e. TextBox). You can do this in one of the following ways:
TextBox textBox = (TextBox)this.FindName(fieldUpdate);
or
TextBox textBox = this.FindName(fieldUpdate) as TextBox;
The first option will throw an InvalidCastException if FindName returns an object which is not a TextBox. The second option will instead just set the value of textBox to null which will be checked by the if statement and the exception will be avoided. As you are only catching all generic exceptions in this code, an InvalidCastException would show your "Could not read file from disk" message which is not true. So you may want to add an additional catch block to handle any invalid casting.
If you're wondering why you don't just stick to the second option as it solves this problem, then consider this scenario as an example. Lets say in the future you decide for some reason that you want to change all of your TextBox to TextBlock or something else, but forget to come back to change this code, or accidently end up with the name of another type of control in your text file. The second option will set the value of textBox to null and your field(s) won't be updated. But there will be absolutely no errors, leaving you scratching your head and having to debug the problem. The first option would throw an InvalidCastException showing you exactly where the problem is. You could then choose how to handle this problem by either showing another message box or silently writing the error to a log file etc.
You don't need a regular expression, just:
var splitted = s.Split("::", StringSplitOptions.RemoveEmptyEntries);
fieldUpdate = splitted[0];
fieldUpdateTo = splitted[1];
For the rest you have to be more explicit

handle error on Microsoft.AnalysisServices update method

I am updating dimension definition in 'Data Source View'. Doing it using C# code inside SSIS script task.
Here is simplified C# code:
DataSourceView ASDataSourceView;
//DataSourceView inherits from MajorObject
ASDataSourceView.Schema.Tables["DimTable"].ExtendedProperties["QueryDefinition"] = "SELECT * FROM ufc.TableWithData";
ASDataSourceView.Update();
I need to handle error which may appear during Update() method.
I thought that usual approach with try catch will work but it seems it is not a case.
I need to get an xml response object somehow and then check if it is empty(no error) or parse it and build further logic.
I was trying to read Microsoft documentation but have no idea how to do it.
XmlaWarningCollection Class
When I run update xml statement in SSMS I get the following messages:
when update succeed:
<return xmlns="urn:schemas-microsoft-com:xml-analysis">
<root xmlns="urn:schemas-microsoft-com:xml-analysis:empty" />
</return>
when update fails(fails because of syntax error not logic which is also not very correct from simulation point of view):
XML parsing failed at line 9597, column 63: The name in the end tag of the element must match the element type in the start tag.
Run complete
Can anybody help?
I think I finally found solution:
First you need to enable CaptureXML option;
ServerName.CaptureXml = true;
Second run Update with XmlaResultCollection option:
UpdateOptions uo = default(UpdateOptions);
UpdateMode om = default(UpdateMode);
XmlaWarningCollection xm = null;
ASDataSourceView.Update(uo, om, xm);
Third you execute update statement:
XmlaResultCollection resultCollection = ServerName.ExecuteCaptureLog(false, false);
After that I was able to parse resultCollection object:
String ErrorMessages = String.Empty;
if (resultCollection.ContainsErrors) {
ErrorMessages += $"Errors occured in cube {ConnectionString.CatalogName}:" + Environment.NewLine;
foreach (AS.XmlaResult result in resultCol) {
foreach (object error in result.Messages) {
if (error.GetType() == typeof(AS.XmlaError))
ErrorMessages += "ERR: " + ((AS.XmlaError)error).Description + Environment.NewLine;
else if (error.GetType() == typeof(AS.XmlaWarning))
ErrorMessages += "WARN: " + ((AS.XmlaWarning)error).Description + Environment.NewLine;
}
}
throw new Exception(ErrorMessages);
}

REST API Consecutive Call is not working

SOLVED
The problem was sending the number with double quotes like "40".
So I replaced quotes with empty space and It worked.
This is the code.
HRMID = HRMID.Replace('"', ' ').Trim();
I am trying to call my REST service consecutively but only one of them is working when I do that.
If I call only one of them in one block it works but two of them in one function block is causing problems I think,I don't know why.
Maybe it is something about restriction in the service.
There is no Error just it is not updating the Database.
If I use it alone it works so call is correct.
This is my code , I am waiting for suggestions.
Thanks!
private void GameClosed(object sender, EventArgs e)
{
// Do your stuff when the game closed.
try
{
var client = new WebClient();
var result = client.DownloadString(wsUrl + "/rest/gethrmid/" + UserValues[4]);// Only the first REST API call is working.This one works.
MessageBox.Show("Result is :" + result);
string HRMID = result;
StreamReader SR = new StreamReader("D:/HRMSession.txt");
string hrmValues = SR.ReadToEnd();
client.DownloadString(wsUrl + "/rest/inserthrmsession/" + HRMID + "/" + hrmValues);//This one is not working if i put here.
}
catch (Exception a)
{
MessageBox.Show(a.ToString());
}
}
EDIT:
If I write it as hardcoded it works but if I use the value that is coming from first call it doesn't work.
client.DownloadString(wsUrl + "/rest/inserthrmsession/" + 40 + "/" + hrmValues);//Works.
But I can not convert the value of HRMID to Int because operation contract is string...

Debugging: Microsoft JScript runtime error

I am desperately in need of debugging help, been stuck at this error for 6 days now.....
the error I get in my ASp.net app is :
Microsoft JScript runtime error: Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed. Common causes for this error are when the response is modified by calls to Response.Write(), response filters, HttpModules, or server trace is enabled.
Details: Error parsing near '<script type='text/j'.
Below is the relevant code snippet,
CollyDataExchangeWebService Col_ValSub = new CollyDataExchangeWebService();
CollyReportServiceRequest ServiceReq = new CollyReportServiceRequest();
CollyReportServiceRequestData ServiceReqData = new CollyReportServiceRequestData();
ServiceReqData.AmendmentIndicatorSpecified = true;
ServiceReqData.AmendmentIndicator = false;
ServiceReqData.CollyReport = ColRep;
ServiceReq.ServiceRequestData = ServiceReqData;
ServiceReq.ServiceRequestHeader = ServiceHeader;
errValidate = null;
//btnOK.OnClientClick = "MSGShow()";
bool Valid = true;
string ErrMsgs = "";
if (((System.Web.UI.WebControls.Button)(sender)).CommandArgument == "Validate")
{
CollyReportServiceResponse ValResponse = Col_ValSub.validateReport(ServiceReq);
switch (ValResponse.ServiceResponseHeader.ServiceStatus)
{
case ServiceStatus.Successful:
btnOK.OnClientClick = "";
valHeader.Text = "Validation is Completed. No errors were found";
mlValPopup.Show();
break;
case ServiceStatus.ValidationErrors:
Valid = false;
ErrMsgs = ErrMsgs + _ValidationError(ValResponse);
ValBTN.Update();
mlValPopup.Show();
break;
case ServiceStatus.SystemError:
btnOK.OnClientClick = "";
Valid = false;
ErrMsgs = ErrMsgs + _SystemError(ValResponse);
ValBTN.Update();
mlValPopup.Show();
break;
}
After hours of debugging I found this line to be causing the error:
CollyReportServiceResponse ValResponse = Col_ValSub.validateReport(ServiceReq);
After 6 days of debugging and frustration I found that SOME records cause this issue and others dont in OLDER versions of the code but in new version ALL of the records lead to this error so it has to do something with the data in the DB which means SOME method in the code behaves differently to nulls but I cant find out exactly what the issue is because my app is 30k lines of code
after searching around and trying various solutions, the below 2 are not the solutions to my issue.
forums.asp.net/t/1357862.aspx
http://www.vbforums.com/showthread.php?t=656246
I want to mention that I am already having a difficult time dealing with this application because it was written by other programmers that are now long gone leaving behind non-documented or commented spaghetti code.
I did not code this but other programmers from past have put Response.Write in code:
private void MessageBox(string msg)
{
if (!string.IsNullOrEmpty(msg))
{
Global.tmpmsg = msg;
msg = null;
}
Response.Write("<script type=\"text/javascript\" language=\"javascript\">");
Response.Write("window.open('ErrorPage.aspx?msg=" + "','PopUp','screenX=0,screenY=0,width=700,height=340,resizable=1,status=no,scrollbars=yes,toolbars=no');");
Response.Write("</script>");
}
This one is in another method:
Response.Write("<script type=\"text/javascript\" language=\"javascript\">");
Response.Write("alert('No search resuls were found');");
Response.Write("</script>");
Or This:
if (!string.IsNullOrEmpty(msg))
{
Global.tmpmsg = msg;
Response.Write("<script type=\"text/javascript\" language=\"javascript\">");
Response.Write("window.open('ErrorPage.aspx?msg=" + "','PopUp','screenX=0,screenY=0,width=700,height=340,resizable=1,status=no,scrollbars=yes,toolbars=no');");
Response.Write("</script>");
}
After Jrummel`s comment I added this to code and then nothing at all happened.
private void MessageBox(string msg)
{/*
if (!string.IsNullOrEmpty(msg))
{
Global.tmpmsg = msg;
msg = null;
}
Response.Write("<script type=\"text/javascript\" language=\"javascript\">");
Response.Write("window.open('ErrorPage.aspx?msg=" + "','PopUp','screenX=0,screenY=0,width=700,height=340,resizable=1,status=no,scrollbars=yes,toolbars=no');");
Response.Write("</script>");
*/
// Define the name and type of the client scripts on the page.
String csname1 = "PopupScript";
Type cstype = this.GetType();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
// Check to see if the startup script is already registered.
if (!cs.IsStartupScriptRegistered(cstype, csname1))
{
String cstext1 = "<script type=\"text/javascript\" language=\"javascript\">" + " " + "window.open('ErrorPage.aspx?msg=" + "','PopUp','screenX=0,screenY=0,width=700,height=340,resizable=1,status=no,scrollbars=yes,toolbars=no');" + " " + "</script>";
cs.RegisterStartupScript(cstype, csname1, cstext1, false);
}
}
I have found the error after 2 weeks of debugging and 2 days of Brute Forcing:
In one of the 800 DB columns that I have there was a null/improper value. This value reacted with one of the 150 methods in my ASP.NET code in such a way as to present a JavaScript error even though Response.Write() was NOT the issue. I have not found which method it was that reacted to this value but I have found the solution which is to simply input a valid value on the column record..
How a programmer can brute force to find the issue:
In my case after long days of debugging I took a sample of one working record and another sample of an error leading record. Once I had achieved this, I used
DELETE FROM tablename WHERE UniqueColID= unique identifier for the error causing record
Then I did:
INSERT INTO tablename ([uniqueIdentifier],[ column 2],[column 3]) SELECT #UniqueIdentifierofErrorCausingRecord, column2, [column3] FROM TableName WHERE [uniqueIdentifier]=#UniqueIdentifierForWorkingRecord;
What the first statement does is delete the non working record then the 2nd statement reinserts that record with identical column values of the working record but with the UniqueIdentifier of the Non working record. This way I can go through each table to find which table is causing the error and then I can pinpoint which column of that table is the issue.
The specific issue in my case was DateTime.TryParse() because a table column value was inserted in improper format.. The code performed field population in one of the methods without a try and catch using the DateTime.Parse method.... After some testing it seems even a try/catch is not able to pick this error up as it is a javascript error..
Don't use Response.Write().
Instead, create a LiteralControl and add it to the page.
Use ClientScriptManager to add scripts to the page. Here's an example from MSDN:
// Define the name and type of the client scripts on the page.
String csname1 = "PopupScript";
Type cstype = this.GetType();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
// Check to see if the startup script is already registered.
if (!cs.IsStartupScriptRegistered(cstype, csname1))
{
String cstext1 = "alert('Hello World');";
cs.RegisterStartupScript(cstype, csname1, cstext1, true);
}

Categories