Showing posts with label code. Show all posts
Showing posts with label code. Show all posts

Saturday, March 31, 2012

String to html conversion

I want to send an email in html format through code. Problem I am having is converting the string into html without and grumps. Does .net have a class that converts this easily. I have tried doing a search and replace chracters, but still having issues. Or has anyone done anything similar?

BC

hi bcanonica,

do you have some sample code on you that i could look into?

regards,

zee


Hello,

By default, email sent with System.Net.Mail is formatted as plain text. To format as Html, set the MailMessage.IsBodyHtml property to true.

[ C# ]

 //create the mail message MailMessage mail = new MailMessage(); //set the addresses mail.From = new MailAddress("me@.mycompany.com"); mail.To.Add("you@.yourcompany.com"); //set the content mail.Subject = "This is an email"; mail.Body = "this is a sample body with html in it. <b>This is bold</b> <font color=#336699>This is blue</font>"; mail.IsBodyHtml = true; //send the message SmtpClient smtp = new SmtpClient("127.0.0.1"); smtp.Send(mail);


[ VB.NET ]

 'create the mail messageDim mail As New MailMessage()'set the addressesmail.From = New MailAddress("me@.mycompany.com")mail.To.Add("you@.yourcompany.com")'set the contentmail.Subject = "This is an email" mail.Body = "this is a sample body with html in it. <b>This is bold</b> <font color=#336699>This is blue</font>"mail.IsBodyHtml = True'send the messageDim smtp As New SmtpClient("127.0.0.1")smtp.Send(mail)

Not exactly what I was looking for. I want to know how I can convert an html email that I create in Publisher to to a string so I can send it in the body of mailMessage object. Is their a namespace that converts from a string to html and vis versa. Meaning using quotes and other characters that do not match.

BC


You can useServer.HtmlEncode and alsoHttpServerUtility.HtmlEncode Method andHttpServerUtility.HtmlDecode Method.

Here still is another way to do such things:Rendering a control as an Html String

HTH

string to string[]

Hi,

I've got this code :


string[] Params;

string SQL = "SELECT * FROM T_MANAGEMENT_PAGES";
SqlCommand myCommand = new SqlCommand(SQL, myConnection);
myConnection.Open();
SqlDataReader myReader = myCommand.ExecuteReader();

try
{
while (myReader.Read())
{
Params_Type = myReader.GetValue(0).ToString();
}
}
catch
{
}
finally
{
}
myReader.Close();

My problem is to obtain Params_Type.
But each time, it says : "impossible to convert '[object]' in 'string[]' "

Thanks for all.
SébHello, try this instead:


int i = 0;
while (myReader.Read())
{
Params_Type[i] = myReader.GetValue(0).ToString();
i++;
}

Hope this works fine for u.
Yes but, in my database I have in one column :
{"BURE_ETUD_ID","LANG_ID","LANG_NAME"}

My sql return only one line.

and what I want is :


string[] Params = {"BURE_ETUD_ID","LANG_ID","LANG_NAME"};

Thanks
Séb
You should, ideally, rework your database. This is not a great layout. You should have a table that links to this record and has one row per entry to allow you to better get at the data.

Given the string returned as it is, you could use String.Split() to create a string array.
I Agree with you, but is there any possibility to convert one string in one string[] ?

Séb
Yes. As I mentioned in my last post: the String class has a Split() method. Please look at the docs.
I'm sorry, i haven't see the end of your message.

Thanks for your heulp

Regards

Séb
Hello,
I believe yes, you should rework ur database, each value should be in one column. this is typical !!!
then, after u rework ur database, use the code i gave, it works just fine.

Good Luck.

String Trancate

Hi,

In following example I would like to Trancate first 5 digits and last 3 digits.

W04056040-PAY001

So I can get 6040-PAY

Any code behind examples?

Any help will be appriciated.

Thanks.

TekinUse the stringbuilder class (remove method):

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemtextstringbuildermemberstopic.asp

Or if you want to do it old school, the intrinsic Mid function works well too.
Hi mtekin303,

There's many ways to solve this problem. Here's two ideas:


[Visual Basic]
Dim temp As String = "W04056040-PAY001"
Response.Write("Sample 1: " + temp.Substring(5,8) + "<br />")
Response.Write("Sample 2: " + temp.Remove(temp.Length-3,3).Remove(0,5))

[C#]
string temp = "W04056040-PAY001";
Response.Write("Sample 1: " + temp.Substring(5,8) + "<br />");
Response.Write("Sample 2: " + temp.Remove(temp.Length-3,3).Remove(0,5));


Hope this helps.
Thank you.

Stringbuilder resolved it.

Thanks again.
Thanks Chuck.

Stringbuilder resolved it.

String was not recognized as a valid DateTime

I moved some projects to another server and using the code below i get
the error:-
"String was not recognized as a valid DateTime"
<asp:Label runat="server" width="40%" text='
<%#
DateTime.Parse(DataBinder.Eval(Container,"DataItem.dt").ToString()).ToSh
ortDateString()%>' id="Label6">
*** Sent via Developersdex http://www.examnotes.net ***Well folks...
I added:-
culture="en-US"
to the globalization in Web.Config and did the trick
<globalization
requestEncoding="utf-8"
responseEncoding="utf-8"
culture="en-US"
/>
*** Sent via Developersdex http://www.examnotes.net ***
Hi Patrick,
If you just use DataBinder.Eval(Container,"DataItem.dt").ToString() is
anything displayed?
If it is, I would be checking that the date format matches your Regional
Settings (System Account). If you are using SQL I��d also be checking that
the collation of the new server/database is the same as your old one.
Brad.
"Patrick Olurotimi Ige" wrote:

> I moved some projects to another server and using the code below i get
> the error:-
> "String was not recognized as a valid DateTime"
> <asp:Label runat="server" width="40%" text='
> <%#
> DateTime.Parse(DataBinder.Eval(Container,"DataItem.dt").ToString()).ToSh
> ortDateString()%>' id="Label6">
>
> *** Sent via Developersdex http://www.examnotes.net ***
>
> <asp:Label runat="server" width="40%" text='
> <%#
> DateTime.Parse(DataBinder.Eval(Container,"DataItem.dt").ToString()).To
> Sh
> ortDateString()%>' id="Label6">
Why don't you just do this instead:
<%# ((DateTime)DataBinder.Eval(Container.DataItem, "dt")).ToShortDateString(
)
%>
-Brock
DevelopMentor
http://staff.develop.com/ballen

Wednesday, March 28, 2012

String was not recognized as a valid DateTime

I moved some projects to another server and using the code below i get
the error:-

"String was not recognized as a valid DateTime"

<asp:Label runat="server" width="40%" text='
<%#
DateTime.Parse(DataBinder.Eval(Container,"DataItem.dt").ToString()).ToSh
ortDateString()%>' id="Label6"
*** Sent via Developersdex http://www.developersdex.com ***Well folks...
I added:-
culture="en-US"
to the globalization in Web.Config and did the trick

<globalization
requestEncoding="utf-8"
responseEncoding="utf-8"
culture="en-US"
/
*** Sent via Developersdex http://www.developersdex.com ***
Hi Patrick,

If you just use DataBinder.Eval(Container,"DataItem.dt").ToString() is
anything displayed?

If it is, I would be checking that the date format matches your Regional
Settings (System Account). If you are using SQL I'd also be checking that
the collation of the new server/database is the same as your old one.

Brad.

"Patrick Olurotimi Ige" wrote:

> I moved some projects to another server and using the code below i get
> the error:-
> "String was not recognized as a valid DateTime"
> <asp:Label runat="server" width="40%" text='
> <%#
> DateTime.Parse(DataBinder.Eval(Container,"DataItem.dt").ToString()).ToSh
> ortDateString()%>' id="Label6">
>
> *** Sent via Developersdex http://www.developersdex.com ***
> <asp:Label runat="server" width="40%" text='
> <%#
> DateTime.Parse(DataBinder.Eval(Container,"DataItem.dt").ToString()).To
> Sh
> ortDateString()%>' id="Label6"
Why don't you just do this instead:

<%# ((DateTime)DataBinder.Eval(Container.DataItem, "dt")).ToShortDateString()
%
-Brock
DevelopMentor
http://staff.develop.com/ballen

String was not recognized as a valid DateTime

I retrive data from web service. My date is in the format 20/6/2006 0:00. When I try to format date with the following code it gives me above error.

the code is

String.Format("{0:MMMM d, yyyy}",Date.Parse(_landcorReport.vrValuationDate))

please help me

please guys can any one help me?
Hi,
Make sure you are getting valid date in _landcorReport.vrValuationDate. Try using TryParse with an out variable of DateTime type, and then try to format it.

DateTime dt;
bool result = DateTime.TryParse(_landcorReport.vrValuationDate.ToString(), out dt);

Thanks,


unless you are doing Visual J#, you should be usingDateTime.Parse instead

String.Format ( "{0:MMMM d, yyyy}",DateTime.Parse ( _landcorReport.vrValuationDate ) )

that should work assuming of course that _landcorReport.vrValuationDate returns a string that is convertible to a valid date


ReyN:

unless you are doing Visual J#, you should be usingDateTime.Parse instead

String.Format ( "{0:MMMM d, yyyy}",DateTime.Parse ( _landcorReport.vrValuationDate ) )

that should work assuming of course that _landcorReport.vrValuationDate returns a string that is convertible to a valid date

If the input string cannot be converted to DateTime, an exception will be thrown. If you are not sure whether the input string can be converted to datetime, use the TryParse, as this method tries to parse only if the input string is valid and gives you the result if succeeded into the out variable. If you are not using TryParse, you need to use a try {} catch {} block to handle the exception.

Thanks

This method is available in .Net 2.0 while I'm working in .Net 1.1
Hi
Check if the value of_landcorReport.vrValuationDate is a valid date, or use your statement in try catch block

THanks

String.Equals Wrong Parameter ?

In VisStudio.Net 1,0, I am receiving the error "Parameter is Incorrect" on lines 5, 6, and 7 below. Line 8 works correctly. This is code I picked up from the MSFT website - any ideas as to what could be wrong with it?

Thanks
Mike Thomas

1 Dim sb As New StringBuilder("abcd")
2 Dim str1 As [String] = "abcd"
3 Dim str2 As [String] = Nothing
4 Dim o2 As [Object] = Nothing

5 ? str1.Equals(sb)
6 ? str1.Equals(o2)
7 ? str1.Equals(str2)
8 ? [String].Equals(str1, str2)

At top is

Imports System.String
Imports System.TextHi,

my guess would be that you have Option Strict set to On so that you have to cast specifically. Try something like this:


str1.Equals(sb.ToString)

Grz, Kris.
Many thanks Kris - that was exactly it.

Mike Thomas

string.format gridview cell

I am trying to use the following code to format specific cells in my gridview and failing. I can successfully format a column by setting htmlencode off and string.format for the field, but I need to control the formatting at the cellular level :-). I can get font, color etc, but not string.format. I can add to the string i.e. in the code below everything works, except the <code> "

Case"Sales"

For i = 1To e.Row.Cells.Count - 1

IfNot RTrim(e.Row.Cells(i).Text.ToString) =""Then

e.Row.Cells(i).Text =String.Format("{0:c}", e.Row.Cells(i).Text)

EndIf

Next

"</code>

Also if not rtrim(e.row.cells(i).text.tostring = "" does not do anything for me, what is the correct syntax so that empty cells do not recieving this formatting?

<code>

Sub gridview2_rowdatabound(ByVal senderAsObject,ByVal eAs GridViewRowEventArgs)Handles GridView2.RowDataBound

Dim iAsInteger

If e.Row.RowType = DataControlRowType.DataRowThen

e.Row.Cells(4).Font.Bold =True

e.Row.Cells(8).Font.Bold =True

e.Row.Cells(12).Font.Bold =True

e.Row.Cells(16).Font.Bold =True

e.Row.Cells(17).Font.Bold =True

e.Row.Cells(4).BackColor = Drawing.Color.LightGray

e.Row.Cells(8).BackColor = Drawing.Color.LightGray

e.Row.Cells(12).BackColor = Drawing.Color.LightGray

e.Row.Cells(16).BackColor = Drawing.Color.LightGray

e.Row.Cells(17).BackColor = Drawing.Color.LightGray

SelectCase RTrim(e.Row.Cells(0).Text)

Case"Sales"

For i = 1To e.Row.Cells.Count - 1

IfNot RTrim(e.Row.Cells(i).Text.ToString) =""Then

e.Row.Cells(i).Text =String.Format("{0:c}", e.Row.Cells(i).Text)

EndIf

Next

Case"Gross Profit"

For i = 1To e.Row.Cells.Count - 1

IfNot e.Row.Cells(i).TextIsNothingThen

e.Row.Cells(i).Text ="$" & e.Row.Cells(i).Text

EndIf

Next

EndSelect

EndIf

EndSub

</code>

Thanks

if you change your trouble code to this:

String str =String.Format("{0:c}", e.Row.Cells(i).Text);
e.Row.Cells(i).Text =String.Format("{0:c}", e.Row.Cells(i).Text)

and debugg it,

what result to you get for str?
Does it format it?
Does your code even go into the if statement above the trouble line?

foregive my ignorance, is there a way to see the value of a variable in vs.net during a debugging session besides assigning it to a label in my web app?

I do know that the code does go into the if statement as changing the code to me e.row.cells(i).text = "$" & e.row.cells(i).text gives me the expected result in the gridview cell.

Also the app compiles without error.

Thanks in advance for your assistance.


Ok, I placed a break immediately after the str1 = string.format...

and in my vs.net 2005 it shows the number with no formatting.

"Good news is I now see how to trouble shoot my code without adding extra labels etc on my application to display variables just so that I know what is being assigned to the variable" Bad news, I still don't see why string.format is not working.


Oops. Disregard this post, plz.


Try this:

IfNot RTrim(e.Row.Cells(i).Text.ToString) =""Then

e.Row.Cells(i).Text =String.Format("{0:c}", Double.Parse(e.Row.Cells(i).Text))

EndIf


that works perfectly. Thank you

String.Formatting a javascript code sample, how do I escape the { } characters?

Hi,

I'm trying to String.format a piece of javascript code

string.Format("function showalert(msg) { window.status = '{0}'; alert(msg); }", "Test");

This compiles ok but when it runs it has a Input string was not in a correct format exception as the '{' and '}' characters are reserved and used for substitution in the string.Format function.

Is there a way I can escape the '{}' characters so that the string.format function ignores them?

I've tried

string.Format("function showalert(msg) \{ window.status = '{0}'; alert(msg); \}", "Test");

which is normally how you escape but it dosen't work.

Thanks for your help

Auschucky

Hi ,To specify a single literal brace character informat, specify two leading or trailing brace characters; that is, "{{" or "}}".
string test =string.Format("function showalert(msg) {{ window.status = '{0}'; alert(msg); }}","Test");
Hope this helps , Gook Luck^_^
Ta, worked a treat

String.Replace() in .net 1.1 did not work!

Hi, guys,

The following source code in Page_Load() did not work:

string pathVal = "2006\";
pathVal.Replace("\\", "/");

I still had the value "2006\", not "2006/", the one I expected.

I then tried the second line as:

pathVal.Replace('\', '/');

still no luck.

Any ideas? Thanks.Replace probably returns a new string that you need to set a variable to.

"Andrew" <Andrew@.discussions.microsoft.com> wrote in message
news:74E97D68-79AC-47AB-B2D3-802DF9579D77@.microsoft.com...
> Hi, guys,
> The following source code in Page_Load() did not work:
> string pathVal = "2006\";
> pathVal.Replace("\\", "/");
> I still had the value "2006\", not "2006/", the one I expected.
> I then tried the second line as:
> pathVal.Replace('\', '/');
> still no luck.
> Any ideas? Thanks.
You need to get the value value returned by Replace function. It returns
stirng variable.
"Andrew" <Andrew@.discussions.microsoft.com> wrote in message
news:74E97D68-79AC-47AB-B2D3-802DF9579D77@.microsoft.com...
> Hi, guys,
> The following source code in Page_Load() did not work:
> string pathVal = "2006\";
> pathVal.Replace("\\", "/");
> I still had the value "2006\", not "2006/", the one I expected.
> I then tried the second line as:
> pathVal.Replace('\', '/');
> still no luck.
> Any ideas? Thanks.
String.Replace() returns a new String value. You can always set the
returned value to the original string.

String.Replace() in .net 1.1 did not work!

Hi, guys,
The following source code in Page_Load() did not work:
string pathVal = "2006\";
pathVal.Replace("\\", "/");
I still had the value "2006\", not "2006/", the one I expected.
I then tried the second line as:
pathVal.Replace('\', '/');
still no luck.
Any ideas? Thanks.Replace probably returns a new string that you need to set a variable to.
"Andrew" <Andrew@.discussions.microsoft.com> wrote in message
news:74E97D68-79AC-47AB-B2D3-802DF9579D77@.microsoft.com...
> Hi, guys,
> The following source code in Page_Load() did not work:
> string pathVal = "2006\";
> pathVal.Replace("\\", "/");
> I still had the value "2006\", not "2006/", the one I expected.
> I then tried the second line as:
> pathVal.Replace('', '/');
> still no luck.
> Any ideas? Thanks.
>
You need to get the value value returned by Replace function. It returns
stirng variable.
"Andrew" <Andrew@.discussions.microsoft.com> wrote in message
news:74E97D68-79AC-47AB-B2D3-802DF9579D77@.microsoft.com...
> Hi, guys,
> The following source code in Page_Load() did not work:
> string pathVal = "2006\";
> pathVal.Replace("\\", "/");
> I still had the value "2006\", not "2006/", the one I expected.
> I then tried the second line as:
> pathVal.Replace('', '/');
> still no luck.
> Any ideas? Thanks.
>
String.Replace() returns a new String value. You can always set the
returned value to the original string.

Monday, March 26, 2012

string.trimstart()

I got to be something stupid, but for some reason I can get this code to work:

string username = HttpContext.Current.User.Identity.Name.ToString();char[] MyChar = {' ','\\'}; Login1.UserName = username.TrimStart(MyChar);

I want to trim the \ of: MAINOFFICE\username

Thanks,

Erick

Can you use :

username.Replace(@."\","");
TrimStart removes all the occurances from the beginning of the instance. "\" appears in the middle of the string.
string username ="MAINOFFICE\\username";

txtOutput.Text = username.Remove(0, username.LastIndexOf("\\") + 1);

that will work, assuming that usernames cant have the \ in them :P


keyboardcowboy:

username.LastIndexOf("\\")

Won't that just give the last index of the string?


I'm sorry. What I mean to said was I want to trim everything before the \, but sometimes it might not be MAINOFFICE thats the problem I'm having. I just want the username.


bullpit:

keyboardcowboy:

username.LastIndexOf("\\")

Won't that just give the last index of the string?

yes, but doing remove(0, LastIndexOf("\\")) will remove all characters from position 0 until the last \. and in this case it seems like the last character before the username will always be \. :)

This should work for the user who posted this question ... i think :P


username.Replace(username.Substring(0,username.LastIndexOf(@."\")+1),"");

Dim userStringAs String ="MAINOFFICE\userName"Dim userNameAs String = userString.SubString(userString.IndexOf("\") + 1)
Just make sure you use your @."\" in C# or "\\"

keyboardcowboy:

bullpit:

keyboardcowboy:

username.LastIndexOf("\\")

Won't that just give the last index of the string?

yes, but doing remove(0, LastIndexOf("\\")) will remove all characters from position 0 until the last \. and in this case it seems like the last character before the username will always be \. :)

This should work for the user who posted this question ... i think :P

yep, it worked like a charm for me.

Thanks


keyboardcowboy-

You are right, but may be I took OP's problem too seriously. He mentioned that he wanted to remove "\" until his last post. Your solution works. I unnecessarily gave a longer method with replace to remove all the characters before "\" in my last post. Ignore all crap that I post.


haha, yeah at first i thought he meant what you were showing to do, but I kinda figured he wanted only the user name.

now he has a handlefull of string altering techniques though :)


thanks guys. I'm sorry for the mess, was my bad.Embarrassed

StringBuilder

can anyone tell me how to declare a stringbuilder using vb in visual studio, I am trying to use a stringbuilder in the following code, but visual studio states stringbuilder is not defined.

Imports System.Data
Imports System.Data.SqlClient
Imports System.Text.StringBuilder

Public Class datagrid2
Inherits System.Web.UI.Page

Public Sub UpdateCommand(ByVal sender As Object, ByVal e As DataGridCommandEventArgs)

Dim sb1 As StringBuilder = New StringBuilder("")
sb1.Append("INSERT Employees (firstname, lastname, titleofcourtesy, title, country) VALUES(")
sb1.Append("@dotnet.itags.org.sFirstName, @dotnet.itags.org.sLastName, @dotnet.itags.org.sTitle, @dotnet.itags.org.sPosition, @dotnet.itags.org.sCountry)")
cmd.CommandText = sb1.ToString()Hi,

Dim sb1 As System.Text.StringBuilder = New System.Text.StringBuilder("")

HTH
Imports System.Text.StringBuilder <-- don't do this, StringBuilder is a class, not a namespace.

use:
Imports System.Text

now you can use "StringBuilder" in your code (instead of having to write the fully qualified version of it each time)
thanks guys

Stringbuilder Class

Could anyone show me the code that allows me reset a Stringbuilder back to
either null or nothing or a blank space?How about this?
sb.Length = 0
I hope this helps,
Steve C. Orr, MCSD, MVP
http://SteveOrr.net
"Paul" <Paul@.discussions.microsoft.com> wrote in message
news:972F577C-0629-4B47-98EA-E403F429BB84@.microsoft.com...
> Could anyone show me the code that allows me reset a Stringbuilder back to
> either null or nothing or a blank space?
Yes, just tested but my comp. is incr. slow at home.
Dim sb As New StringBuilder
sb.Append("Hello")
MsgBox(sb.ToString)
sb.Length = 0
MsgBox(sb.ToString)
"Steve C. Orr [MVP, MCSD]" <Steve@.Orr.net> schreef in bericht
news:OUdAFyd9FHA.2640@.tk2msftngp13.phx.gbl...
> How about this?
> sb.Length = 0
>
> --
> I hope this helps,
> Steve C. Orr, MCSD, MVP
> http://SteveOrr.net
>
> "Paul" <Paul@.discussions.microsoft.com> wrote in message
> news:972F577C-0629-4B47-98EA-E403F429BB84@.microsoft.com...
>
Hi Paul,
It looks like you can set the Length to zero or just use New again.
Here's a little demo:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As
System.EventArgs)
Dim sb As New StringBuilder
sb.Append("!", 50)
sb.Append(": Length is now " & sb.Length.ToString)
Label1.Text = sb.ToString
sb.Length = 0
Label2.Text = "After Length=0:" & sb.ToString
sb = New StringBuilder
End Sub
Ken
Microsoft MVP [ASP.NET]
"Paul" <Paul@.discussions.microsoft.com> wrote in message
news:972F577C-0629-4B47-98EA-E403F429BB84@.microsoft.com...
> Could anyone show me the code that allows me reset a Stringbuilder back to
> either null or nothing or a blank space?
Actually, I tried using New again and that did not seem to work.
Setting the length to 0 did work.
Thank you for your assistance.
"Ken Cox" wrote:

> Hi Paul,
> It looks like you can set the Length to zero or just use New again.
> Here's a little demo:
> Protected Sub Page_Load(ByVal sender As Object, ByVal e As
> System.EventArgs)
> Dim sb As New StringBuilder
> sb.Append("!", 50)
> sb.Append(": Length is now " & sb.Length.ToString)
> Label1.Text = sb.ToString
> sb.Length = 0
> Label2.Text = "After Length=0:" & sb.ToString
> sb = New StringBuilder
> End Sub
> Ken
> Microsoft MVP [ASP.NET]
>
> "Paul" <Paul@.discussions.microsoft.com> wrote in message
> news:972F577C-0629-4B47-98EA-E403F429BB84@.microsoft.com...
>
>

Saturday, March 24, 2012

strip out any html code from textbox

Hi! I am looking for a way to stip out any html code if the user type in some html in the textbox. Thanks!!

If the ValidateRequest is turned on for a page then ASP.Net will automatically detect the HTML in the text box and throw an error.

ValidateRequest can be turned on in the Page directive.


use

yourString= Server.HtmlEncode(Trim(TxtBxManufactureProductID.Text))

or
yourString=HttpUtility.HtmlEncode(TxtBxManufactureProductID.Text)

yourString is a string variable


Use can use HTMLEncode as told previously, else if you want to completely remove HTML then you may user RegEx. <(?<tag>\w*)>(?<text>.*)</\k<tag>> , and replace them with some empty string.

I am not sure of the exact code, but you can replace HTML for sure.

Ankit


Hi! Thank you for the reply, I tried yourString=HttpUtility.HtmlEncode(TxtProfile.Text) and got an error ( a potentially dangerous request...)

And I also tried the one that has Trim,but it says that Trim doesn't exist in the current contest. Do I have to import a namespace for that? Thanks.


Thanks! I get a syntax error on the reguloar expression:

<asp:RegularExpressionValidatorID="RegularExpressionValidator1"runat="server"ControlToValidate="txtBusinessprofile"ValidationExpression="<(?<tag>\w*)>(?<text>.*)</\k<tag>>">Please do not incluse html code!</asp:RegularExpressionValidator>


<%@. Page Language="VB" MasterPageFile="AdminMasterPage.master" AutoEventWireup="false" Inherits="YYY" title="xxxx"ValidateRequest="false" Codebehind="YYY.aspx.vb" %>

you will have a line like above in your axpx file(the fist line)

write the ValidateRequest="false" there

Then also use codes in my previous replay


Do you know how to catch the exception that is thrown when ValidationRequest="true" and user inputs an html? I can see that this exception is fired much before the execution point ever comes the actual page's codebehind. I guess i could not even catch it in Application_Error.....

It will be actually nice to have something like this:

1. keep ValidationRequest="true"

2. Exception is thrown if user enters html or anything inside angular brackets

3. Error is caught at Page error handler and action is taken (display msg etc)

This will save remembering to validate for malicious input (or at least a scripting type of malicious input) in all the forms in all the pages...


Thanks for the tip! I have also read that it's not a good habit to set validaterequest to false cos of the script injection attacks that might arise...I had mine set to false for the page only and I need to make sure that all html code is stripped out of the textbox.

Thursday, March 22, 2012

strong naming assembly

I am attempting trying to create an assembly with strong name
Here is what I have done:
called sn -k Tesstkey.snk
placed this code in my class:
using System.Reflection;
[assembly:AssemblyKeyFileAttribute("TestKey.snk")]
I am getting an error saying it cannot read the key file
First, Where should that .snk file go?
Second, What could cause that error?
DerrickHi,
You can give absolute path also for the .snk file.
I believe VS.NET IDE looks for the .snk file in the devenv.exe folder
itself.
"Derrick" <Derrick_no_spam@.geostrategies.ca> wrote in message
news:9LfOc.137615$ek5.83297@.pd7tw2no...
I am attempting trying to create an assembly with strong name
Here is what I have done:
called sn -k Tesstkey.snk
placed this code in my class:
using System.Reflection;
[assembly:AssemblyKeyFileAttribute("TestKey.snk")]
I am getting an error saying it cannot read the key file
First, Where should that .snk file go?
Second, What could cause that error?
Derrick
Hi Derrick,
As for the making stong-named asembly issue, I think you Shiva's suggestion
that use the full absolutte path of the key file is reasonable. Since
you're using the relative path of the file(haven't specify the full path),
I'm not sure whether the problem is cause by this. Anyway, please have a
try and if you have anyother findings, please also feel free to post here.
Thanks.
Regards,
Steven Cheng
Microsoft Online Support
Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)
Get Preview at ASP.NET whidbey
http://msdn.microsoft.com/asp.net/whidbey/default.aspx
Derrick,
You can use a relative path for this, but it should be relative to the
compiled assembly, not the project file. For example, if you keep the key
file in the project root folder and your assemblies get compiled to <project
root>\bin\debug or <project root>\bin\release, then your relative path must
point up two directories. e.g.:
[assembly: AssemblyKeyFile(@."..\..\TestKey.snk")]
HTH,
Nicole
"Derrick" <Derrick_no_spam@.geostrategies.ca> wrote in message
news:9LfOc.137615$ek5.83297@.pd7tw2no...
>I am attempting trying to create an assembly with strong name
> Here is what I have done:
> called sn -k Tesstkey.snk
> placed this code in my class:
> using System.Reflection;
> [assembly:AssemblyKeyFileAttribute("TestKey.snk")]
> I am getting an error saying it cannot read the key file
> First, Where should that .snk file go?
> Second, What could cause that error?
> Derrick
>
>
>
Thanks for the help.
physical path wouldn't work because I have to move the projects between
machines. I used Nicole's suggestion to use the relative path of
"..\..\file.snk", and that worked. I had the file in the \bin\release\
folder, so that should have worked, but I can work with the relative path
approach.
Derrick
"Steven Cheng[MSFT]" <v-schang@.online.microsoft.com> wrote in message
news:Ic7VahfdEHA.2932@.cpmsftngxa10.phx.gbl...
> Hi Derrick,
> As for the making stong-named asembly issue, I think you Shiva's
suggestion
> that use the full absolutte path of the key file is reasonable. Since
> you're using the relative path of the file(haven't specify the full path),
> I'm not sure whether the problem is cause by this. Anyway, please have a
> try and if you have anyother findings, please also feel free to post here.
> Thanks.
> Regards,
> Steven Cheng
> Microsoft Online Support
> Get Secure! www.microsoft.com/security
> (This posting is provided "AS IS", with no warranties, and confers no
> rights.)
> Get Preview at ASP.NET whidbey
> http://msdn.microsoft.com/asp.net/whidbey/default.aspx
>
Thanks, Nicole
That worked
Derrick
"Nicole Calinoiu" <nicolec@.somewhere.net> wrote in message
news:OJjcaIkdEHA.3704@.TK2MSFTNGP09.phx.gbl...
> Derrick,
> You can use a relative path for this, but it should be relative to the
> compiled assembly, not the project file. For example, if you keep the key
> file in the project root folder and your assemblies get compiled to
<project
> root>\bin\debug or <project root>\bin\release, then your relative path
must
> point up two directories. e.g.:
> [assembly: AssemblyKeyFile(@."..\..\TestKey.snk")]
> HTH,
> Nicole
>
> "Derrick" <Derrick_no_spam@.geostrategies.ca> wrote in message
> news:9LfOc.137615$ek5.83297@.pd7tw2no...
>

strong naming assembly

I am attempting trying to create an assembly with strong name

Here is what I have done:
called sn -k Tesstkey.snk
placed this code in my class:
using System.Reflection;

[assembly:AssemblyKeyFileAttribute("TestKey.snk")]

I am getting an error saying it cannot read the key file

First, Where should that .snk file go?
Second, What could cause that error?

DerrickHi,

You can give absolute path also for the .snk file.

I believe VS.NET IDE looks for the .snk file in the devenv.exe folder
itself.

"Derrick" <Derrick_no_spam@.geostrategies.ca> wrote in message
news:9LfOc.137615$ek5.83297@.pd7tw2no...
I am attempting trying to create an assembly with strong name

Here is what I have done:
called sn -k Tesstkey.snk
placed this code in my class:
using System.Reflection;

[assembly:AssemblyKeyFileAttribute("TestKey.snk")]

I am getting an error saying it cannot read the key file

First, Where should that .snk file go?
Second, What could cause that error?

Derrick
Hi Derrick,

As for the making stong-named asembly issue, I think you Shiva's suggestion
that use the full absolutte path of the key file is reasonable. Since
you're using the relative path of the file(haven't specify the full path),
I'm not sure whether the problem is cause by this. Anyway, please have a
try and if you have anyother findings, please also feel free to post here.
Thanks.

Regards,

Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)

Get Preview at ASP.NET whidbey
http://msdn.microsoft.com/asp.net/whidbey/default.aspx
Derrick,

You can use a relative path for this, but it should be relative to the
compiled assembly, not the project file. For example, if you keep the key
file in the project root folder and your assemblies get compiled to <project
root>\bin\debug or <project root>\bin\release, then your relative path must
point up two directories. e.g.:

[assembly: AssemblyKeyFile(@."..\..\TestKey.snk")]

HTH,
Nicole

"Derrick" <Derrick_no_spam@.geostrategies.ca> wrote in message
news:9LfOc.137615$ek5.83297@.pd7tw2no...
>I am attempting trying to create an assembly with strong name
> Here is what I have done:
> called sn -k Tesstkey.snk
> placed this code in my class:
> using System.Reflection;
> [assembly:AssemblyKeyFileAttribute("TestKey.snk")]
> I am getting an error saying it cannot read the key file
> First, Where should that .snk file go?
> Second, What could cause that error?
> Derrick
>
Thanks for the help.

physical path wouldn't work because I have to move the projects between
machines. I used Nicole's suggestion to use the relative path of
"..\..\file.snk", and that worked. I had the file in the \bin\release\
folder, so that should have worked, but I can work with the relative path
approach.

Derrick

"Steven Cheng[MSFT]" <v-schang@.online.microsoft.com> wrote in message
news:Ic7VahfdEHA.2932@.cpmsftngxa10.phx.gbl...
> Hi Derrick,
> As for the making stong-named asembly issue, I think you Shiva's
suggestion
> that use the full absolutte path of the key file is reasonable. Since
> you're using the relative path of the file(haven't specify the full path),
> I'm not sure whether the problem is cause by this. Anyway, please have a
> try and if you have anyother findings, please also feel free to post here.
> Thanks.
> Regards,
> Steven Cheng
> Microsoft Online Support
> Get Secure! www.microsoft.com/security
> (This posting is provided "AS IS", with no warranties, and confers no
> rights.)
> Get Preview at ASP.NET whidbey
> http://msdn.microsoft.com/asp.net/whidbey/default.aspx
Thanks, Nicole

That worked

Derrick
"Nicole Calinoiu" <nicolec@.somewhere.net> wrote in message
news:OJjcaIkdEHA.3704@.TK2MSFTNGP09.phx.gbl...
> Derrick,
> You can use a relative path for this, but it should be relative to the
> compiled assembly, not the project file. For example, if you keep the key
> file in the project root folder and your assemblies get compiled to
<project
> root>\bin\debug or <project root>\bin\release, then your relative path
must
> point up two directories. e.g.:
> [assembly: AssemblyKeyFile(@."..\..\TestKey.snk")]
> HTH,
> Nicole
>
> "Derrick" <Derrick_no_spam@.geostrategies.ca> wrote in message
> news:9LfOc.137615$ek5.83297@.pd7tw2no...
> >I am attempting trying to create an assembly with strong name
> > Here is what I have done:
> > called sn -k Tesstkey.snk
> > placed this code in my class:
> > using System.Reflection;
> > [assembly:AssemblyKeyFileAttribute("TestKey.snk")]
> > I am getting an error saying it cannot read the key file
> > First, Where should that .snk file go?
> > Second, What could cause that error?
> > Derrick

Strongly Type Web Forms

How does a User Control invoke a method on its parent page? Say I have a publicMethod in code behind for an aspx page:
...
public void SomeImportantMethod() { /* do important stuff */}
...
From an Event Handler within the User Control, I'd like to invoke a method on the page in which the User Control is embedded. If I stop in the debugger and inspect this.Page, I see that it has a type of "ASP.MyAspxPage"... where did that come from? Can I delcare it intentionally somewhere?
TIA,
Geo
Your MyAspxPage is your custom page class, which inherits from the System.Web.UI.Page class.
The thing with UserControls is though, that you don't know what parent page they could be in at run-time.
So, to be safe, if you want to call a particular method on the parentPage, I'd say let your Page implement your interface which contains themethod signature (and other stuff if you want).
In your UserControl you then do a defensive cast (using the as keyword)to that interface and check for != null. You then simply call yourmethod on your interface object.
Hope that helps.
Wim

Yes, that does help. It helped in that I was hung up in anold paradigm and should get over it and just use an interface. So, thanks, that helped me get the job done.
I guess I was stuck in theOLD ASP.NET 1.1 code behind days where an ASPX page would have a code behind page which had a namespace declaration and the web form would be a public class derived from System.Web.UI.Page. So, from any C# code I could say:
MyNamespace.MyPage myPage = this.Page as MyNameSpace.MyPage;
if ( myPage != null)
{
myPage.MyMethod("hello world");
}
else
{
Response.Write("what gives?");
}
No fuss no muss, no interfaces.
I think I better go find an article or 2 on code beside or what ever it is we call it now.
Thanks again,
geo

Hello.

I think that you can also use the @.reference directive to introduce the type of the page in the user control (haven't tried it though).

Structures, character arrays, and unmanaged code in C#

I'm not entirely sure how to ask this question because, frankly, I have no idea what I'm dealing with. I have a C header file that would allow me to access an API. The header needs to be converted to .NET so I can use the API. I converted and tested the methods successfully (using DllImport). I'm running into a problem converting, well using, a structure:
struct record {
char id[32];
char name[64];
char number[16];
char dept[64];
... you get the idea ...
};

My searches have brought me to the conclusion that I'm working with something called "unmanaged code", which I gather means the CLR won't be touching my API. I converted the struct to something that I think is equivalent:

[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi)]
public struct pager_record
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string id;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 64)] public string name;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)] public string number;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 64)] public string dept;
... you get the idea ...
};

When I try to pass the structure into my API call, I get an "Object Reference not set to an instance of an object" error. This is the code I use to initialize and populate the struct:


private void btnAdd_Click(object sender, System.EventArgs e)
{
StringBuilder error = new StringBuilder(Export.ERROR_BUFFER_SIZE);
Admin.record pr = new Admin.record();

pr.id = "123456789";
pr.name = "George Bush";
pr.number = "5555555555";
pr.dept = "Executive";
... you get the picture ...

This is the line that fails:


int Stat = Admin.pagemate_add(pr, error);

And this is the API method itself:
[DllImport(API.dll)]
public static extern int add(record Record, StringBuilder error_buffer);

I know that I'm populating the struct fine; if I change the struct to a managed equivalent (without the [MarshalAs(��) ] code, data makes it into program. It's just that the data that gets in is gibberish. I'm guessing this has something to do with references, since .NET passes data ByVal by default.

So the questions:
1.Is this how I want to rewrite the Struct?
a.Why?
2.What do I need to do to pass the structure into the API call?
a.Why?

Thanks��

-ChrisChris,

Unmanaged simply means that the CLR won't do type-checking and garbage collection for your non .Net library.

What level of indirection does your unmanged method require? This may affect how you can pass the struct into the API. If you need one level of indirection you can pass the struct in using the ref keyword. No indierction, you can use standard byval. Two levels, you are out of luck. See this MSDN article for more information on supported indirection levels.

Also, I think the attribute you need on your struct members is [FieldOffset] vs [MarshallAs].

What you are really dealing with here is called Platform Invoke, or P-Invoke.

Hope this helps.

-kristopher
Kristopher,

Thanks. I'm not sure but I think I require one level of indirection. Here's the original method definition:

extern long int add(struct record *, char *);

Changing to [FieldOffset] and passing the struct byref allows the code to execute again. Interesting results. I call the API through a button.click event. The first time I press the button (or call the API) it tells me the record ID is empty or null, and the insert fails. If I click a second time it will addsomething, but not what I put in the fields. A third call fails the same way the first does, a fourth tries to add (but fails because the record already exists), etc.

-Chris
Interesting. Have you verified that what is being passed to the API is the same as what you entered (i.e. by using the debugger)? Also, check to make sure that your offsets are correct, otherwise its possible you're stepping on other struct members (aka a C union).

-k

Tuesday, March 13, 2012

stuck in a loop

Hi

I try to use this piece of code, but the page seems to get stuck in the loop. What am I doing wrong here?

Function NumberOfLinesInFile()
Dim path As String = Server.MapPath("row.txt")
Dim sr As StreamReader = New StreamReader(path)
Dim i As Integer
i = 0
Do While sr.Peek() >= 0
i = i + 1
Loop
sr.Close()
Return i
End Function

Regards

Mhello, what if sr.Peek() is always >= 0 ? check the values returned by sr !!!
The Peek function does not move to the next character, it only consumes it. Try using the sr.Read() instead.

hope this helps,

sivilian