Solved

VB.Net to C#...... (Struggling)

Posted on 2014-03-20
16
310 Views
Last Modified: 2014-03-21
I've been working with VB.Net for years, pretty good at it, but now I'm attempting to write my first web app in C#.

Starting off slow, with a simple form that has one text box, a submit button, and a cancel button.

On the back end, I just want to begin with a simple validation to make sure that the text box isn't empty on submit.

       
protected void Submit_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(tbPCName.Text))
            {
                UserMsgBox(this, "Please enter a computer name.");
            }
            else
            {
            }
        }

Open in new window


Below that I have the method that kicks out the message box. In VB it looked like this:

   
Public Sub UserMsgBox(ByVal F As Object, ByVal sMsg As String)
        Dim sb As New StringBuilder()
        Dim oFormObject As System.Web.UI.Control = Nothing
        Try
            sMsg = sMsg.Replace("'", "\'")
            sMsg = sMsg.Replace(Chr(34), "\" & Chr(34))
            sMsg = sMsg.Replace(vbCrLf, "\n")
            sMsg = "<script language='javascript'>alert('" & sMsg & "');</script>"
            sb = New StringBuilder()
            sb.Append(sMsg)
            For Each oFormObject In F.Controls
                If TypeOf oFormObject Is HtmlForm Then
                    Exit For
                End If
            Next
            oFormObject.Controls.AddAt(oFormObject.Controls.Count, New LiteralControl(sb.ToString()))
        Catch ex As Exception
        End Try
    End Sub

Open in new window


I attempted to use a VB to C# Converter and got the following. I should also point out that after some research, I found out that Strings is VB.Net class. String appears in C#, but it doesn't like String.Chr either.

           
public void UserMsgBox(object F, string sMsg)
            {
	            System.Text.StringBuilder sb = new System.Text.StringBuilder();
	            System.Web.UI.Control oFormObject = null;
	            try {
		            sMsg = sMsg.Replace("'", "\\'");
		            sMsg = sMsg.Replace(Strings.Chr(34), "\\" + Strings.Chr(34));
		            sMsg = sMsg.Replace(Constants.vbCrLf, "\\n");
		            sMsg = "<script language='javascript'>alert('" + sMsg + "');</script>";
		            sb = new System.Text.StringBuilder();
		            sb.Append(sMsg);
		            foreach (System.Web.UI.Control oFormObject_loopVariable in F.Controls) {
			            oFormObject = oFormObject_loopVariable;
			            if (oFormObject is HtmlForm) {
				            break; // TODO: might not be correct. Was : Exit For
			            }
		            }
		            oFormObject.Controls.AddAt(oFormObject.Controls.Count, new LiteralControl(sb.ToString()));
	            } catch (Exception ex) {
	            }

Open in new window


I always enjoyed using the above function because it was clean and concise, but if you've got a more efficient or better way in C#, I'm more than willing to use that.

Thanks in advance,

JB
0
Comment
Question by:JB4375
  • 7
  • 6
  • 2
  • +1
16 Comments
 
LVL 23

Assisted Solution

by:Jens Fiederer
Jens Fiederer earned 300 total points
ID: 39943816
Probably the simplest way to get a C# character using numeric code is to use literals as in
http://msdn.microsoft.com/en-us/library/aa691090(v=vs.71).aspx

So Chr(34) would be '\x22'


Note that the .NET-like way to do this, whether you are in C# or in VB.Net, is to use Validators such as

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.requiredfieldvalidator(v=vs.110).aspx
0
 
LVL 23

Expert Comment

by:Jens Fiederer
ID: 39943820
You can also just case from an integer type, like
(char)34
0
 
LVL 23

Expert Comment

by:Jens Fiederer
ID: 39943825
Sorry, I meant CAST not case.

"foo" + (char)34

->

"foo\""
0
 
LVL 29

Assisted Solution

by:anarki_jimbel
anarki_jimbel earned 100 total points
ID: 39943847
If you use sMsg = sMsg.Replace("'", "\\'") for sigle quotation mark, why not use                        sMsg = sMsg.Replace("\"", "\\" + "\"") for character 34. Char 34 is double quota.

"break" in your code should work.

F.Controls will not work - you need to cast it to a proper type...

For vbCrLf  - use Enviroment.NewLine:

sMsg = sMsg.Replace(Environment.NewLine, "\\n");
0
 
LVL 1

Author Comment

by:JB4375
ID: 39943874
Sorry.... not really sure what I'm supposed to do with foo. Definitely doesn't like:

 sMsg = sMsg.Replace("foo" + (char)34), "\\" + "foo" + (char)34);

Again if there's an easier way to handle the message box, that's OK. I made the mistake of assuming I was just missing something on the conversion that would be easier to correct by someone else more familiar with C#.
0
 
LVL 1

Author Comment

by:JB4375
ID: 39943885
Anarki,

So:  sMsg = sMsg.Replace(Strings.Chr(34), "\\" + Strings.Chr(34));

Becomes:  sMsg = sMsg.Replace("\"", "\\" + "\"")
0
 
LVL 23

Assisted Solution

by:Jens Fiederer
Jens Fiederer earned 300 total points
ID: 39943894
The "foo" was just an example of using a char as part of a string (in C# string and char are completely different datatypes, so to make a string containing a double-quote char you could use

"" + (char)34

The reason I mentioned that is that you seemed to want to know an equivalent for the VB Chr method -- as anarki_jimbel mentioned you don't actually NEED it in that context.
0
 
LVL 1

Author Comment

by:JB4375
ID: 39943904
Here's what I currently have at this point. Could you elaborate on "F.Controls will not work - you need to cast it to a proper type..."

            public void UserMsgBox(object F, string sMsg)
            {
                  System.Text.StringBuilder sb = new System.Text.StringBuilder();
                  System.Web.UI.Control oFormObject = null;
                  try {
                        sMsg = sMsg.Replace("'", "\\'");
                        sMsg = sMsg.Replace("\"", "\\" + "\"");
                        sMsg = sMsg.Replace(Environment.NewLine, "\\n");
                        sMsg = "<script language='javascript'>alert('" + sMsg + "');</script>";
                        sb = new System.Text.StringBuilder();
                        sb.Append(sMsg);
                        foreach (System.Web.UI.Control oFormObject_loopVariable in F.Controls) {
                              oFormObject = oFormObject_loopVariable;
                              if (oFormObject is HtmlForm) {
                                    break; // TODO: might not be correct. Was : Exit For
                              }
                        }
                        oFormObject.Controls.AddAt(oFormObject.Controls.Count, new LiteralControl(sb.ToString()));
                  } catch (Exception ex) {
                  }
0
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 
LVL 1

Author Comment

by:JB4375
ID: 39943965
Nevermind....

Seems like this is too much for what needs to be done.

How about this? The only error I'm getting now is on the last line: Result is a 'field' but used like a 'type'.

        protected void Submit_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(tbPCName.Text))
            {
                UserMsgBox();
            }
            else
            {
            }
        }

        public void UserMsgBox();
              string message = "Please enter a computer name.";
            string caption = "Input Error";
                  MessageBoxButtons buttons = MessageBoxButtons.OK;
                  DialogResult result;

                  // Displays the MessageBox.

                  result = MessageBox.Show(message, caption, buttons);
        }
0
 
LVL 29

Expert Comment

by:anarki_jimbel
ID: 39943994
Looks OK,

You can use MessageBox.Show(message, caption) overload, I believe it shows "OK" by default.
0
 
LVL 1

Author Comment

by:JB4375
ID: 39945258
result = MessageBox.Show(message, caption, buttons);

is generating the following errors:

Error      1      Invalid token '=' in class, struct, or interface member declaration      
Error      2      Invalid token '(' in class, struct, or interface member declaration
Error      3      Invalid token ',' in class, struct, or interface member declaration
Error      4      Invalid token ',' in class, struct, or interface member declaration
Error      5      Invalid token ')' in class, struct, or interface member declaration
0
 
LVL 23

Assisted Solution

by:Jens Fiederer
Jens Fiederer earned 300 total points
ID: 39945277
You left out the left curly bracket.  

Your indentation suggests you are trying to define a function UserMsgBox - but you actually just DECLARE it (the line ends in a semicolon) and then declare some strings.  

Anyway, the MessageBox.Show functionality is appropriate for a Windows Forms application, not for a web app.
0
 
LVL 74

Accepted Solution

by:
käµfm³d   👽 earned 100 total points
ID: 39945318
For web applications, you are aware that MessageBox.Show only works on the development machine, yes? The reason being that the code is running on the same machine where the page is being requested from. Once you deploy you web application to a web server, end users won't see the message box because the code will be running on the server, not the client.

Actually, having a MessageBox in this way is actually a bad thing because MessageBox.Show is a blocking operation:  until someone actually clicks "OK", the thread that is running that code will be blocked.

To show a message box to the user in a web application, you would use the alert function like you did in your original code.
0
 
LVL 1

Author Closing Comment

by:JB4375
ID: 39945459
Yes.... I do remember reading that at some point. I'd been dropping the java script code in for so long that I forgot. Nothing like learning something the hard way. Twice.

Awarding points and closing this question as solved. The point here is to learn and I'm not nearly as far along as I thought I was. Back to the drawing board. Thanks guys!!
0
 
LVL 23

Expert Comment

by:Jens Fiederer
ID: 39945470
Pleasure, thanks.

Since you are trying to learn, I very much recommend looking at the Validation controls for doing this sort of thing.
0
 
LVL 1

Author Comment

by:JB4375
ID: 39945524
Right, I checked the MSDN link for the Required Field Validators, and while I may be leaving myself completely open to ridicule.....  

I have to say that the incredibly massive layouts resulting from Microsoft's efforts to be as thorough as possible tend to create more confusion for me to the point that they literally give me a headache. I find it much more helpful to seek out examples that offer problem/solution scenarios.

Granted that kind of leaves in dark room with a tiny flashlight, only seeing a little bit at a time. But I've yet to figure out how to learn from looking at long lists of properties and methods with tiny examples at the end.

Thanks again!!
0

Featured Post

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now