casting data split to integer - c#

i realize that it does not read inside if (berjaya[23].Equals(70)) as if it was not equal to 70. but when i tried to show berjaya[23] using MessageBox, it do appear 70.
my first guess is casting. i tried int value = (int)(berjaya[23]); and my next plan is try do if(value == 70) but it says string cannot be convert to int.
is there any other way for the (berjaya[23].Equals(70)) be read?
===EDIT===
i should casting the data split by this way:
int.TryParse(berjaya[23], out value1);
then to change the picture, i used this:
if (value1 == 301)
{
Bitmap abc = (Bitmap)System.Drawing.Bitmap.FromFile("C:\\Users\\HDAdmin\\Pictures\\HospitalIcon\\web\\web2\\images\\a3_01.gif");
pictureBox1.Image = abc;
}

Try this, but set the image names
Bitmap abc = (Bitmap)System.Drawing.Bitmap.FromFile("C:\\Users\\HDAdmin\\Pictures\\HospitalIcon\\fafa\\images\\a3_00.gif");
if (berjaya[23].Equals(70))
{
abc = (Bitmap)System.Drawing.Bitmap.FromFile("C:\\Users\\HDAdmin\\Pictures\\HospitalIcon\\fafa\\images\\a3_01.gif");
}
myPicturebox.Image = abc;

You must add first a Empty bitmap.
like:
Bitmap abc;
Or you can assign value for that. Then in if/else you change into:
abc = (Bitmap)System.Drawing.Bitmap.FromFile("C:\\Users\\HDAdmin\\Pictures\\HospitalIcon\\fafa\\images\\a3_01.gif");
Additonal:
Ops, sorry Miss/Mr/Ms (What must I say?) Sara Brown, That will be a much complicated. add this function
public int value(string num){
string a = num.split("");//If this function true?
int res = 0;
for(var b = 0; b<a.Length; b++){
res = res*10;
switch(a[b]){
case "0":
break;
case "1":
res += 1;
break;
case "2":
res += 2;
break;
case "3":
res += 3;
break;
case "4":
res += 4;
break;
case "5":
res += 5;
break;
case "6":
res += 6;
break;
case "7":
res += 7;
break;
case "8":
res += 8;
break;
case "9":
res += 9;
break;
}
}
return res;
}
the add this code
Bitmap abc;
if(value(Berjaya[23])==70){
abc = (Bitmap)System.Drawing.Bitmap.FromFile("C:\\Users\\HDAdmin\\Pictures\\HospitalIcon\\fafa\\images\\a3_01.gif");
}

Related

Values not retained after postback during a method call

I am currently working on migration of a vb.net desktop application into a web application, in the desktop application the previous developer had declared all the variables once on the
form_load
stdate = VB6.Format(Now, "mmddyyyyhh")
current_month = CInt(Mid(stdate, 1, 2))
current_day = CInt(Mid(stdate, 3, 2))
current_year = CInt(Mid(stdate, 5, 4))
current_hour = CInt(Mid(stdate, 9, 2))
base_year = current_year
this_year = current_year
base_month = current_month
this_month = current_month
txtBaseyear.Text = CStr(base_year)
txtBaseMonth.Text = CStr(base_month)
swyearerror = 0
They were then able to use these variables anywhere in the code and it would retain the values.
my application
protected void Page_Load(object sender, EventArgs e)
{
DateTime now = DateTime.Now;
string format = "MMdyyyyhh";
string stdate = now.ToString(format);
Session["stdate"] = stdate;
int current_month = Convert.ToInt32(now.Month);
Session["currentmonth"] = current_month;
int current_day = Convert.ToInt32(now.Day);
Session["currentday"] = current_day;
int current_year = Convert.ToInt32(now.Year);
Session["currentyear"] = current_year;
int current_hour = Convert.ToInt32(now.Hour);
Session["currenthour"] = current_hour;
int base_year = (int)(Session["currentyear"]);
int this_year = (int)(Session["currentyear"]);
int base_month = (int)(Session["currentmonth"]);
int this_month = (int)(Session["currentmonth"]);
TxtBase.Text = Convert.ToString(base_year);
TxtBase1.Text = Convert.ToString(base_month);
}
Now each time there is a post-back when the text is changed the values are lost and set to zero so I tried storing it in a session but that still doesn't work.
Let me give you a visual of my situation.
1) on the first load everything loads fine.
2) then the users enters an item and hits enter
protected void TxtItem_TextChanged(object sender, EventArgs e)
{
Calc_Rotation();
Calc_Best_Before();
}
now...
public void Calc_Rotation()
{
switch (current_month) becomes 0 suppose to be 4
{
case 1:
rotation_month = "A";
break;
case 2:
rotation_month = "B";
break;
case 3:
rotation_month = "G";
break;
case 4:
rotation_month = "J";
break;
case 5:
rotation_month = "K";
break;
case 6:
rotation_month = "L";
break;
case 7:
rotation_month = "N";
break;
case 8:
rotation_month = "P";
break;
case 9:
rotation_month = "S";
break;
case 10:
rotation_month = "W";
break;
case 11:
rotation_month = "Y";
break;
case 12:
rotation_month = "Z";
break;
}
switch (current_hour) becomes 0 suppose to be the current hour
{
case 0:
case 1:
rotation_batch = 2;
break;
case 2:
case 3:
rotation_batch = 4;
break;
case 4:
case 5:
rotation_batch = 6;
break;
case 6:
case 7:
rotation_batch = 8;
break;
case 8:
case 9:
rotation_batch = 10;
break;
case 10:
case 11:
rotation_batch = 12;
break;
case 12:
case 13:
rotation_batch = 14;
break;
case 14:
case 15:
rotation_batch = 16;
break;
case 16:
case 17:
rotation_batch = 18;
break;
case 18:
case 19:
rotation_batch = 20;
break;
case 20:
case 21:
rotation_batch = 22;
break;
case 22:
case 23:
rotation_batch = 24;
break;
}
}
same goes for the Calc_Best_Before
after I tried the postback solution I am still getting 0 values.
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
return;
DateTime now = DateTime.Now;
string format = "MMdyyyyhh";
string stdate = now.ToString(format);
Session["stdate"] = stdate;
int current_month = Convert.ToInt32(now.Month);
Session["currentmonth"] = current_month;
int current_day = Convert.ToInt32(now.Day);
Session["currentday"] = current_day;
int current_year = Convert.ToInt32(now.Year);
Session["currentyear"] = current_year;
int current_hour = Convert.ToInt32(now.Hour);
Session["currenthour"] = current_hour;
int base_year = (int)(Session["currentyear"]);
int this_year = (int)(Session["currentyear"]);
int base_month = (int)(Session["currentmonth"]);
int this_month = (int)(Session["currentmonth"]);
TxtBase.Text = Convert.ToString(base_year);
TxtBase1.Text = Convert.ToString(base_month);
}
Put your code inside the below code. If the web page loads for the first time IsPostBack property is 'false' and code inside the if condition will be executed.
if the page loads after a post back IsPostBack turns to 'true' which cause program execution to escape the if condition.
if (!IsPostBack)
{
}
In case you are using Session to store the values, you need to ensure that you are checking the IsPostBack Property. Otherwise, everytime the page postback occurs, you are initializing the values again and thus you loose the state.
Page.IsPostBack property basically signifies whether the Page is accessing the server for the first time or not.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DateTime now = DateTime.Now;
string format = "MMdyyyyhh";
string stdate = now.ToString(format);
Session["stdate"] = stdate;
int current_month = Convert.ToInt32(now.Month);
Session["currentmonth"] = current_month;
int current_day = Convert.ToInt32(now.Day);
Session["currentday"] = current_day;
int current_year = Convert.ToInt32(now.Year);
Session["currentyear"] = current_year;
int current_hour = Convert.ToInt32(now.Hour);
Session["currenthour"] = current_hour;
int base_year = (int)(Session["currentyear"]);
int this_year = (int)(Session["currentyear"]);
int base_month = (int)(Session["currentmonth"]);
int this_month = (int)(Session["currentmonth"]);
TxtBase.Text = Convert.ToString(base_year);
TxtBase1.Text = Convert.ToString(base_month);
}
}
UPDATE 1:
#CodeMan: You need to use the Session to read the value for the current month in the function Calc_Rotation. You are trying to read the value from the variable current_month which is an int and would default to zero.
I would suggest you to use a Property to wrap up the Session Variable and then use the property in the code. Below, i have created a wrapper property CurrentMonth which encapsulates the Read and write operations on Session in the webpage, declared at class scope. Simmilary you can create wrapper properties for other variables as well. After creating the properties, you need to read the property value in the Calc_Rotation function.
private int CurrentMonth {
get {
var monthfromSession = HttpContext.Current.Session["ClassNameSpace.CurrentMonth"];
return monthfromSession!= null ? (int)monthfromSession : 0;
}
set {
HttpContext.Current.Session["ClassNameSpace.CurrentMonth"] = value;
}
}
public void Calc_Rotation()
{
switch (this.CurrentMonth) // it should have correct month value now.
{
case 1:
rotation_month = "A";
break;
case 2:
rotation_month = "B";
break;
case 3:
....
}
}

Looping through string keeping only digits and decimal points

After reading answers to similar questions I came up with the following approach to my problem of testing the contents of a text box for a number.
My question now is: Is my solution as simple as it can be?
internal static string testStringForNumber(string v)
{
// example: string strToTest = Data.CommonMethods.testStringForNumber(this.amountTextBox.Text.Trim());
string returnValue = "";
string chr = "";
int nLen = v.Length;
int i = 0; // this is my counter
while (i < nLen)
{
chr = v.Substring(i, 1);
switch (chr)
{
case ".":
returnValue = returnValue + chr;
break;
case "0":
returnValue = returnValue + chr;
break;
case "9":
returnValue = returnValue + chr;
break;
case "8":
returnValue = returnValue + chr;
break;
case "7":
returnValue = returnValue + chr;
break;
case "6":
returnValue = returnValue + chr;
break;
case "5":
returnValue = returnValue + chr;
break;
case "4":
returnValue = returnValue + chr;
break;
case "3":
returnValue = returnValue + chr;
break;
case "2":
returnValue = returnValue + chr;
break;
case "1":
returnValue = returnValue + chr;
break;
}
i = i + 1;
}
return returnValue;
}
I'd use a regex instead personally.
string newString = Regex.Replace(strToTest,#"[^\d.]","");
Of course, I don't know WHY you would do this. Something like "Test 23. Test 42." Will return the string 23.42.
It is not, I'll give a one-liner here, but I'd recommend StringBuilder for code maintainance.
public string NumbersAndDecimalPoints(string input)
{
return new string(input.ToCharArray().Where(t => char.IsDigit(t) || t == '.').ToArray());
}
If a string is what you want. Else you can parse it to a number as well.
return decimal.Parse(NumbersAndDecimalsPoints(v));
If on the other hand the task is finding out if the string is a valid number, I'd either go with #Steve and use Any() or just try to parse it.
Using Any() (which won't catch multiple separators):
var isNumber = !input.ToCharArray().Any(c => "1234567890.".IndexOf(c) < 0);
Using TryParse() (really the best method):
var number = 0m;
var isNumber = decimal.TryParse(input, out number); // is number true = is valid number

Assigning variables using switch case

i need to use the variables that is assigned in switch case for my stored procedure but i always get unexpected results .please help..any reply would be a great help.thanks.
private void CheckMessage()
{
string chk = null;
ShortMessage l = new ShortMessage();
string strCommand = "AT+CMGL=\"ALL\"";
objShortMessageCollection = objclsSMS.ReadSMS(this.port, strCommand);
foreach (ShortMessage msg in objShortMessageCollection)
{
l.Message = msg.Message;
string[] splt = l.Message.Split('#');
for (int i = 0; i < splt.Length; i++)
{
string[] parts = splt[i].Split(':');
char prefix = Convert.ToChar(parts[0]);
string value = parts[1];
switch (prefix)
{
case 'T':
l.truck = value;
break;
case 'D':
l.driver = value;
break;
case 'R':
l.receiveby = value;
break;
case 'A':
l.arrivedate = value;
break;
case 'U':
l.unloaddate = value;
break;
case 'N':
l.deliverynote = value;
break;
case 'L':
l.deliverydate = value;
break;
case 'S':
l.deliverystatus = value;
break;
case 'M':
l.mac = value;
break;
case 'C':
l.msgcreatedate = value;
break;
}
}
chk = l.getINFO(l).Tables[0].Rows[0][0].ToString();
if (chk == "1")
{
this.AutomaticReply();
this.DeleteToSim();
}
else
{
this.DeleteToSim();
}
l = null;
}
}
#endregion
here is my stored procedure..
ALTER PROCEDURE [dbo].[Message_Check]
#truck nvarchar(20),
#driver nvarchar(20),
#deliverynote int
AS
BEGIN
SELECT 1 FROM Truck trk, Driver drv, DeliveryNotes dnt
WHERE trk.Plate_Number = #truck
AND drv.DRIVER_ID = #driver
AND dnt.DNID = #deliverynote
AND dnt.Status = 'N'
END
Your query will give output 1..... always
SELECT 1 FROM Truck trk, Driver drv, DeliveryNotes dnt
WHERE trk.Plate_Number = #truck
AND drv.DRIVER_ID = #driver
AND dnt.DNID = #deliverynote
AND dnt.Status = 'N'
It should be
SELECT Top 1 * FROM Truck trk, Driver drv, DeliveryNotes dnt
WHERE trk.Plate_Number = #truck
AND drv.DRIVER_ID = #driver
AND dnt.DNID = #deliverynote
AND dnt.Status = 'N'
One possibility is the character you're looking at isn't a capital, or you might be getting a leading space. See if something like this helps:
char prefix = parts[0].Trim().ToUpper()[0];
If you still have problems, edit your original post and add the structure of the ShortMessage class
Please use Break Points and Debug by Checking the values that are passed to stored procedures.
values may have Extra space like "aa bb " Trim the end values using TrimEnd(' '); function, & Please Parse correctly to its Data types (Int , Double , DateTime etc).the sms you are reading and utilizing for other things. Please check the call is Private / Public so as to reach its values to stored procedures.
char prefix = Convert.ToChar(parts[0]);
use
parts[0]=parts[0].ToUpper();
char prefix = Convert.ToChar(parts[0]);
keep Trying...

c# web service not returning results

I recently "finished" a new project except there is a small problem. Im not getting my results back.
This project utilizes c# web services via a SOAP client along with Request and Response Classes. The project is designed to reserve something, in this demo, it reserves a seat in a cinema. However when the data is passed from the windows form client to the web service, nothing comes back. I recently stopped the project from freezing upon execution of the web method.
This is the method that calls the web service (The method signature is only temporary)
public void derp()
{
var client = new SampleServiceSoapClient();
var req = new GetReservationRequest();
req.row = row;
req.seat = seat;
req.name = textNameRequest.Text;
try
{
client.GetReservation(req);
}
catch (Exception err)
{
MessageBox.Show("Server Unavailable");
}
}
I am running this method on a seperate thread to stop crashing. The output of this method is supposed to come back through a response object and then i assign the values of said object to text boxes on the form. However, the data is lost before it returns.
The web method is as follows
[WebMethod]
public GetReservationResponse GetReservation(GetReservationRequest req)
{
object o = HttpContext.Current.Cache["Reservation"];
if(o == null)
{
o = reservedSeat;
}
else
{
reservedSeat = (bool[,])o;
}
GetReservationResponse resp = new GetReservationResponse();
string rowHolder = "A";
int rowRequest = req.row;
int seatCopy = 0;
bool emptySeat = false;
while (rowRequest < 12)
{
for (int seat = req.seat; seat < 16; seat++)
{
if (reservedSeat[req.row, seat])
{
//Loop back
}
else
{
emptySeat = true;
seatCopy = seat;
break;
}
}
if (reservedSeat[req.row, 15])
{
seatCopy = 0;
break;
}
}
switch (rowRequest)
{
case 1: rowHolder = "A";
break;
case 2: rowHolder = "B";
break;
case 3: rowHolder = "C";
break;
case 4: rowHolder = "D";
break;
case 5: rowHolder = "E";
break;
case 6: rowHolder = "F";
break;
case 7: rowHolder = "G";
break;
case 8: rowHolder = "H";
break;
case 9: rowHolder = "I";
break;
case 10: rowHolder = "J";
break;
case 11: rowHolder = "K";
break;
case 12: rowHolder = "L";
break;
default: rowHolder = "None Specified";
break;
}
int x = 0;
if (!reservedSeat[rowRequest, seatCopy])
{
reservedSeat[rowRequest, seatCopy] = true;
seatCopy++;
//resp.row = rowRequest;
x = seatCopy;
seatCopy--;
if (seatCopy.Equals(15))
{
rowRequest++;
}
}
resp.row = rowHolder;
resp.seat = x;
//row++
return resp;
}
I have no clue why the data is being lost before it comes back but some information would be amazing...
Where in this code rowrequest is incremented? It seems to me, that you have infinite loop here:
while (rowRequest < 12)
{
for (int seat = req.seat; seat < 16; seat++)
{
if (reservedSeat[req.row, seat])
{
//Loop back
}
else
{
emptySeat = true;
seatCopy = seat;
break;
}
}
if (reservedSeat[req.row, 15])
{
seatCopy = 0;
break;
}
}

c# compiler ILSpy on WP7

I use ILSpy and .NET Reflector to see code, and I found code I don't understand it, I serach in the web and I don't found any1 can help how to resolve it.
This code with ILSpy (.NET Reflector show the same)
private void Item_Clicked(object sender, EventArgs e)
{
switch (0)
{
case 0:
{
IL_0E:
FileSystemItem fileSystemItem;
while (true)
{
fileSystemItem = (sender as FileSystemItem);
int num = 1;
while (true)
{
switch (num)
{
case 0:
if (<PrivateImplementationDetails>{4E2292E7-C82C-431F-9529-B0045F4C1457}.$$method0x60003e4-1 != null)
{
goto IL_25F;
}
if (true)
{
IL_163:
num = 3;
continue;
}
goto IL_163;
case 1:
if (fileSystemItem != null)
{
num = 11;
continue;
}
return;
case 2:
goto IL_3B8;
case 3:
{
Dictionary<string, int> expr_1B9 = new Dictionary<string, int>(9);
expr_1B9.Add(".mp3", 0);
expr_1B9.Add(".wav", 1);
expr_1B9.Add(".wma", 2);
expr_1B9.Add(".wmv", 3);
expr_1B9.Add(".avi", 4);
expr_1B9.Add(".jpg", 5);
expr_1B9.Add(".png", 6);
expr_1B9.Add(".txt", 7);
expr_1B9.Add(".inf", 8);
<PrivateImplementationDetails>{4E2292E7-C82C-431F-9529-B0045F4C1457}.$$method0x60003e4-1 = expr_1B9;
num = 15;
continue;
}
case 4:
{
string ext;
if ((ext = fileSystemItem.Ext) != null)
{
num = 8;
continue;
}
return;
}
case 5:
goto IL_2C9;
case 6:
num = 12;
continue;
case 7:
{
string ext;
int num2;
if (<PrivateImplementationDetails>{4E2292E7-C82C-431F-9529-B0045F4C1457}.$$method0x60003e4-1.TryGetValue(ext, ref num2))
{
num = 6;
continue;
}
return;
}
case 8:
num = 0;
continue;
case 9:
goto IL_25A;
case 10:
goto IL_36A;
case 11:
num = 14;
continue;
case 12:
{
int num2;
switch (num2)
{
case 0:
case 1:
case 2:
num = 16;
continue;
case 3:
case 4:
goto IL_171;
case 5:
case 6:
goto IL_1A4;
case 7:
case 8:
this.ShowText(fileSystemItem.Path);
num = 9;
continue;
default:
num = 13;
continue;
}
break;
}
case 13:
return;
case 14:
if (fileSystemItem.IsFolder)
{
switch ((1 == 1) ? 1 : 0)
{
case 0:
case 2:
goto IL_36F;
case 1:
IL_2B7:
if (false)
{
IL_2BD:
num = 5;
continue;
}
goto IL_2BD;
}
goto IL_2B7;
}
num = 4;
continue;
case 15:
goto IL_25F;
case 16:
if (fileSystemItem.IsPlaying)
{
num = 10;
continue;
}
goto IL_36F;
}
break;
IL_25F:
num = 7;
continue;
IL_36F:
BackgroundAudioPlayer.get_Instance().set_Track(new AudioTrack(new Uri(fileSystemItem.Path, 2), "Unknown", "Unknown", "Unknown", null));
IEnumerator<object> enumerator = this.filesListBox.get_Items().GetEnumerator();
num = 2;
}
}
IL_131:
BackgroundAudioPlayer.get_Instance().Stop();
fileSystemItem.IsPlaying = false;
return;
IL_171:
MediaPlayerLauncher mediaPlayerLauncher = new MediaPlayerLauncher();
mediaPlayerLauncher.set_Media(new Uri(fileSystemItem.Path, 2));
mediaPlayerLauncher.set_Location(2);
mediaPlayerLauncher.Show();
return;
IL_1A4:
this.ShowImage(fileSystemItem.Path);
return;
IL_25A:
return;
IL_2C9:
this.ShowFolderContents(fileSystemItem.Path);
return;
IL_36A:
goto IL_131;
IL_3B8:
try
{
int num = 2;
while (true)
{
switch (num)
{
case 0:
num = 1;
continue;
case 1:
goto IL_EC;
case 3:
{
IEnumerator<object> enumerator;
if (!enumerator.MoveNext())
{
num = 0;
continue;
}
FileSystemItem fileSystemItem2 = (FileSystemItem)enumerator.get_Current();
fileSystemItem2.IsPlaying = false;
num = 4;
continue;
}
}
IL_A7:
num = 3;
continue;
goto IL_A7;
}
IL_EC:
goto IL_23A;
}
finally
{
int num = 2;
while (true)
{
IEnumerator<object> enumerator;
switch (num)
{
case 0:
goto IL_12E;
case 1:
enumerator.Dispose();
num = 0;
continue;
}
if (enumerator == null)
{
break;
}
num = 1;
}
IL_12E:;
}
goto IL_131;
IL_23A:
fileSystemItem.IsPlaying = true;
return;
}
}
goto IL_0E;
}
the error of this dictionnary show me this error
<PrivateImplementationDetails>{4E2292E7-C82C-431F-9529-B0045F4C1457}.$$method0x60003e4-1
So, this what? and how Can I resolve that?
I need to replace it with another variable or what?
<PrivateImplementationDetails>{4E2292E7-C82C-431F-9529-B0045F4C1457} is not a proper C# construct. This is perhaps a substitute name which ILSpy issues to some internal framework function, which is not supposed to be used by ordinary developers.
So you need to reverse-engineer the code and understand what does it really do. And implement it by some other means. You cannot just take it and use it :)
By the way, the code seems to be an obfuscated one, while there are lots of unnecessary instructions there. In your case, the whole loop/switch codes a state machine in a fancy way. (It could be that its execution is always sequential, so you ought to try tracing it manually -- with paper and pencil. Try it, it's fun!)

Categories

Resources