This per this:
catch (EndOfStreamException end)
{
throw (e);
}
catch (NullReferenceException nullRef)
{
throw (nullRef);
}
This per this:
catch (EndOfStreamException end)
{
throw (e);
}
catch (NullReferenceException nullRef)
{
throw (nullRef);
}
Something interesting is to come, but first, look at this:
using System;
namespace ParameterlessConstructorExample.Models
{
public class Animal
{
public Int32 numberOfMouths { get; set; }
public Animal()
{
numberOfMouths = 1;
}
}
}
Now for something interesting: If Bird inheirts from Animal, then newing up a Bird will cause the parameterless constructor on Animal to be called.
using System;
namespace ParameterlessConstructorExample.Models
{
public class Bird : Animal
{
public Int32 numberOfLegs { get; set; }
public Bird()
{
numberOfLegs = 2;
}
}
}
ViewBag.Whatever below will end up with the number one in it.
using System.Web.Mvc;
using ParameterlessConstructorExample.Models;
namespace ParameterlessConstructorExample.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
Bird bird = new Bird();
ViewBag.Whatever = bird.numberOfMouths;
return View();
}
}
}
This comes from chapter 18 of C# in a Nutshell. I tried to find a way to set numberOfLegs in Animal and have the Animal setting sabotage the Bird's setting, but fortunately there isn't an easy way to "accidentally" do this. I found this which made me smile. The first bullet of the Conclusion is: "C# is not Java."
This points out that you may change the port for an IIS web site at the "Bindings..." link which should appear at the right nav in IIS7 when you select a site at the left nav. When I try to switch to port 443 from 80 I am told: "This Web site cannot be started. Another Web site may be using the same port." I navigated to C:\Windows\system32> at the command prompt and typed netstat -a to get a list of ports being used. I found 443 set to a state of LISTENING in two line items of the results returned.
Addendum 4/10/2013: A lot of this posting is really bad. See: this
Trilogy complete! |
Keira Knightley as Sabina Spielrein gives an excellent performance in David Cronenberg's film "A Dangerous Method" and yes, I think it the very best Cronenberg film, and I've seen every single one except for Spider, including the overrated Scanners. Naturally, Sabina Spielrein finding herself really doesn't have anything at all to do with finding yourself in C#...
string nameOfTheComputer = System.Net.Dns.GetHostName();
string localIp =
System.Net.Dns.GetHostByName(nameOfTheComputer).AddressList[0].ToString();
string publicIpv4 = Request.ServerVariables["REMOTE_ADDR"];
string publicIpv6 =
System.Net.Dns.GetHostEntry(nameOfTheComputer).AddressList[0].ToString();
string url = Request.Url.ToString();
string nameOfCurrentPage = Request.ServerVariables["SCRIPT_NAME"];
string localeInFileTree =
Server.MapPath(System.IO.Path.GetFileName(nameOfCurrentPage));
Maybe VB script is more suitable, as it feels like it is eighty years old and thus from Sabrina's era...
Dim nameOfTheComputer As String = System.Net.Dns.GetHostName()
Dim localIp As String =
System.Net.Dns.GetHostByName(nameOfTheComputer).AddressList(0).ToString()
Dim publicIpv4 As String = Request.ServerVariables("REMOTE_ADDR")
Dim publicIpv6 As String =
System.Net.Dns.GetHostEntry(nameOfTheComputer).AddressList(0).ToString()
Dim url As String = Request.Url.ToString()
Dim nameOfCurrentPage As String = Request.ServerVariables("SCRIPT_NAME")
Dim localeInFileTree As String =
Server.MapPath(System.IO.Path.GetFileName(nameOfCurrentPage))
Nah. The truth is, this is really bad analogy and I just like goofing off with Tumblr. So, what am I struggling to say?
Well, the stuff above will help you "find yourself." The variables are largely going to end up with stuff in them that corresponds appropriately to their names. One exception is that either the publicIpv4 or publicIpv6 variable is going to be botched in the code above, but I'll get to that in a minute. Other things to mention are:
Alright, the only thing really new about this posting in contrast to the other two is the IP stuff. First remember that a local IP starts with...
publicIpv6 will end up with the same string as localIp (not literally the same... I do understand the heap and reference types) if there is not an IPv6 IP address to be had, which are those new freaky things that look like fe80::4869:3aca:f1b9:d214%10 for example. (The world is running out of the traditional IPv4 IP addresses the same way it is running out of tungsten. Those left not on the list above are public IP addresses.) So what will publicIpv4 look like?
It is likely going to look like ::1 if there is an IPv6 address and legitimate otherwise. Note that "legitimate" may include 127.0.0.1 which is not technically a private IP address. This means, that in order to really use the code above, one needs to do an equality comparison between publicIpv6 and localIp to see if either publicIpv4 or publicIpv6 holds the value for the public IP address. If publicIpv6 and localIp do match then publicIpv4 holds the public IP address while the absence of a match means that publicIpv6 holds the public IP address.
Do you every feel lost and just wish you could ping the cave walls like a bat? I found a way to sniff the url line yesterday. Awake last night, I realized that if you split a url on the slash and take the third item in the collection that you will have your hands on the subdomain standalone.
public static string GetSecureSubDomainWithoutTrailingSlash()
{
string fullUrl = HttpContext.Current.Request.Url.ToString();
return "https://" + fullUrl.Split('/')[2];
}
This posting may serve as a companion piece for this which shows off how to find where one is at in a file structure. Also, here is the VB Script way to do the thing I did above in C#:
Imports Microsoft.VisualBasic
Public Class LocationProvider
Public Shared Function GetSecureSubDomainWithoutTrailingSlash() As String
Dim fullUrl As String = HttpContext.Current.Request.Url.ToString()
Dim revisedUrl As String = "https://" + Split(fullUrl, "/")(2)
Return revisedUrl
End Function
End Class
Call things static-style in VB script like so:
Label1.Text = LocationProvider.GetSecureSubDomainWithoutTrailingSlash()
...is gonna give you something like: http://localhost:35155/About.aspx
ConfigurationManager.ConnectionStrings("foo").ConnectionString
Per this a hacky way to autosort a view is:
SELECT TOP 99 PERCENT Whatever FROM SomethingErOther
ORDER BY Whatever
This posting isn't something to worry about. Instead just use the command line to force a shutdown:
shutdown /r /t timeout_in_seconds
give a number for "timeout_in_seconds" (duh)
http://www.stata.com/support/faqs/windows/64-bit-compliance/ has a pretty good cheat sheet for determining if a given PC is of a 64-bit shape. In Windows 7 go to: Start > Control Panel > System and Security > System ...and then find the line item for "System type"
SELECT TOP 1 @ValueToReturn = HorseName FROM Horses
...is how it is done in lieu of...SELECT TOP 1 HorseName FROM Horses
This is an older blog posting I wrote on output parameters for stored procedures.
Public Shared Function IsRouteParametersSane(ByVal dataSet As DataSet, url As
String) As Boolean
If InStr(url, "?") = 0 Then
Return True
End If
Dim secondHalfOfUrl As String
secondHalfOfUrl = Split(url, "?")(1)
Dim routeParametersAndTheirVariables As New ArrayList()
If InStr(secondHalfOfUrl, "&") = 0 Then
routeParametersAndTheirVariables.Add(secondHalfOfUrl)
Else
Dim routeParametersAndTheirVariablesAsArray = Split(secondHalfOfUrl, "&")
routeParametersAndTheirVariables = New
ArrayList(routeParametersAndTheirVariablesAsArray)
End If
Dim routeParameters As New ArrayList()
Dim routeParameterAndValue As String
For Each routeParameterAndValue In routeParametersAndTheirVariables
If InStr(routeParameterAndValue, "=") = 0 Then
routeParameters.Add(routeParameterAndValue)
Else
routeParameters.Add(Split(routeParameterAndValue, "=")(0))
End If
Next
Dim routeParameter As String
For Each routeParameter In routeParameters
Dim isFailure As Boolean = True
For Each Row As DataRow In dataSet.Tables(0).Rows
If Row(2) = "Route Parameter" Then
If Row(1).ToLower() = routeParameter.ToLower() Then
isFailure = False
End If
End If
Next
If isFailure = True Then
Return False
End If
Next
Return True
End Function
Addendum 1/4/2017: list-style: none; and not list-type-style: none; gets rid of bullets. I hope you weren't pulling your hair out over this. ;)
Null dereferences are not so much security holes as they are of performance problems. If one attempts to use a pointer that points at null as though it points to legitimate content on the heap it may "invariably result in the failure of the process" per https://www.owasp.org/index.php/Null-pointer_dereference
Today I learned about D3.js which is a JavaScript project for "Data-Driven Documents" at what will hopefully be the first of many Far North Austin geek lunches. D3.js allows for all sorts of creative charts, maps, tree views, reports, etc. Some of them can work with div tags and some of them work with SVG (Scalable Vector Graphics, an XML markup for Flashesque vector content without the overhead of the third-party plugin).
Refactoring the work I begun here I have learned that if one wants to have n number of controls for each record out of a database such as, for example...
...that when creating web forms controls dynamically it is tricky to associate the n controls. I got around this by creating a new Panel for each set of three as seen here:
foreach (KeyValuePair<int,string> keyValuePair in subdomains)
{
TextBox textBox = new TextBox();
textBox.Attributes.Add("style", "float: left; width: 350px; margin-top: 4px;");
textBox.Text = keyValuePair.Value;
CheckBox checkBox = new CheckBox();
checkBox.Attributes.Add("style", "float: left; margin: 6px 0px 0px 10px;");
HiddenField hiddenField = new HiddenField();
hiddenField.Value = keyValuePair.Key.ToString();
Panel innerPanel = new Panel();
innerPanel.Controls.Add(checkBox);
innerPanel.Controls.Add(textBox);
innerPanel.Controls.Add(hiddenField);
LeftPanel.Controls.Add(innerPanel);
}
I then get a collection of panels back when its time to analyze stuff in the controls. From any one item in the collection, it isn't too tough to associate its three children together.
List<Panel> panels = new List<Panel>();
foreach (Panel panel in LeftPanel.Controls) panels.Add(panel);
foreach (Panel panel in panels)
{
List<Control> controls = new List<Control>();
foreach (Control control in panel.Controls) controls.Add(control);
Tuple<bool, string, int> changeSet = new Tuple<bool, string, int>(((CheckBox)
controls[0]).Checked, ((TextBox) controls[1]).Text,
Convert.ToInt32(((HiddenField)controls[2]).Value));
}
private void UseAddStoredProcedure(string newEntry)
{
try
{
using (SqlConnection sqlConnection = new SqlConnection(AddConnectionString()))
{
using (SqlCommand sqlCommand = new SqlCommand())
{
sqlCommand.CommandText = addStoredProcedure;
sqlCommand.Parameters.Add("@Item", SqlDbType.VarChar).Value = newEntry;
sqlCommand.CommandType = CommandType.StoredProcedure;
sqlCommand.Connection = sqlConnection;
sqlConnection.Open();
sqlCommand.ExecuteNonQuery();
}
}
}
catch
{
throw new System.ApplicationException(addStoredProcedure + " failed");
}
}
if (ViewState["AddOrAlter"] != null)
{
if (ViewState["AddOrAlter"] as string == "add")
{
string whatever = "somethingerother";
}
}
Compare an instance to a type!
TOOLS > Options... > Text Editor > All Languages > General ...is where one turns on and off showing line numbers for code in Visual Studio 2012.
I just did it for the first time. You are going to have to have some controls (think Panel) to put the code-created controls in. Here is a web form that will work:
<%@ Page Language="C#" AutoEventWireup="true"
CodeBehind="WhitelistForReroutingAdministration.aspx.cs"
Inherits="ResponseRedirectWhitelisting.WhitelistForReroutingAdministration" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Whitelist For Rerouting Administration</title>
</head>
<body>
<form id="form1" runat="server">
<div style="margin:0 auto; width: 800px;">
<div style="float:left; width: 400px;">
<asp:Panel runat="server" ID="LeftPanel"></asp:Panel>
</div>
<div style="float:right; width: 400px;">
<asp:Panel runat="server" ID="RightPanel"></asp:Panel>
</div>
<div style="clear:both; height:20px;"></div>
</div>
</form>
</body>
</html>
Here is the magic in the code behind. (not too tough really)
using System;
using System.Web.UI.WebControls;
namespace ResponseRedirectWhitelisting
{
public partial class WhitelistForReroutingAdministration : System.Web.UI.Page
{
protected void Page_Init(object sender, EventArgs e)
{
int counter = 0;
while (counter < 10)
{
counter++;
TextBox textBox = new TextBox();
textBox.Attributes.Add("style", "float: left; width: 370px; margin-top: 4px;");
textBox.Text = counter.ToString();
LeftPanel.Controls.Add(textBox);
}
while (counter < 13)
{
counter++;
TextBox textBox = new TextBox();
textBox.Attributes.Add("style", "float: right; width: 370px; margin-top: 4px;");
textBox.Text = counter.ToString();
RightPanel.Controls.Add(textBox);
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
}
}
Adding onto this, one configures a route in RouteConfig as show here, and again, this is Mr. Sullivan's code.
routes.MapConnection<ChatConnection>("chat", "chat/{*operation}");
He (Brian Sullivan) made a view which looks like so:
<div id="chatArea"></div>
<div>
<input type="text" id="chatText" />
<button id="sendButton">Send</button>
</div>
@section scripts
{
<script type="text/javascript" src="~/Scripts/jquery.signalR-1.0.0-rc1.js"></script>
<script type="text/javascript">
$(function () {
var conn = $.connection("/chat");
$("#sendButton").click(function () {
conn.Send($("#chatText").val());
$("#chatText").val("");
});
conn.received(function (data) {
$("#chatArea").append("<div>" + data + "</div>");
}
conn.start().done(function() {
if (conn.eventSource) {
conn.eventSource.addEventListener('message', function(event) {
console.log("EventSource message: " + event.data);
});
}
});
});
</script>
}
conn.Send($("#chatText").val()); above is going to send the contents of the chatText input field to a ChatConnection object as defined below. From there, am I not sure how the magic happens, but every browser listening via SignalR is going to get updated by SignalR! My notes have the ChatConnection object looking like so. I can't remember if the speaker added other lines to this object or not. Maybe all of the voodoo is in the view above and the C# object just empowers it, you know?
namespace SignalRChat
{
using Microsoft.AspNet.SignalR;
public class ChatConnection : PersistentConnection
{
protected override System.Threading.Tasks.Task OnReceivedAsync(IRequest
request, string connectionId, string data)
{
return base.OnReceivedAsync(request, connectionId, data);
}
}
}
The second parameter in Substring in C# denotes the distance from first parameter (the place in the string to start collecting characters) to stop collecting characters and not the locale in the string to stop collecting characters. I am midway into writing some code and I will eventually do more with urlAfterDoubleSlashes than what is given below as what is given below, partially finished, is goofy. I really need the -7 and -8 below as without out it there is drama.
private static bool IsCompleteUrl(string redirect)
{
string urlAfterDoubleSlashes = null;
if (redirect.ToLower().Substring(0, 7) == "http://")
{
urlAfterDoubleSlashes = redirect.Substring(7, redirect.Length-7);
}
if (redirect.ToLower().Substring(0, 8) == "https://")
{
urlAfterDoubleSlashes = redirect.Substring(8, redirect.Length-8);
}
if (urlAfterDoubleSlashes == null) return false;
return true;
}
The drama I refer to is a System.ArgumentOutOfRangeException with a message of "Index and length must refer to a location within the string." and this code will get you that drama:
private static bool IsCompleteUrl(string redirect)
{
string urlAfterDoubleSlashes = null;
if (redirect.ToLower().Substring(0, 7) == "http://")
{
urlAfterDoubleSlashes = redirect.Substring(7, redirect.Length);
}
if (redirect.ToLower().Substring(0, 8) == "https://")
{
urlAfterDoubleSlashes = redirect.Substring(8, redirect.Length);
}
if (urlAfterDoubleSlashes == null) return false;
return true;
}
Mr. Sullivan's talk on SignalR was very informative and it showed off a lot of how-to. For example one pulls SignalR out of NuGet like so:
install-package Microsoft.AspNet.SignalR -pre
Other things I learned included that WebSockets requires either Windows8 or WindowsServer2012 in tandem with both IIS8 and ASP.NET 4.5 and that with Forever Frame, the browser holding the iFrame is tricked into believing that the page within the iFrame never finishes loading so that the page within the iFrame may consistently load new scripts as part of "loading a page." Bigger yet, there is a new version of ASP.NET coming down the pipe to us soon, this per Brian Sullivan last night, and it will have SignalR already baked into it. Microsoft has an all-chips-in investment. Such is prudent, the equivalent power of SignalR already exists in Node.js. The trick is getting IIS to play catchup. There are two varieties of web-based SignalR APIs. The one I've seen before is called the persistence parsing API and it basically allows one to talk string variables back and forth to a server as part of what Scott Hanselman referred to a real-time updates. The other seemed to allow one to fire off C# code upon the click of the button or another act which could then ultimately fire off events back in jQuery! The second variety was called Hubs. To allow for Hubs to work, one has to install the Nuget package and put this in the RouteConfig:
routes.MapHubs();
I did not come out of the training with a comprehensive understanding of Hubs, but some of the C# code which would ultimately allow for reaching back to JavaScript looked as seen below. Please make note of inheritance from Hub and the call to .cardCreate(card); as cardCreate is a JavaScript method!
using System;
namespace SignalRKanban.Hubs
{
using Microsoft.AspNet.SignalR.Hubs;
using SignalRKanban.Models;
public class KanbanHub : Hub
{
public void CreateCard()
{
var id = Guid.NewGuid();
var card = new Card { Content = "", Lane = "1", ID = id };
clients.All.cardCreate(card);
}
}
}
The jQuery side of things looks like so:
$(function () {
var kanbanHub = $.connection.kanbanHub;
KanbanBoard.prototype.createCard = function() {
kanbanHub.server.createCard();
}
var vm = new KanbanBoard();
ko.applyBindings(vm);
kanbanHub.client.cardCreated = function (card) {
vm.addNewCardToLane(card.ID, card.Content, card.Lane);
}
$.connection.hub.start();
});
A script tag needs to call out to ~/Scripts/jquery.signalR-1.0.0-rc1.mis.js and a second script tag will need to call out to ~/signalr/hubs for this to work in a view. Note that this whole thing assumes MVC4 and ASP.NET Web API.
News is breaking now about Mr. Swartz's death. Honestly, I did not know who he was until this moment, but I have used his XML template/convention in the past certainly. It's growing antiquated, but was once the new hotness. Aaron Swartz seems to have died... badly. I am glad he got some recognition. I wish the following inventors recognition while I am thinking of it:
Quest's Toad apparently allows one to optimize SQL for Oracle. One can ping a server with the tool and the tool will try to rewrite existing, specified SQL in different ways while gauging the roundtrip speed of each implemenation and eventually picking a winner. Quest has a comparable tool for MSSQL (I think). SSMS Tools is something else I heard of today. It allows you to do other things that you cannot do with SSMS (SQL Server Management Studio) standalone such as save your query history.
OK, I want to put Sabrina Spielrein's two favorite hobbies in a paragraph on an ASP.NET web form. The copy will mostly come from a text file in the same folder as the ASP.NET web form. I used the word mostly because the hobbies themselves will be injected into the paragraph which will have a sentance in it like so: "Sabrina's favorite hobbies are {1} and {2}, in no particular order." allowing for a String.Format approach to injecting the values for the hobbies which will be driven from the web form's C# code behind which looks like this:
using System;
public partial class SomeFolder_Modern : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
TemplateParser templateParser = new TemplateParser();
Label1.Text = templateParser.CraftCopy("suicide", "interplanetary travel",
Server.MapPath(System.IO.Path.GetFileName(Request.ServerVariables
["SCRIPT_NAME"])));
}
}
The copy above in black gets the file path to the filename handed to it and the copy in white within black gets the name of the web form itself (Modern.aspx). The real work is done from the TemplateParser class which looks like this:
using System;
using System.IO;
public class TemplateParser
{
public string CraftCopy(string firstHobby, string secondHobby, string location)
{
string templateLocation = "";
string[] pathParts = location.Split(Path.DirectorySeparatorChar);
int counter = 0;
foreach (string pathPart in pathParts)
{
counter++;
if (counter < (pathParts.Length))
{
templateLocation = templateLocation + pathPart + Path.DirectorySeparatorChar;
}
}
templateLocation = templateLocation + "HobbyTemplate.txt";
using (var stream = new StreamReader(templateLocation))
{
return String.Format(stream.ReadLine(), firstHobby, secondHobby);
}
}
}
Alright, in the copy above, before the using statement, we are basically taking the file path to Modern.aspx and trimming off "Modern.aspx" and replacing it with "HobbyTemplate.txt" which I mentioned sits in the same folder. Our cleaned up file path ends up in the templateLocation variable and allows us to create a StreamReader connection. The copy above in black will read the first line out of the file. As it is tied to the return statement (and yes, you can nest the return inside a using statement) it will be the only line read. That means that if there is a second line in the text file reading "Sabrina also likes being punished." that such a line will not make its way back to the web form's label.
The practial application of the read-one-line-but-not-the-other-thing is to use the first line of the text document as a content template and the second line for a note. A better note might denote who the author was or what the purpose of the text file was. I wrote some C# vaguely of this shape at work today as an excerise as I had to really write the code in VB script and I wanted to know how to do the same thing in C#. I know you probably don't care about the VB stuff, but here it is:
Partial Class SomeFolder_Whatever
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Handles Me.Load
Dim templateParser As TemplateParser
Label1.Text = templateParser.CraftCopy("suicide", "interplanetary travel",
Server.MapPath(System.IO.Path.GetFileName(Request.ServerVariables
("SCRIPT_NAME"))))
End Sub
End Class
In this version, TemplateParser is very different:
Imports System.IO
Imports Microsoft.VisualBasic
Public Class TemplateParser
Public Shared Function CraftCopy(ByVal firstHobby As String, ByVal secondHobby
As String, ByVal location As String) As String
Dim templateLocation = ""
Dim pathParts() As String = location.Split(Path.DirectorySeparatorChar)
Dim counter As Int32 = 0
For Each pathPart In pathParts
counter = counter + 1
If counter < (pathParts.Length) Then
templateLocation = templateLocation + pathPart + Path.DirectorySeparatorChar
End If
Next
templateLocation = templateLocation + "HobbyTemplate.txt"
Dim stream = CreateObject("ADODB.Stream")
stream.Open()
stream.CharSet = "UTF-8"
stream.LoadFromFile(templateLocation)
Dim linesOfCopy As Object
linesOfCopy = Split(stream.ReadText, vbCrLf)
stream.Close()
stream = Nothing
Return String.Format(linesOfCopy(0), firstHobby, secondHobby)
End Function
End Class
Above, I had to call out UTF-8 or the copy that came back from the template would be preceded by three strange characters. vbCrLf seems to allow for splitting at line breaks.
This is a VB script class:
Imports Microsoft.VisualBasic
Public Class EmailTemplateParser
Public Shared Function ConfigureEktronGroups(ByVal
identity As String, ByVal secret As String) As String
Return identity + secret
End Function
End Class
I can populate a web forms label using the class like so:
Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object,
ByVal e As System.EventArgs) Handles Me.Load
Dim emailTemplateParser As EmailTemplateParser
Label1.Text = emailTemplateParser.
ConfigureEktronGroups("hello", "world")
End Sub
End Class
This offers the following list:
I noticed that Fiddler did not want to spy on localhost and I found this this online as possible fix, but I couldn't get it to work. (I used port 443 for an https port, which I think is the right port to use. I dunno. I somehow screwed this up.) But, rather than face this challenge, I just worked around it using HttpWatch which is comparable to Fiddler. Note:
You cannot do this!
private static DataSet PopulateDataSetFromStoredProcedure(string connectionString)
{
DataSet dataSet = new DataSet();
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand())
{
command.CommandText = "dbo.Whatever";
command.CommandType = CommandType.StoredProcedure;
command = AddParametersToSqlCommand(command);
command.Connection = connection;
using (SqlDataAdapter adapter = new SqlDataAdapter())
{
adapter.SelectCommand = command;
adapter.Fill(dataSet);
}
}
}
return dataSet;
}
private static SqlCommand AddParametersToSqlCommand(SqlCommand sqlCommand)
{
sqlCommand.Parameters.AddWithValue("@Foo", "my");
sqlCommand.Parameters.AddWithValue("@Bar", "dog");
sqlCommand.Parameters.AddWithValue("@Baz", "has");
sqlCommand.Parameters.AddWithValue("@Qux", "fleas");
return sqlCommand;
}
The variable in black above will cause this error:
Readonly variable cannot be used as an assignment target
This is one way you might try to hack around the problem, but this won't work either.
private static DataSet PopulateDataSetFromStoredProcedure(string connectionString)
{
DataSet dataSet = new DataSet();
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand())
{
command.CommandText = "dbo.Whatever";
command.CommandType = CommandType.StoredProcedure;
bool refHackWorks = AddParametersToSqlCommand(command);
command.Connection = connection;
using (SqlDataAdapter adapter = new SqlDataAdapter())
{
adapter.SelectCommand = command;
adapter.Fill(dataSet);
}
}
}
return dataSet;
}
private static bool AddParametersToSqlCommand(ref SqlCommand sqlCommand)
{
sqlCommand.Parameters.AddWithValue("@Foo", "my");
sqlCommand.Parameters.AddWithValue("@Bar", "dog");
sqlCommand.Parameters.AddWithValue("@Baz", "has");
sqlCommand.Parameters.AddWithValue("@Qux", "fleas");
return true;
}
The variable in black above will cause this error:
Arguement is 'value' while parameter is declared as 'ref'
The soultion is to create a new using "loop" inside of the existing one like so:
private static DataSet PopulateDataSetFromStoredProcedure(string connectionString)
{
DataSet dataSet = new DataSet();
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand dumbCommand = new SqlCommand())
{
dumbCommand.CommandText = "dbo.Whatever";
dumbCommand.CommandType = CommandType.StoredProcedure;
using (SqlCommand parameterizedCommand =
AddParametersToSqlCommand(dumbCommand))
{
parameterizedCommand.Connection = connection;
using (SqlDataAdapter adapter = new SqlDataAdapter())
{
adapter.SelectCommand = parameterizedCommand;
adapter.Fill(dataSet);
}
}
}
}
return dataSet;
}
private static SqlCommand AddParametersToSqlCommand(SqlCommand sqlCommand)
{
sqlCommand.Parameters.AddWithValue("@Foo", "my");
sqlCommand.Parameters.AddWithValue("@Bar", "dog");
sqlCommand.Parameters.AddWithValue("@Baz", "has");
sqlCommand.Parameters.AddWithValue("@Qux", "fleas");
return sqlCommand;
}
http://logview4net.com/ is a way to tail database tables and watch what rows are being asserted into them.
I thought of Robert C. Martin's words as I had retyped them here from his Clean Code treatise...
The ideal number of arguments for a function is zero (niladic). Next comes one (monadic), followed closely by two (dyadic). Three arguments (triadic) should be avoided where possible. More than three (polyadic) requires very special justification - and then shouldn't be used anyway.
...as I was abstracting a method in a web form's code behind out to a standalone class. The method which took no parameters at its signature now needs to be handed the string values kept in numerous web form controls. At first I started writing a method with twenty string variables in the signature as I've seen this sort of thing elsewhere in a sister codebase. I then thought of Uncle Bob's words and considered handing in a string array instead. This would introduce an encoding however and just be more confusing. The thing to do here is to roll a DTO (data transfer object). I should populate the DTO before calling the method and then just hand the method the DTO which will be the only thing in the method's signature.
This and this has a good article on how to beat this error when running a web site in Visual Studio via IIS:
ASP.NET 4.0 has not been registered on the Web server. You need to manually configure your Web server for ASP.NET 4.0 in order for your site to run correctly, Press F1 for more details.
The last line of C# code here will cause an error:
Cat cat = new Cat();
Lynx lynx = new Lynx();
Cat attemptedUpcast = (Cat) lynx;
Lynx attemptedDowncast = (Lynx) cat;
But none of the following lines of VB Script are problematic:
Partial Class VBform
Inherits System.Web.UI.Page
Dim snake As Snake
Dim viper As Viper
Dim attemptedUpcasting As Snake = CType(viper, Snake)
Dim attemptedDowncasting As Viper = DirectCast(snake, Viper)
End Class