I'm having trouble querying an XDocument using LINQ - asp.net

I'm new to LINQ so I gather I just have some of my syntax wrong. I've looked at many examples online but everyone seems to have their own style.
Here's the XML data I'm querying against:
<ajax-response>
<response type="object" id="unknown">
<generic response="Success" message="Channel status will follow" />
</response>
<response type="object" id="unknown">
<generic event="Status" privilege="Call" channel="SIP/452-000006fc" calleridnum="452" calleridname="Joe" connectedlinenum="430" connectedlinename="device" accountcode="" channelstate="6" channelstatedesc="Up" context="macro-dial-one" extension="s" priority="37" seconds="54" bridgedchannel="SIP/430-000006fd" bridgeduniqueid="1363822334.1829" uniqueid="1363822334.1828" />
</response>
<response type="object" id="unknown">
<generic event="Status" privilege="Call" channel="SIP/430-000006fd" calleridnum="430" calleridname="device" connectedlinenum="452" connectedlinename="Joe" account="" state="Up" bridgedchannel="SIP/452-000006fc" bridgeduniqueid="1363822334.1828" uniqueid="1363822334.1829" />
</response>
<response type="object" id="unknown">
<generic event="StatusComplete" items="2" />
</response>
</ajax-response>
and here's what I have so far:
Function ParseXML(statusXML As XmlDocument) As String
Dim xdoc As XDocument = XDocument.Load(New XmlNodeReader(statusXML))
Dim parsed As StringBuilder = New StringBuilder()
Dim query = From generic In xdoc.Descendants("generic") _
Where generic.Attribute("privilege") IsNot Nothing And generic.Attribute("privilege").Value = "Call" _
Select connectedlinenum = generic.Attribute("connectedlinenum").ToString, _
calleridnum = generic.Attribute("calleridnum").ToString
For Each i In query
parsed.Append(i.connectedlinenum).Append(",").Append(i.calleridnum).Append(vbCrLf)
Next
Return parsed.ToString
End Function
I'm guessing I am misunderstanding how my generic object is supposed to be working, because I get a NullReferenceException in my Where clause when I try to reference it.

I'm not familiar with Xml parsing, but in two of the nodes you do not have the privilege attribute. Could that be causing the error?
In that case, what happens if you change the And to AndAlso in the Where clause? That way it would not evaluate the latter part of the statement if there is no privilege attribute.

Related

Asp.Net Linq and XML query

I'm trying to grab some data using LINQ and a "WHERE" function within my "SELECT" function
Here's my sample XML
<Items>
<Extras>
<Extra Code="TEST1" Quantity="1" />
<Extra Code="TEST2" Quantity="1" />
</Extras>
<Options>
<OptionalExtra Description="Test 1" Code="TEST1" type="TESTING1" />
<OptionalExtra Description="Test 2" Code="TEST2" type="TESTING2" />
</Options>
</Items>
And here's my LINQ query
bookingsInfo = xel.Descendants("Extras").Descendants("Extra") _
.Select(Function(f) New With { _
.Code = f.Attributes("Code").First.Value, _
.Type = f.Parent.Parent.Descendants("Options").Descendants("OptionalExtra") _
.Where(Function(g) g.Attributes("Code").First.Value = _
f.Attributes("Code").First.Value).Attributes("type").First.Value, _
.Quantity = f.Attributes("Quantity").First.Value _
})
The "TYPE" is the problem I'm having trouble getting and I'm not really sure what the issue is.
I don't have any control of how the XML is laid out but I can edit the LINQ query no problem.
Does anyone have any suggestions?
Thanks in advance
I think it will be easier to use Join instead of Parent.Parent:
Dim bookingsInfo = From e In xel.Root.<Extras>.<Extra>
Join o In xel.Root.<Options>.<OptionalExtra> On e.#Code Equals o.#Code
Select New With {
.Code = e.#Code,
.Type = o.#Type,
.Quantity = e.#Quantity
}

Can an ASP.Net asp:ControlParameter ControlID be a public shared variable instead of an asp:label?

Can an ASP.Net asp:ControlParameter ControlID be a public shared variable instead of an ASP:label?
We were using an asp:label as a parameter for a DataSource but now want to use a public shared variable instead of the label.
This is the markup of the parameter using the asp:label.
<asp:ControlParameter
ControlID="LabelCheckBoxMonday"
Name="DayOfWeekMonday"
PropertyName="Text"
Type="String" />
We added this public shared variable in the code-behind.
Public Shared blnDayOfWeekMonday As Boolean
We changed the markup for the parameter to this.
<asp:ControlParameter
ControlID="blnDayOfWeekMonday"
Name="DayOfWeekMonday"
PropertyName="Text"
Type="String" />
This is the coding that places values into the variable. The original coding that used to do that for the label is commented out.
Protected Sub ImageButtonInsertDayOfWeekMonday_Click(sender As Object, e As ImageClickEventArgs)
Dim imgTheImageButton As New ImageButton
imgTheImageButton = DetailsView.FindControl("ImageButtonInsertDayOfWeekMonday")
If imgTheImageButton.ImageUrl = "../../Images/checked.png" = True Then
imgTheImageButton.ImageUrl = "../../Images/unchecked.png"
' LabelCheckBoxMonday.Text = False
blnDayOfWeekMonday = False
Else
imgTheImageButton.ImageUrl = "../../Images/checked.png"
' LabelCheckBoxMonday.Text = True
blnDayOfWeekMonday = True
End If
End Sub
All of this is part of the following InsertCommand:
InsertCommand=
"INSERT INTO [TeacherSchedule]
([DayOfWeekMonday],
[DayOfWeekTuesday],
[DayOfWeekWednesday],
[DayOfWeekThursday],
[DayOfWeekFriday],
[DayOfWeekSaturday],
[DayOfWeekSunday],
[StartTime],
[EndTime],
[ClassID],
[TeacherID])
VALUES (#DayOfWeekMonday,
#DayOfWeekTuesday,
#DayOfWeekWednesday,
#DayOfWeekThursday,
#DayOfWeekFriday,
#DayOfWeekSaturday,
#DayOfWeekSunday,
#StartTime,
#EndTime,
#ClassID,
#TeacherID)"
When the web form is running nothing happens after changing it to the public shared variable.
Can you tell me what else I need to do to proceed?
* Update *
Using Marks suggestion I found out how to do an asp:QueryStringParameter but still don't know how to populate it with a value. This is the parameter as an asp:QueryStringParameter
<asp:QueryStringParameter
Name="DayOfWeekMonday"
QueryStringField="QSDayOfWeekMonday" />
How do I populate QSDayOfWeekMonday in the ImageButtonInsertDayOfWeekMonday_Click sub routine?
I tried:
QSDayOfWeekMonday = False
but got a "not declared" error.
* Full markup and code-behind coding *
http://pastebin.com/embed_js.php?i=kye3c2U8
Another option is to use a Parameter as:
<asp:Parameter Name="DateOfWeekMonthly" />
And in code set the DefaultValue property to the value you want to specify, as in:
DataSourceControl1.Parameters["DateOfWeekMonthly"].DefaultValue = someVariable;
This has worked for me.
You could establish this event in the Selecting event that fires; this event fires before the select happens; therefore, you can establish the boolean value. I believe here, you can add it to the collection of values defined in the event argument.
I used this shorter way:
<asp:Parameter Name="DateOfWeekMonthly" Type="Boolean" DefaultValue="true" />
This is also working.

Linq2Xml Parse Output from REST web service

I am attempting to parse the XML output from a REST web service and have been pointed in the direction of using Linq2Xml to query the XML for the attributes that I am after. The XML output is as follows:
<?xml version="1.0" encoding="UTF-8"standalone="yes" ?>
<Response Status="OK">
<Item Name="NumberZones">2</Item>
<Item Name="CurrentZoneID">10001</Item>
<Item Name="CurrentZoneIndex">1</Item>
<Item Name="ZoneName0">Westralia</Item>
<Item Name="ZoneID0">0</Item>
<Item Name="ZoneGUID0">{81C56183-31DA-45C2-90C3-81609F01B38B}</Item>
<Item Name="ZoneName1">Lounge</Item>
<Item Name="ZoneID1">10001</Item>
<Item Name="ZoneGUID1">{eac0109e-0090-a992-7fba-dc67fe29e6e7}</Item>
</Response>
I am wanting to return in a datatable the ZoneID, ZoneName, and ZoneGUID, I am wanting the function to return something like:
id name guid
0 westralia {81C56183-31DA-45C2-90C3-81609F01B38B}
10001 lounge {eac0109e-0090-a992-7fba-dc67fe29e6e7}
I have been working on the following function to query the XML, and have gotten as far as attempting to return results (not even at the point of trying to manipulate the data to get it into the format that I am wanting).
Private Function getServerResponse_Linq(ByVal queryString As Uri) As DataTable
Dim dt As DataTable = New DataTable("data")
With dt
.Columns.Add("name")
.Columns.Add("Value")
End With
Dim loaded As XDocument = XDocument.Load(queryString.ToString)
Dim dr As DataRow
Dim query = From c In loaded.<Response> Select c
For Each result In query
dr = dt.NewRow
With dr
.Item("name") = result.#name
.Item("value") = result.Value
End With
Next
Return dt
End Function
The returned datatable is empty, I have confirmed that result does have the XML assigned, and result.value is the string version of the XML file (200Westralia0{81C56183-31DA-45C2-90C3-81609F01B38B}Lounge10001{eac0109e-0090-a992-7fba-dc67fe29e6e7})
Is anyone able to provide assistance in how I can read from the REST XML example above the name (ZoneName%) and the attribute value (Westralia and Lounge)?
There are three problems I can see with your code snippet. First, instead of
Dim query = From c In loaded.<Response> Select c
you need
Dim query = From c In loaded.<Response>.Elements Select c
or even just
Dim query = loaded.<Response>.Elements
to fetch the Items rather than the Response.
Also, you need to add
dt.Rows.Add(dr)
to your loop, otherwise your new row won't get added to the DataTable.
Finally, XML is case sensitive so you need to use #Name, not #name.

Get scope_identity returned value

How can i get the scope identity parameter in my vb code. I have this so far....
InsertCommand="INSERT INTO [table_name] ([title], [subtitle], [description], [image1], [image1_caption], [image2], [pdf], [meta_description], [meta_keywords]) VALUES (#title, #subtitle, #description, #image1, #image1_caption, #image2, #pdf, #meta_description, #meta_keywords); SELECT #NewID = SCOPE_IDENTITY()"
<asp:Parameter Direction="Output" Name="NewID" Type="Int32" />
How can i retreive this ID, in the DetailsView1_ItemInserted?
If you need anymore info let me know.
Thanks
Did you try this in the ItemInserted event handler?
Sub EmployeeDetailsSqlDataSource_OnInserted(sender As Object, e As SqlDataSourceStatusEventArgs)
Dim command As System.Data.Common.DbCommand = e.Command
EmployeesDropDownList.DataBind()
EmployeesDropDownList.SelectedValue = _
command.Parameters("#NewID").Value.ToString()
EmployeeDetailsView.DataBind()
End Sub
Not sure if you need Parameter Direction attribute.
Check out this MSDN article, they do exactly what you are attempting.
http://msdn.microsoft.com/en-us/library/xt50s8kz(VS.80).aspx

Return value from SQL 2005 SP returns DBNULL - Where am I going wrong?

This is the SP...
USE [EBDB]
GO
/****** Object: StoredProcedure [dbo].[delete_treatment_category] Script Date: 01/02/2009 15:18:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
RETURNS 0 FOR SUCESS
1 FOR NO DELETE AS HAS ITEMS
2 FOR DELETE ERROR
*/
ALTER PROCEDURE [dbo].[delete_treatment_category]
(
#id INT
)
AS
SET NOCOUNT ON
IF EXISTS
(
SELECT id
FROM dbo.treatment_item
WHERE category_id = #id
)
BEGIN
RETURN 1
END
ELSE
BEGIN
BEGIN TRY
DELETE FROM dbo.treatment_category
WHERE id = #id
END TRY
BEGIN CATCH
RETURN 2
END CATCH
RETURN 0
END
And I'm trying to get the return value using the below code (sqlDataSource & Gridview combo in VB .NET
Protected Sub dsTreatmentCats_Deleted(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceStatusEventArgs) Handles dsTreatmentCats.Deleted
Select Case CInt(e.Command.Parameters(0).Value)
Case 0
'it worked so no action
lblError.Visible = False
Case 1
lblError.Text = "Unable to delete this category because it still has treatments associated with it."
lblError.Visible = True
Case 2
lblError.Text = "Unable to delete this category due to an unexpected error. Please try again later."
lblError.Visible = True
End Select
End Sub
The problem is that the line CInt(e.Command.Parameters(0).Value) returns a DBNull instead of the return value but only on deletes - this approach works fine with both updates and inserts.
Hopefully I'm just being a bit dense and have missed something obvious - any ideas?
Edit
I'm still having this problem and have tried all of the options below to no avail - I'm surprised no one else has had this problem?
Code for adding parameters:
<asp:SqlDataSource ID="dsTreatmentCats" runat="server"
ConnectionString="<%$ ConnectionStrings:EBDB %>"
DeleteCommand="delete_treatment_category" DeleteCommandType="StoredProcedure"
InsertCommand="add_treatment_category" InsertCommandType="StoredProcedure"
SelectCommand="get_treatment_categories" SelectCommandType="StoredProcedure"
UpdateCommand="update_treatment_category"
UpdateCommandType="StoredProcedure" ProviderName="System.Data.SqlClient">
<DeleteParameters>
<asp:Parameter Direction="ReturnValue" Name="RetVal" Type="Int32" />
<asp:Parameter Name="id" Type="Int32" />
</DeleteParameters>
<UpdateParameters>
<asp:Parameter Direction="ReturnValue" Name="RetVal" Type="Int32" />
<asp:Parameter Name="id" Type="Int32" />
<asp:Parameter Name="name" Type="String" />
<asp:Parameter Name="additional_info" Type="String" />
</UpdateParameters>
<InsertParameters>
<asp:Parameter Direction="ReturnValue" Name="RetVal" Type="Int32" />
<asp:ControlParameter ControlID="txtCat" Name="name" PropertyName="Text"
Type="String" />
<asp:ControlParameter ControlID="txtAddInfo" Name="additional_info"
PropertyName="Text" Type="String" />
</InsertParameters>
</asp:SqlDataSource>
I'm a little late to the game here, but for the sake of people who stumble upon this question...
If you're using ExecuteReader in ADO.Net, the return value will not be populated until you close either the Reader or the underlying connection to the database. (See here)
This will not work:
SqlConnection conn = new SqlConnection(myConnectionString);
SqlCommand cmd = new SqlCommand(mySqlCommand, conn);
// Set up your command and parameters
cmd.Parameters.Add("#Return", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
// Read your data
}
int resultCount = (int)cmd.Parameters["#Return"].Value;
conn.Close();
return resultCount;
This will:
SqlConnection conn = new SqlConnection(myConnectionString);
SqlCommand cmd = new SqlCommand(mySqlCommand, conn);
// Set up your command and parameters
cmd.Parameters.Add("#Return", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
// Read your data
}
conn.Close();
int resultCount = (int)cmd.Parameters["#Return"].Value;
return resultCount;
When you added the Parameter, did you set the Direction to ReturnValue?
Yep I did - I'm using the sqlDataSource control which sniffed out the params for me including the return value with the correct direction set. Just for fun I did also create the param from scratch with return val direction too but no joy :(
Run this in the SQL tools to ensure that the stored proc behaves as expected.
DECLARE #rtn int;
EXEC #rtn = dbo.delete_treatment_category /*insert valid id here > 2*/;
SELECT #rtn;
I mention "an id > 2" because you may be reading the wrong parameter.
That is, this stored proc has 2 parameters... one for the id and the other for the return value.
IIRC:
cmd.CommandType = CommandType.StoredProcedure 'cmd is SqlCommand
Dim retValParam as New SqlParameter("#RETURN_VALUE", SqlDbType.Int)
retValParam.Direction = ParameterDirection.ReturnValue
cmd.Parameters.Add(retValParam)
'add the ID parameter here
'execute
'look at the #RETURN_VALUE parameter here
You don't show the code where you are adding the parameters and executing the command. Both may be critical.
I know one way of reproducing this - if your procedure also returns rows (for example, from a DELETE trigger), and you haven't consumed those rows... basically, the out/return parameter values follow the grids in the TDS stream, so if you haven't read the grids yet (when using ExecuteReader) - then you can't get the updated parameters / return value. But if you are using ExecuteNonQuery this shouldn't be a factor.
Why do you use Name="RETURN_VALUE" for the Delete parameter but Name="RetVal" for Update and Insert? If the latter two work, that is the first place I'd look.

Resources