It might sound kiddish or silly but i wanna know that in codes like..
SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
rdr.Read();
Response.Write(rdr[1]. ToString());
how do we use the SqlDataReader object as an array (rdr[1]) without declaration?
What I want to know is, what is happening in the following line?
Response.Write(rdr[1].ToString());
Since rdr is an object, how art we able to use square brackets with that?
You are looking for Indexers.
Please refer to this link.
Indexers are a syntactic convenience
that enable you to create a class,
struct, or interface that client
applications can access just as an
array
ref: http://msdn.microsoft.com/en-us/library/2549tw02.aspx
you can do something like this.
Object[] values = new Object[reader.FieldCount];
int fieldCount = reader.GetValues(values);
Console.WriteLine("reader.GetValues retrieved {0} columns.",
fieldCount);
for (int i = 0; i < fieldCount; i++)
Console.WriteLine(values[i]);
Console.WriteLine();
No, since SqlDataReader is a forward-only read-only stream of rows from a SQL Server database, the stream of rows will be looped through whether explicitly in your code or hidden in a framework implementation (such as DataTable's Load method). So you cannot directly convert it to array type. You need to convert it to list.
It sounds like using a generic list and then returning the list as an array would be a good option. For example,
List list = new List();
while (rdr.Read())
{
list.Add(rdr.GetInt32(0));
}
return list.ToArray();
Related
I've been building this project as the solo dev for a while, and while I'm comfortable in the front end and middle tier, I don't really think I'm doing the database the way I should be, and the reason why is because I simply don't really know of any other way. The way I'm currently getting data is by testing out queries in my MySQL workbench and copying and pasting the SQL as a string literal into a method that makes a call to the DB, pulls the data and hydrates my objects.
This hasn't really been a problem until recently, when I had to create a monster of a query and it got me thinking that maybe there's a better way to do this. I don't have a formal DAL separated out, so I know there's room for improvement there, but I was curious about what the correct way would be to store SQL strings. I assume there is a tool somewhere built into VS10 where I can manipulate and work with SQL as SQL instead of as a string.
You should be doing this in stored procedures. That will basically format and store your query. You set parameters that are passed in from your code, then read out the results.
Example:
The C# method:
private void SetNote()
{
const string sql = "sp_SelectControllerNoteByID";
using (var conn = MocSystem.GetMocDbConnection())
{
using (var comm = new SqlCommand(sql, conn))
{
comm.CommandType = CommandType.StoredProcedure;
comm.Parameters.Add(new SqlParameter("#ControllerNoteID", ControllerNoteId));
try
{
conn.Open();
using (var rdr = comm.ExecuteReader())
{
while (rdr.Read())
{
CommentText = rdr["NoteText"].ToString();
_commentor = new User(new Guid(rdr["NoteAuthor"].ToString()));
CommentDate = (DateTime)rdr["NoteDate"];
MocRequestId = (int)rdr["MocRequestID"];
}
}
}
catch (Exception ex)
{
HasError = true;
ErrorMessage += "\nThere was a problem building the note: " + ex.Message;
}
}
}
}
The stored procedure on the DBMS (sql server in this example):
ALTER proc [dbo].[sp_SelectControllerNoteByID]
#ControllerNoteID int
AS
SELECT
ControllerNoteID,
NoteText,
NoteDate,
NoteAuthor,
MocRequestID
FROM
ControllerNotes
WHERE
ControllerNoteID = #ControllerNoteID
So here we call the stored procedure which in this case is just a simple select statement, then we read it out into an object via ADO. Now, this way, you can modify your query without recompiling. Unless you add parameters, in which case you'll have to update those in your code as well.
I have a vb .net ArrayList that I would like to store in one field on my Ms SQL 2008 database. Is it possible to put it in and get it back out as an ArrayList?
I'm guessing i need to break down the Array some how and store it as a string, then rebuild it when reading back as i dont see any datatypes for sql that are for arrays. Which is a bummer for me!
Can anyone suggest the best way to do this?
Many thanks.
edit - The ArrayList stores a set of quote ID's. There is no limit to how big it is so it could hold 1 or 1001 different ID's
This is probably part of a one-to-many relationship. Say for example your ArrayList is storing strings, then create a separate table, where one of its fields in this string value. You can send the ArrayList as a param to your DALC class and loop through it there, adding one record at a time to the DB by calling a stored proceedure, etc.
You can use a serializer such as
var serializer = new XmlSerializer(typeof(ArrayList));
var buffer = new StringBuilder();
using(var tw = new XmlTextWriter(new StringWriter(buffer)){
serializer.serialize(tw, myArrayList);
}
var xml = buffer.ToString();
BUT There are a few warnings:
If you have a collection, this is often a sign you should make a many-to-one table but I will assume you know what you are doing and dont need that table
When instantiating XmlSerializer, watch out for memory leaks. It may not apply in your case because you are using a built in type but this is something to be aware of: http://blogs.msdn.com/b/tess/archive/2010/05/05/net-memory-leak-xslcompiledtransform-and-leaked-dynamic-assemblies.aspx
Dim no As Integer() = {11, 22, 33, 44}
Dim MS As New System.IO.MemoryStream
Dim bin As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
bin.Serialize(MS, no)
Dim bytes(MS.Length - 1) As Byte
MS.Position = 0
MS.Read(bytes, 0, bytes.Length)
....
...
cmd.ComandText="insert into TableName values (#data)"
cmd.Parameters.Add("#data", SqlDbType.Image, bytes.Length).Value = bytes
Source: http://www.daniweb.com/software-development/vbnet/threads/253410/save-array-to-database
I want to dynamically populate a link with the URI of the current request, but set one specific query string parameter. All other querystring paramaters (if there are any) should be left untouched. And I don't know in advance what they might be.
Eg, imagine I want to build a link back to the current page, but with the querystring parameter "valueOfInterest" always set to be "wibble" (I'm doing this from the code-behind of an aspx page, .Net 3.5 in C# FWIW).
Eg, a request for either of these two:
/somepage.aspx
/somepage.aspx?valueOfInterest=sausages
would become:
/somepage.aspx?valueOfInterest=wibble
And most importantly (perhaps) a request for:
/somepage.aspx?boring=something
/somepage.aspx?boring=something&valueOfInterest=sausages
would preserve the boring params to become:
/somepage.aspx?boring=something&valueOfInterest=wibble
Caveats: I'd like to avoid string manipulation if there's something more elegant in asp.net that is more robust. However if there isn't something more elegant, so be it.
I've done (a little) homework:
I found a blog post which suggested copying the request into a local HttpRequest object, but that still has a read-only collection for the querystring params. I've also had a look at using a URI object, but that doesn't seem to have a querystring
This will work as long as [1] you have a valid URL to begin with (which seems reasonable) [2] you make sure that your new value ('sausages') is properly escaped. There's no parsing, the only string manipulation is to concatenate the parameters.
Edit
Here's the C#:
UriBuilder u = new UriBuilder(Request.Url);
NameValueCollection nv = new NameValueCollection(Request.QueryString);
/* A NameValueColllection automatically makes room if this is a new
name. You don't have to check for NULL.
*/
nv["valueOfInterest"] = "sausages";
/* Appending to u.Query doesn't quite work, it
overloaded to add an extra '?' each time. Have to
use StringBuilder instead.
*/
StringBuilder newQuery = new StringBuilder();
foreach (string k in nv.Keys)
newQuery.AppendFormat("&{0}={1}", k, nv[k]);
u.Query = newQuery.ToString();
Response.Redirect(u.Uri.ToString());
UriBuilder u = new UriBuilder(Request.Url);
NameValueCollection nv = new NameValueCollection(Request.QueryString);
nv["valueofinterest"] = "wibble";
string newQuery = "";
foreach (string k in nv.Keys)
{
newQuery += k + "=" + nv[k] + "&";
}
u.Query = newQuery.Substring(0,newQuery.Length-1);
Response.Redirect(u.ToString());
that should do it
If you can't find something that exists to do it, then build a bullet-proof function to do it that is thoroughly tested and can be relied upon. If this uses string manipulation, but is efficient and fully tested, then in reality it will be little different to what you may find any way.
I need to remove the value associated with a property in a Flex 3 associative array; is this possible?
For example, suppose I created this array like so:
var myArray:Object = new Object();
myArray[someXML.#attribute] = "foo";
Later, I need to do something like this:
delete myArray[someXML.#attribute];
However, I get this error message at runtime:
Error #1119: Delete operator is not supported with operand of type XMLList.
How do I perform this operation?
delete doesn't do as much in AS3 as it did in AS2:
http://www.gskinner.com/blog/archives/2006/06/understanding_t.html
However, I think your problem might be solved by simply using toString(), i.e.
var myArray:Object = new Object();
myArray[someXML.#attribute.toString()] = "foo";
delete myArray[someXML.#attribute.toString()];
Rather than delete it, try setting the value to null.
myArray[someXML.#attribute] = null;
That way it'll end up the same as any other value in the array that isn't defined.
In a Flex application I am trying to turn an Object into a QueryString such as name1=value1&name2=value2... But I am having trouble getting the names of the Objects children. How do I enumerate the names instead of the values?
Thanks
I'm guessing you're doing a for each(in) loop. Just do a normal for(in) loop and you'll get the names instead of the values:
for(var name:String in obj) {
var value:* = obj[name];
// do whatever you need
}
Ok, first off, if you need that query string to actually query a server, you don't really need to get it yourself as this code will query the server for you
protected function callSerivce():void
{
var o:Object = new Object();
o.action = "loadBogusData";
o.val1 = "dsadasd";
service.send(o);
}
<mx:HTTPService id="service" url="http://www.somewhere.com/file.php" method="GET" showBusyCursor="true"/>
Will make a call to the server like this: http://www.somewhere.com/file.php?action=loadBogusData&val1=dsadasd
But in case you really want to analyze the object by hand, try using ObjectUtil.getClassInfo, it returns a lot of information including all the fields (read more on LiveDocs).