“A from e-mail address must be specified in the From property or the system.net/mailSettings/smtp config section.”
If you haven’t already, create a new system.web section in the web.config file like this:
<system.net>
<mailSettings>
<smtp from="yourmail@yourcompany.com">
<network
host="smtp.yourcompany.com"
userName="yourmail@yourcompany.com"
password="xxxx" />
</smtp>
</mailSettings>
</system.net>
They key being the extra from="yourmail@yourcompany.com". This problem is usually encountered when you’re trying to use the new Login controls available in ASP.NET 2.0. More info here such as what to do if you don’t want to have the system create a new password and email.
Array
Dim charArray() As String = New String() {"?", ":", "*", """", "<", ">"}
ASP Configuration/Security –
Local –
Run C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727>aspnet_regsql, making sure to supply YOURLOCALSVRNAME\SQLEXPRESS for the server name make sure to add that “SQLEXPRESS” at the end
make sure you have something like this in web.config:
<configuration>
<appSettings/>
<connectionStrings>
<remove name="LocalSqlServer"/> this may or may not be all that important
<add name="LocalSqlServer"
connectionString=
"Server=YOURLOCALSVRNAME\SQLEXPRESS;Integrated Security=True;Database=aspnetdb" the key, again, being to add that SQLEXPRESS at the end
providerName="System.Data.SqlClient"/>
</connectionStrings>
…
Remote – if things works great in our little development environment but bombs out on most any production web site. Use code at Microsoft ASP.NET 2.0 Member/Role Management with IIS, Part 2: Implementation instead.
asp:Label, change font – you can’t do this directly in HTML. Let’s say you have
<span style="font-weight:bold">
<asp:Label ID="LblYourLabel" runat="server" Font-Bold="True"
Font-Underline="True" Text="Your label: "></asp:Label>
</span>
It’s showing up as 10 and you decide you want the font bigger. Like, say, 18. So you change it to be like this:
<span style="font-weight:bold; font-size:18pt;">
<asp:Label ID="LblYourLabel" runat="server" Font-Bold="True"
Font-Underline="True" Text=" Your label: "></asp:Label>
</span>
But when you run it, no change? Huh? How to fix? You must add this to your form’s underlying .vb code file:
Protected Sub LabelFont18_Init(sender As Object, e As EventArgs)
LblYourLabel.Font.Size = 18
End Sub
And change your code above to add OnInit="LabelFont18_Init":
<span style="font-weight:bold">
<asp:Label ID="LblYourLabel" runat="server" Font-Bold="True"
Font-Underline="True" Text=" Your label: " OnInit="LabelFont18_Init"></asp:Label>
</span>
To actually invoke the dang thing. Note that you can then invoke this same Sub from other label objects. But, of course, you’ll have to specifically state which labels you’re applying the new font to in your code.
aspnet_regsql - C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727>aspnet_regsql
if you get “SQL Server 2005 SQLExpress error: ...provider: Named Pipes Provider, error 40 - Could not open connection to SQL Server”, then make sure that you specifiy the instance name as well as the server name (lord knows why, but when MS refer to "Server Name" they really mean "Server Instance Name") eg if your server was named 'bob' then you need to specify ''bob\sqlexpress' (where sqlexpress is the instance name - this one just happens to be the default used by SQL Server 2005 SQLExpress).
Attribute ‘align’ is considered dated. A newer construct is recommended. Use: <p style="text-align: center"> instead. See Validation (XHTML 1.0 Transitional): A newer construct is recommended
Attribute ‘bgcolor’ is considered dated. A newer construct is recommended. Use: <p style="background: #0000ff"> instead. See Validation (XHTML 1.0 Transitional): A newer construct is recommended
Error:<authentication mode="Windows" /> - Control Panel/Administrative Tools/Internet Information Services/Right click the directory/Properties/Directory(default) tab/Application name/Add
AutoPostBack="True", setting this on a control causes the focus to jump back to the top of the page – see scroll, maintain position
Authorize.net, code to use
Partial Class YourWebPage
Inherits System.Web.UI.Page
'Public events
Event TransactionSuccess(ByVal sAuthCode As String, ByVal TransactionID As String)
Event TransactionFailed(ByVal sErrorDesc As String)
Private Function readHtmlPage(ByVal url As String) As [String]
'Public Sub AuthorizePayment(
Dim result As [String] = ""
Dim AuthNetVersion As String = "3.1"
Dim AuthNetLoginID = "xxxxx"
Dim AuthNetPassword = ""
Dim AuthNetTransKey = "xxxxxxxxx"
Dim objRequest As New System.Net.WebClient
Dim objInf As New System.Collections.Specialized.NameValueCollection(30)
Dim objRetInf As New System.Collections.Specialized.NameValueCollection(30)
Dim objRetBytes As Byte()
Dim objRetVals As String()
Dim strError As String = ""
objInf.Add("x_version", AuthNetVersion)
objInf.Add("x_delim_data", "True")
objInf.Add("x_login", AuthNetLoginID)
'objInf.Add("x_password", AuthNetPassword)
objInf.Add("x_tran_key", AuthNetTransKey)
objInf.Add("x_relay_response", "False")
' Switch this to False once you go live
objInf.Add("x_test_request", "True")
objInf.Add("x_delim_char", ",")
objInf.Add("x_encap_char", "|")
' Card Details
objInf.Add("x_card_num", txtCCno.Text)
objInf.Add("x_exp_date", txtCCexp.Text)
objInf.Add("x_method", "CC")
objInf.Add("x_type", "AUTH_CAPTURE")
objInf.Add("x_amount", txtAmount.Text) 'Amount.ToString())
' Currency setting. Check the guide for other supported currencies
objInf.Add("x_currency_code", "USD")
Try
'Test/Live server
objRequest.BaseAddress = url
'objRequest.BaseAddress = "https://certification.authorize.net/gateway/transact.dll"
'objRequest.BaseAddress = "https://secure.authorize.net/gateway/transact.dll"
objRetBytes = objRequest.UploadValues(objRequest.BaseAddress, "POST", objInf)
objRetVals = System.Text.Encoding.ASCII.GetString(objRetBytes).Split(",".ToCharArray())
If 0 = 1 Then 'objRetVals(0).Trim(Char.Parse("|")) = "1" Then
'Return the authorization code
RaiseEvent TransactionSuccess(objRetVals(4).Trim(Char.Parse("|")), objRetVals(6).Trim(Char.Parse("|")))
Else
RaiseEvent TransactionFailed(strError)
End If
strError = objRetVals(3).Trim(Char.Parse("|")) & " (" & objRetVals(2).Trim(Char.Parse("|")) + ")"
lblResponse.Text = objRetVals(0).Trim(Char.Parse("|")) & "," & _
objRetVals(1).Trim(Char.Parse("|")) & "," & _
objRetVals(2).Trim(Char.Parse("|"))
errLabel.Text = strError
Catch ex As Exception
End Try
Return result
End Function
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
readHtmlPage("https://test.authorize.net/gateway/transact.dll")
'Uncomment the line ABOVE for shopping cart testing OR uncomment the line BELOW for live accounts
'readHtmlPage("https://secure.authorize.net/gateway/transact.dll")
End Sub
End Class
blue wavy lines under components in the YourName.aspx.vb and say they aren’t registered even though components are there in the YourName.aspx file – I’ve seen this happen when moving from a “project” to a “web site”. You need to make sure to include Inherits="YourName" in the top line of the .aspx right after the CodeFile=" YourName.aspx.vb". Then, in the .aspx.vb file you need Partial Class YourName. Instead of Public or Private Class. Seems this never works right if I just substitute the name “Partial” for “Public”. I usually end up making a whole new YourNameNew.aspx and YourNameNew.aspx.vb files and then putting the old code in the YourNameNew.aspx.vb, but keeping the new file’s “Partial”.
browser default, set
1. Right click on a .aspx page in your solution explorer
2. Select the "browse with" context menu option
3. In the dialog you can select or add a browser. If you want Firefox in the list, click "add" and point to the firefox.exe filename
4. Click the "Set as Default" button to make this the default browser when you run any page on the site.
C# to vb.net online translator
close the a form you’re in and open another one -
Response.Redirect("Default.aspx")
code location, inline or split out as a separate file – when first creating a form, choose to put code in separate file
combo box – see drop-down list
components have blue wavy lines under them in the YourName.aspx.vb and say they aren’t registered even though components are there in the YourName.aspx file – see blue wavy lines under components in the YourName.aspx.vb even though components are there in the YourName.aspx file
connection string “LocalSqlServer” only thing available at GoDaddy ‘cause that’s hard-coded in GoDaddy’s machine.config file but you can’t get to it at the remote GoDaddy connection and you already have a “LocalSqlServer” on your local machine – see GoDaddy machine.config, can’t add anything but the “LocalSqlServer” connection string ‘cause that’s hard-coded in GoDaddy’s machine.config file but you can’t get to it at the remote GoDaddy connection and you already have a “LocalSqlServer” on your local machine
Could not load type (Parser Error Message: Could not load type) - This error occurs when you create a new web application in asp.net using visual studio.net and without compiling the application, you try to browse a page in the application. This occurs because of the Application DLL not having been formed. asp.net will look in the Global Assembly Cache, and then in the application’s local bin directory. If it can’t find the class with the name you specified then it won’t load. When you do a codebehind file in Visual studio, you are writing a base class for your aspx file to inherit from – the HTML template you write in the aspx is inlined into the dynamically generated subclass’s Render method. Even if you don’t put any code in your page, you still need to compile it as long as you put the Inherts Global in your Page directive. To resolve this, build the application using Ctrl + Shift + B or use F5 to build the application and then try to browse the application. The error will be resolved.
Could not find schema information for the element 'http://schemas.microsoft.com/.NetConfiguration/v2.0:system.configuration' –
The warnings are caused by a line in web.config:
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
Remove the xmlns part so it is:
<configuration>
The warnings will not show up. The "xmlns" part is added when you use Web Site Administration Tool.
CreateUserWizard control, after user create
Protected Sub CreateUserWizard1_CreatedUser(ByVal sender As Object, ByVal e As System.EventArgs) Handles CreateUserWizard1.CreatedUser
Dim UserID As String
Dim body As String
Const cr As String = "<br>" 'Chr(13) & Chr(10)
Const beginDiff As String = "<b>"
Const endDiff As String = "</b>"
Const beginSection As String = "<div align=""center""> <span bgcolor=""#ffff88"" style=""color: #0000ff"">"
Const endSection As String = "</span> </div>"
'Build up variables
'Biggest one to build: the body of the email
body = beginSection & "User info:" & endSection & cr
UserID = CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("UserName"), TextBox).Text
body = body & "email/user ID: " & beginDiff & UserID & endDiff & cr
'(1) Create the MailMessage instance
'Dim mm As New MailMessage()
Dim mail As New Net.Mail.MailMessage()
mail.From = New Net.Mail.MailAddress("xx@yourcompany.com", "Bob Smith")
mail.CC.Add("xx@yourcompany.com ")
'(2) Assign the MailMessage's properties
mail.Subject = "New user id created on our site"
mail.Body = body
mail.IsBodyHtml = True
'(3) Create the SmtpClient object
Dim smtp As New Net.Mail.SmtpClient
'(4) Send the MailMessage to Barb, et al (will use the Web.config settings)
smtp.Send(mail)
End Sub
CreateUserWizard control, continue button
Protected Sub CreateUserWizard1_ContinueButtonClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles CreateUserWizard1.ContinueButtonClick
Response.Redirect("Default.aspx")
End Sub
CreateUserWizard control, customize - here
email, not require - CreateUserWizard1.RequireEmail = False
email, not even display – shouldn’t need to have to do anything special other than the CreateUserWizard1.RequireEmail = False above. But you could also start with the code and delete the email row
CreateUserWizard NullReferenceException – if you have code like:
x = CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Company"), TextBox).Text
and you get a NullReferenceException, then try a simple
x = Contact.Text
Some variables – like "UserName" – you do seem to need to reference the indirect way above.
Credit card processing – see Authorize.net, code
CustomValidator – a few things to keep in mind, especially in how it differs from the other validators such as RequiredFieldValidator and CompareValidator
1. Anything you write on a page's code file (its .aspx.vb file) is, by default, server side. The little rules in other such as RequiredFieldValidator and CompareValidator you don't have to put into that page and so are automatically client-side. This means that any code you might have on the submit button that would not have been executed until all the validators have been satisfied probably will execute in this case. You need to explicitly write your client side JavaScript code to check your validation on the client to prevent that submit button code from being prematurely executed.
2. Even after you've explicitly written your CustomValidator JavaScript client code, unlike the other validators such as RequiredFieldValidator and CompareValidator, your submit button code will execute unless you enclose it in an
If Page.IsValid Then
End If
"if" statement – even if your CustomValidator test fails and you flag the return key to fail! Normally, for those other validators you don't have to check the Page.IsValid flag to prevent that submit button's code from executing on failure. Even more annoying, it seems as though once so little as one CustomValidator's custom code is executed, it wipes out any other failure flags set by your other validators and that submit button's code will be executed unless the Page.IsValid is checked. Very annoying and not what you'd expect.
database, can’t log into – perhaps you’re running Visual Web Developer as an administrator. Perhaps because you had to move your project from your “My Documents \Documents\Visual Studio 2010\WebSites\YourProject” directory to “C:\inetpub\wwwroot\YourProject” in order to include your includes. But, it seems you can’t run projects located there unless you run Visual Web Developer as an administrator. And when you do that, you aren’t running as your normal domain\user ID. Now you’re running as your local PC’s ID. Good luck trying to log into your production server now! You can’t add PCs as approved users in SQL Server; only IDs and groups. So you point your Web.config database connection to point to a local copy on your PC. But now you get, “login failed for user 'iis apppool defaultapppool'” Argh! Now what? Go into IIS, ConnectionStrings, Application Pools, DefaultAppPool and change its Identity from “ApplicationPoolIdentity” to “LocalSystem”.
date, format – When displaying a date column in a gridview, it is often the case that you only need to display the date and not the time. This is simple enough, just include a DataFormatString attribute in your BoundField declaration. Easy huh?
<asp:BoundField HeaderText="Last Review" DataField="LastReviewDate" DataFormatString="{0:MM/dd/yyyy}" />
Let's see the results:
10/11/2006 2:07:35 PM
11/1/2005 1:52:11 PM
5/28/2005 12:28:01 PM
Wha???? For the DataFormatString to correctly display, you have to include an HtmlEncode="false" attribute in your column declaration as well. So your code should look something like this:
<asp:BoundField HeaderText="Last Review" DataField="LastReviewDate" DataFormatString="{0:MM/dd/yyyy}" HtmlEncode="false" />
And the world is a better place:
10/11/2006
11/1/2005
5/28/2005
After a little research, the reasoning became clear. By default, the GridView control encodes HTML before rendering it. This is to prevent cross-site scripting attacks in the event that the grid tries to load unsafe scripts from a data source. Since we are just displaying dates here, it is safe to assume that we don't need to HtmlEncode the data before rendering. This is simple enough to fix, just not entirely obvious.
date picker – download basic date picker and use the BDPLite control. Me.SeminarDate1.IsNull to test for null and Me.SeminarDate1.SelectedDate to retrieve value
debug.print - Response.Write(message)
directory, create – see how to create a directory
directory info –
Request.PhysicalApplicationPath – the path you’re in – with the “C:” and a bunch of backslashes (“\”)
Request.PhysicalPath – the path and file you’re in – with the “C:” and a bunch of backslashes (“\”)
Request.Path – the top-most directory down from the web root you’re in – with regular slashes (“/”)
Request.ApplicationPath – the whole directory – including the actual file name you’re in – down from the web root you’re in – with regular slashes (“/”)
Directory, restrict – put this in web.config. Note that this tag does not go under the <system.web> tag, which applies to the website as a whole.
<location path="Projects">
<system.web>
<authorization>
<allow users="*" /> - allow all users, including authenticated and anonymous users
<deny users="?" /> - prevent all Non-Authenticated, or Anonymous, users
</authorization>
</system.web>
</location>
.dll, don’t make – create a “New Web Site”, not a “New Project”
download files – see ASP.NET File Uploading
drop-down list
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="CategoryID" HeaderText="CategoryID" />
<asp:BoundField DataField="CategoryName" HeaderText="Category Name" />
<asp:TemplateField HeaderText="Products">
<ItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
'DropDownList1' has a SelectedValue which is invalid because it does not exist in the list of items. Parameter name: value
Need to add an AppendDataBoundItems="true" and Value = ""
<asp:DropDownList
DataTextField="ProofFileName"
DataValueField="ProofFileName"
ID="DropDownList1"
Runat="server"
SelectedValue='<%# Bind("ProofFileName") %>'
AppendDataBoundItems="true">
<asp:ListItem Value = "">CA</asp:ListItem>
<asp:ListItem>VT</asp:ListItem>
<asp:ListItem>UT</asp:ListItem>
<asp:ListItem>MD</asp:ListItem>
</asp:DropDownList>
email, not require in the CreateUserWizard - CreateUserWizard1.RequireEmail = False
email, send – “Sending Email” article. Start by putting in this above <system.web> in web.config
<system.net>
<mailSettings>
<smtp>
<network
host="smtp.lisco.com" />
<!-- port="portNumber"
userName="username"
password="password"
-->
</smtp>
</mailSettings>
</system.net>
<system.web>
at the very top of your form’s code:
Imports System.Net.Mail
put this in your button:
Protected Sub SendEmail_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles SendEmail.Click
'!!! UPDATE THIS VALUE TO YOUR EMAIL ADDRESS
Const ToAddress As String = "youraddr@yourdomain.com"
'(1) Create the MailMessage instance
Dim mm As New MailMessage(UsersEmail.Text, ToAddress)
'(2) Assign the MailMessage's properties
mm.Subject = Subject.Text
mm.Body = Body.Text
mm.IsBodyHtml = False
'(3) Create the SmtpClient object
Dim smtp As New SmtpClient
'(4) Send the MailMessage (will use the Web.config settings)
smtp.Send(mm)
End Sub
And you should get an email
Failed to update database: "APP_DATA\ASPNETDB.MDF" is read-only on host site – need to go to the C:\Inetpub\wwwroot\App_Data directory and add the user “ASPNET” as an ID with full permissions to that directory. Some places say you need to mess with SSEU, but I didn’t have to. Just adding that user worked. Interestingly, adding “everyone” with full permissions didn’t.
file, write with XML
Protected Sub WriteXML(ByVal AttachmentFile As String)
Try
Dim enc As Encoding
'Create file, overwrite if exists
'enc is encoding object required by constructor
'It is null, so default encoding is used
Dim objXMLTW As New XmlTextWriter(Server.MapPath(AttachmentFile), enc)
With objXMLTW
.Formatting = Formatting.Indented
.WriteStartDocument()
'Top level (Parent element)
.WriteStartElement("WebApplication")
.WriteComment("Add Person XML")
.WriteStartElement("Person") 'Begin Person
'.WriteAttributeString("id", 1)
.WriteStartElement("FirstName")
.WriteString(Request("FirstName"))
.WriteEndElement()
.WriteStartElement("LastName")
.WriteString(Request("LastName"))
.WriteEndElement()
.WriteStartElement("Phone")
.WriteString(Request("PhoneNumber"))
.WriteEndElement()
.WriteStartElement("email")
.WriteString(Request("CustomerEmail"))
.WriteEndElement()
.WriteEndElement() 'End Person
.WriteEndElement() 'End WebApplication
.WriteEndDocument() 'End Document
.Flush() 'Write to file
.Close()
End With
Catch Ex As Exception
'lblXMLFile.Text = "The following error occurred: " & Ex.Message
End Try
End Sub
font for an asp:Label, change – see asp:Label, change font
form – close one and open another
Response.Redirect("Default.aspx")
framework, change – Start by going to the project “Property Pages”. How to get to that? In the Solution Explorer, highlight the main (1st) heading for the project itself. Since any stuff that happens from here on is context sensitive, it’s important that you have the project itself highlighted instead of any one of the pages or whatnot below it highlighted. Once it’s highlighted, you can do 1 of 4 things:
· right click on it. Down at the bottom of the pop-up list is “Property Pages”.
· click the “Properties” button which is the 1st icon in the upper left of the Solution Explorer, right under where it says “Solution Explorer”
· hit “Alt-Enter”
· hit “Shift-F4”
Once you’re there, go to “Build” and then you can change your Target Framework using a pick list.
GoDaddy machine.config, can’t add anything but the “LocalSqlServer” connection string ‘cause that’s hard-coded in GoDaddy’s machine.config file but you can’t get to it at the remote GoDaddy connection and you already have a “LocalSqlServer” on your local machine. Solution: got to first remove “LocalSqlServer” in your local config.web before adding it again! So, in your local “config.web” file:
<connectionStrings>
<remove name="LocalSqlServer"/>
<add name="LocalSqlServer" connectionString="Data Source=NILE;Initial Catalog=SC;Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
But in your remote “config.web” file
<connectionStrings>
<clear />
<add
name="LocalSqlServer"
connectionString=
"Data Source=whsql-v20.prod.mesa1.secureserver.net;
Initial Catalog=yourdbname;
User ID=yourID; Password='YourPwd'"
/>
</connectionStrings>
GoDaddy write problems
1. Try making a separate web.config override file for one directory per here:
<? xml version="1.0"?>
<configuration>
<appSettings/>
<connectionStrings/>
<system.web>
<identity impersonate="true" userName="HOSTING\myUserName" password="myPassword"/>
</system.web>
</configuration>
But this didn’t seem to work so well. Even replacing “HOSTING” with “GDHOSTING” didn’t work.
1. need to add the AutoGenerateEditButton="True" to the GridView, as below. Also, good idea to add DataKeyNames="YourTableID":
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
AutoGenerateEditButton="True" DataKeyNames="YourTableID"
DataSourceID="SqlDataSource1" AllowPaging="True" AllowSorting="True">
<Columns>
<asp:BoundField DataField="WhenAdded" HeaderText="When Added"
SortExpression="WhenAdded" />
<asp:BoundField DataField="Description" HeaderText="Description"
SortExpression="Description" />
<asp:BoundField DataField="Name" HeaderText="Name"
SortExpression="Name" />
</Columns>
</asp:GridView>
2. need to add the UpdateCommand and UpdateParameters to the SqlDataSource, as below:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:YourConnectionString %>"
SelectCommand="SELECT WhenAdded, Description, Name
FROM [YourTable]" UpdateCommand="update YourTable
set Description = @Description, Name = @Name
where YourTableID = @YourTableID ">
<UpdateParameters>
<asp:Parameter Name="Description" />
<asp:Parameter Name="Name" />
<asp:Parameter Name="YourTableID" />
</UpdateParameters>
</asp:SqlDataSource>
The former (add the AutoGenerateEditButton="True") seems you need to add manually; the latter (add the UpdateCommand and UpdateParameters to the SqlDataSource) can be done more easily in design view interface via the “Configure Data Source” link under the “Grid View Tasks” menu that appears when you click the arrow to the right of the grid view. You “Specify a custom SQL statement or stored procedure” in the second step and type in
update YourTable
set Description = @Description, Name = @Name
where YourTableID = @YourTableID
In the “UPDATE” tab in the 3rd step
Note that you need to display YourTableID field as a column in the grid view for the update to work if you don’t specify DataKeyNames="YourTableID".
gridview, empty elements show up as “ ”
One site suggested: Click your gridview from the design view and select the little white arrow to bring up a menu and select edit columns
Select the field you don't want to say “ ” and change these values:
ConvertEmptyString > true
HtmlEncode > false
HtmlEncodeFormatString >false
Didn’t work worth squat! But Server.HtmlDecode(e.Cell.Text) seemed to work just great.
Me.CompanyInfo.Rows.Item(0).Cells(5).Text
Or
Me.CompanyInfo.Rows(0).Cells(5).Text
gridview, select a row
If CompanyInfo.SelectedIndex = -1 Then ' no row was selected - just get the 1st row
pdfFormFields.SetField("Address", Server.HtmlDecode(CompanyInfo.Rows(0).Cells(2).Text))
Else ' a row was selected
pdfFormFields.SetField("Address", Server.HtmlDecode(CompanyInfo.SelectedRow.Cells(2).Text))
End If
Hash table – here for an example
Dim Restaur1 As Hashtable = New Hashtable
Restaur1.Add("Name", Me.RestaurantName1.Text)
Restaur1.Add("Address", Me.RestaurantAddress1.Text)
There’s also HashSet
' String array.
Dim a As String() = {"cat", "dog", "cat", "leopard", "tiger", "cat"}
Console.WriteLine(String.Join(" ", a))
' Create HashSet.
Dim hash As HashSet(Of String) = New HashSet(Of String)(a)
' String array.
a = hash.ToArray()
Console.WriteLine(String.Join(" ", a))
ids and passwords – Website/ASP Configuration/Security works great in our little development environment but bombs out on most any production web site. Use code at Microsoft ASP.NET 2.0 Member/Role Management with IIS, Part 2: Implementation instead.
illegal characters, remove – adapted from here:
Function clean(ByVal strToClean As String)
'Remove illegal characters ?:*"<>
Dim charArray() As String = New String() {"?", ":", "*", """", "<", ">"}
Dim arraySize As Integer = UBound(charArray) 'get the size of the character array
Dim tmpstr As String = strToClean 'store string in temporary variable
Dim cont As Boolean = True 'repeat string check for current character
Dim current As Integer = 0 'store current array index
Dim charAt As Integer
Dim leftPart, rightPart As String
'Loop through illegal character array until all illegal chars removed from string
While cont
charAt = InStr(tmpstr, charArray(current))
If (charAt > 0) Then
leftPart = Left(tmpstr, charAt - 1)
rightPart = Mid(tmpstr, charAt + 1, Len(tmpstr))
If charArray(current) = ":" Then
tmpstr = leftPart & "-" & rightPart
Else
tmpstr = leftPart & "" & rightPart
End If
Else 'Character not found in string
If current < arraySize Then
current = current + 1 'Increment
Else
cont = False 'get out of the loop
End If
End If
End While
clean = tmpstr 'Return the cleaned string
End Function
includes, can’t find – you can’t use the default of “file system” when creating a “New Web Site” if you want to use includes. You need to use “HTTP”. And that means you have to put these under the C:\Inet\wwwroot. And when you do that, you have to always start as an administrator. And, you have to refer to your includes with “~/”, not “../”. Argh! But don’t be changing any of your references to your .jpgs to “~/images/…”. Uh-uh. Got to keep those as “../images/…”
“"Inherits" can appear only once within a Class statement and can only specify one class.” – put an “imports” statement before the “inherits” statement:
Imports System.IO
Partial Class Upload
Inherits System.Web.UI.Page
label, assign database field to – assuming you already have asp:SqlDataSource ID="SqlDataSource1" in the main aspx page and that the SQL therein returns just one row, one of whose columns is “Description”:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim dv As System.Data.DataView = SqlDataSource1.Select(System.Web.UI.DataSourceSelectArguments.Empty)
Dim dr As System.Data.DataRow = dv.Table.Rows(0)
LabelTestimonial.Text = Convert.ToString(dr("Description"))
End Sub
“LocalSqlServer” connection string ‘cause that’s hard-coded in GoDaddy’s machine.config file but you can’t get to it at the remote GoDaddy connection and you already have a “LocalSqlServer” on your local machine – see GoDaddy machine.config, can’t add anything but the “LocalSqlServer” connection string ‘cause that’s hard-coded in GoDaddy’s machine.config file but you can’t get to it at the remote GoDaddy connection and you already have a “LocalSqlServer” on your local machine
login, customize – see CreateUserWizard control, customize
logging in – Website/ASP Configuration/Security works great in our little development environment but bombs out on most any production web site. Use code at >Microsoft ASP.NET 2.0 Member/Role Management with IIS, Part 2: Implementation instead.
MAC failed, Validation of viewstate – see Validation of viewstate MAC failed
machine.config for GoDaddy, can’t add anything but the “LocalSqlServer” connection string ‘cause that’s hard-coded in GoDaddy’s machine.config file but you can’t get to it at the remote GoDaddy connection and you already have a “LocalSqlServer” on your local machine – see GoDaddy machine.config, can’t add anything but the “LocalSqlServer” connection string ‘cause that’s hard-coded in GoDaddy’s machine.config file but you can’t get to it at the remote GoDaddy connection and you already have a “LocalSqlServer” on your local machine
mail attachments
Dim AttachmentFile As String
AttachmentFile = "file.xml"
Dim mail As New MailMessage()
Dim ThisAttachment As New Attachment(Server.MapPath(AttachmentFile)) 'create the attachment
mail.Attachments.Add(ThisAttachment)
mail recipients, specify multiple – from systemnetmail.com:
Imports System.Net.Mail
Protected Sub MultipleRecipients()
'create the mail message
Dim mail As New MailMessage()
'set the addresses
'to specify a friendly 'from' name, we use a different ctor
mail.From = New MailAddress("me@mycompany.com", "Steve James")
'since the To,Cc, and Bcc accept addresses, we can use the same technique as the From address
'since the To, Cc, and Bcc properties are collections, to add multiple addreses, we simply call .Add(...) multple times
mail.To.Add("you@yourcompany.com")
mail.To.Add("you2@yourcompany.com")
mail.CC.Add("cc1@yourcompany.com")
mail.CC.Add("cc2@yourcompany.com")
mail.Bcc.Add("blindcc1@yourcompany.com")
mail.Bcc.Add("blindcc2@yourcompany.com")
'set the content
mail.Subject = "This is an email"
mail.Body = "this is the body content of the email."
'send the message
Dim smtp As New SmtpClient("127.0.0.1")
smtp.Send(mail)
End Sub 'MultipleRecipients
membership – Website/ASP Configuration/Security works great in our little development environment but bombs out on most any production web site. Use code at Microsoft ASP.NET 2.0 Member/Role Management with IIS, Part 2: Implementation instead.
“Namespace or type specified in the project-level Imports '<whatever>' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the alias name doesn't contain other aliases.”
Add a reference by either going to “Add a reference” under “Project” or “References” folder in the “Solution Explorer” window (normally off to the right).
navigate from one form to another
Response.Redirect("Default.aspx")
or
Server.Transfer("Default.aspx ")
“ ” shows up when reading empty elements from gridview – see gridview, empty elements show up as “ ”
null, check to see if a value is null – IsDBNull
null, check to see if a radio button is null – you can NOT check the “SelectedItem” property (Go ahead, try) but you can check the “SelectedIndex” property!
If Me.MailListSource.SelectedIndex <> -1 Then
Choice = Me.MailListSource.SelectedItem.Value
Else
Choice = True
End If
NullReferenceException using the CreateUserWizard– see CreateUserWizard NullReferenceException
open a form and close the one you’re in
Response.Redirect("Default.aspx")
Password for ASP.Net 2.0 Membership, reset –
The first thing to note is that you must know the working password of another account on your site. For this example I know the password of my "admin" account for DotNetNuke, you can use any account in your system that you know the password for. Once you have identified the user account, run the following query to obtain the needed user information. You will need to know the username and application name for the specific user account. In my example below the username is admin and the applicaton name is DotNetNuke.
SELECT password, passwordformat, passwordsalt
FROM aspnet_membership am
INNER JOIN aspnet_users au
ON (au.userid = am.userid)
INNER JOIN aspnet_applications aa
ON (au.applicationId = aa.applicationid)
WHERE au.username = 'admin'
AND aa.applicationname = 'DotNetNuke'
You will want to copy the results of this query to your clipboard as you will need this information for the next step of the process. Next we will be using the ASP.NET stored procedure "aspnet_Membership_setPassword" to set the password value for our user. Whne calling this stored procedure we must pass the following values to it. ApplicationName, Username, Password, PasswordSalt, ChangeTime, passwordFormat. Below is an example, you will simply need to substitute your values.
--Prepare the change date
DECLARE @changeDate datetime
set @changeDate = getdate()
--set the password
exec aspnet_Membership_setPassword 'DotNetNuke',
'TestUser',
'DM1tZvBjM+27Eck5eI1TWFeG42XuJnMuin3jqFOtMjS83RN6d7dFbQ==',
'4e5Bb5jOOMYu/JFXVdRmlA==',
@changeDate,
2
--Sets the password to dnnadmin
After running this script you should now be able to login with the newly set password. A few things to remember about this method. First to guarantee that this will work correctly the known user account information must be taken from the same application as the machine and validation keys change the encryption methods used for setting the passwords.
Or
Dim mp As MembershipProvider = Membership.Providers("AspNetAdminMembership")
Dim user As MembershipUser = mp.GetUser(ddlUsers.SelectedItem.ToString, False)
Dim pass As String = user.ResetPassword
password strength, don’t require 8 characters and one special character – modify web.config per here:
<system.web>
<membership>
<providers>
<clear/>
<add name="AspNetSqlMembershipProvider"
type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
connectionStringName="LocalSqlServer"
enablePasswordRetrieval="false" - must be “false” if passwordFormat="Hashed" below
enablePasswordReset="true"
requiresQuestionAndAnswer="true"
requiresUniqueEmail="false"
passwordFormat="Hashed"
maxInvalidPasswordAttempts="5"
minRequiredPasswordLength="4"
minRequiredNonalphanumericCharacters="0"
passwordAttemptWindow="10"
passwordStrengthRegularExpression=""
applicationName="/" - although having nothing to do with password strength, it’s good to specify this
/>
</providers>
</membership>
…
</system.web>
passwords and ids – Website/ASP Configuration/Security works great in our little development environment but bombs out on most any production web site. Use code at Microsoft ASP.NET 2.0 Member/Role Management with IIS, Part 2: Implementation instead.
quote - To include the double quote character within a string, add in two of them, as in this example:
Dim strString as String
String = "This will ""embed"" a double quote character within this string."
radio button list, handle empty values – check .SelectedIndex for not equaling -1
If Me.WhereTextComesFrom.SelectedIndex <> -1 Then
body = body & "Where Text Comes From: " & beginDiff & _
Me.WhereTextComesFrom.SelectedItem.Value & endDiff & cr
Else
body = body & "Where Text Comes From: not specified" & cr
End If
referring URL - x
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim Referrer As String
If Not Request.UrlReferrer Is Nothing Then
Referrer = Request.UrlReferrer.AbsolutePath.ToString
Response.Write(Referrer & " path only <br>") ' only the path after the domain
Referrer = Request.UrlReferrer.ToString
Response.Write(Referrer & " whole thing <br>") ' domain (with "http//:") + path
Referrer = Request.UrlReferrer.Host.ToString()
Response.Write(Referrer & " domain only <br>") ' only the domain (no "http//:")
Else
Response.Write("No one referred us here")
End If
End Sub
scroll, maintain position - if you set a control to AutoPostBack="True", then it automatically hops back to the begining of the page. This annoys the end user. The best solution I’ve found so far is to simply add MaintainScrollPositionOnPostback="true" at the top of the page so it looks something like
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="SCApplication.aspx.vb"
Inherits="SCApplication" enableViewStateMac="False" MaintainScrollPositionOnPostback="true" %>
SmartNavigation seems to be obsolete and that only ever worked in IE. Another would be to create a Custom Server Control such as here. I couldn’t get this to work so I just stuck with MaintainScrollPositionOnPostback="true"
special characters, remove – see illegal characters, remove
“System.Web.HttpException: Maximum request length exceeded” when uploading – see uploading, “System.Web.HttpException: Maximum request length exceeded”
Updating is not supported by data source 'SqlDataSource1' unless UpdateCommand is specified – When you configure your datasource, choose "Advanced". On the Advanced page, check "Generate Insert,Update and Delete commands". This will generate attributes in your sqldatasource that allow for these things to happen. When done, should look something like this:
ProviderName="System.Data.SqlClient" UpdateCommand="update YourTable
set IntegerValue =@IntegerValue, DateValue = @DateValue
where name = @Name">
<UpdateParameters>
<asp:Parameter Name="IntegerValue" />
<asp:Parameter Name="DateValue" />
<asp:Parameter Name="Name" />
</UpdateParameters>
Make sure you have a primary key in your table set. Then, later on to execute, set your parameters
SqlDataSource1.UpdateParameters("Name").DefaultValue = "YourRowName"
SqlDataSource1.UpdateParameters("IntegerValue").DefaultValue = 1
SqlDataSource1.UpdateParameters("DateValue").DefaultValue = Date.Now
SqlDataSource1.Update()
upload files –
ASP.NET File Uploading – also shows how to download. This does it manually building HTML rows, not a DataGrid
How to upload a file to a Web server in ASP.NET by using Visual Basic .NET
Also, use in conjunction with Displaying the Files in a Directory using a DataGrid. But to accomplish the download you must also modify DataNavigateUrlFormatString as shown here
uploading, “System.Web.HttpException: Maximum request length exceeded” – change web.config just for the directory you care about:
<?xml version="1.0"?>
<configuration>
<system.web>
<httpRuntime maxRequestLength="8192" />
</system.web>
</configuration>
user, current - User.Identity.Name
Validation of viewstate MAC failed – quick fix or more involved discussion. One quick fix is, for the page in question, to modify its top line to read:
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="YourApp.aspx.vb"
Inherits="YourApp" enableViewStateMac="False"%>
Website/ASP Configuration/Security works great in our little development environment but bombs out on most any production web site. Use code at Microsoft ASP.NET 2.0 Member/Role Management with IIS, Part 2: Implementation instead.
XML read/write sample