|
Thanks for your answer. Since the attribute is under my control, I could modify it: I added a property for the ResourceType. Meant that I had to modify a few hundred places where it was used, but it works...
Strange that sometimes such "easy" ideas require such a lot of work-around.
Oh sanctissimi Wilhelmus, Theodorus, et Fredericus!
|
|
|
|
|
what is the benefit of delegets and how it is differ from Event and how it handled?
|
|
|
|
|
Delegates
Briefly, delegates are reference to method and they are important because they represent callback to your asynchronous operations i.e. events: you may never know when particular event encounters but you might want to handle it exactly once it's there
|
|
|
|
|
Events are Delegates as a very simple Google would have found you: delegets and how it is differ from Event - Google Search[^]
Follow a few of the links, read a few of the answers at SO and CP - if that doesn't clear it up for you, come back and explain exactly what you don't understand.
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
can i use try catch finally in PHP?
|
|
|
|
|
This is the C# forum. Have you tried the PHP documentation?
|
|
|
|
|
Apart from trying the right forum: Linux, Apache, MySQL, PHP Discussion Boards[^] or Ask A Question[^], Google is your friend: Be nice and visit him often. He can answer questions a lot more quickly than posting them here...
A very quick search using your subject as the search term gave over two million hits: try catch finally in PHP - Google Search[^]
The top "summary" and link tells you the answer by reference to the standard documentation!
PHP: Exceptions - Manual[^]
In future, please try to do at least basic research yourself, and not waste your time or ours.
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
Some time I make method for example the treenode in treeview some programmer write the code in four lines and it flexible me I write many lines and it is not flexible so if you have articles ,books help me to be proffessional make me call the method it self many times it will be nice.
this is my code:
<pre> public void FillTreeViewWith5(string Query1, string Query2, string Query3, string Query4,
string Query5,string Query6,string Query7, DataSet Ds, TreeView tr, TreeNode tn1,
TreeNode tn2, TreeNode tn3, TreeNode tn4, TreeNode tn5,TreeNode tn6,TreeNode tn7)
{
int z = 0;
int r = 0;
int res;
string i1;
string i2;
string i3;
string i4;
string i5;
string i6;
tr.Nodes.Clear();
SqlDataAdapter da1 = new SqlDataAdapter(Query1,con);
da1.Fill(Ds, "d1");
for (int i = 0; i < Ds.Tables["d1"].Rows.Count; i++)
{
i1 = Ds.Tables["d1"].Rows[i][0].ToString();
string x1 = Ds.Tables["d1"].Rows[i][1].ToString();
tn1 = new TreeNode(x1);
SqlCommand cmd2 = new SqlCommand();
cmd2.Connection = con;
cmd2.CommandText = Query2;
cmd2.Parameters.AddWithValue("@i1", i1);
SqlDataAdapter da2 = new SqlDataAdapter(cmd2);
da2.Fill(Ds, "d2");
for (int j = 0; j < Ds.Tables["d2"].Rows.Count; j++)
{
i2= Ds.Tables["d2"].Rows[j][0].ToString();
string x2 = Ds.Tables["d2"].Rows[j][1].ToString();
tn2 = new TreeNode(x2);
tn1.Nodes.Add(tn2);
SqlCommand cmd3 = new SqlCommand();
cmd3.Connection = con;
cmd3.CommandText = Query3;
cmd3.Parameters.AddWithValue("@i2", i2);
SqlDataAdapter da3 = new SqlDataAdapter(cmd3);
da3.Fill(Ds, "d3");
for (int b = 0; b < Ds.Tables["d3"].Rows.Count; b++)
{
i3 = Ds.Tables["d3"].Rows[b][0].ToString();
string x3 = Ds.Tables["d3"].Rows[b][1].ToString();
tn3 = new TreeNode(x3);
tn2.Nodes.Add(tn3);
SqlCommand cmd4 = new SqlCommand();
cmd4.Connection = con;
cmd4.CommandText = Query4;
cmd4.Parameters.AddWithValue("@i3", i3);
SqlDataAdapter da4 = new SqlDataAdapter(cmd4);
da4.Fill(Ds, "d4");
for (int c = 0; c < Ds.Tables["d4"].Rows.Count; c++)
{
i4 = Ds.Tables["d4"].Rows[c][0].ToString();
string x4 = Ds.Tables["d4"].Rows[c][1].ToString();
tn4 = new TreeNode(x4);
tn3.Nodes.Add(tn4);
SqlCommand cmd5 = new SqlCommand();
cmd5.Connection = con;
cmd5.CommandText = Query5;
cmd5.Parameters.AddWithValue("@i4", i4);
SqlDataAdapter da5 = new SqlDataAdapter(cmd5);
da5.Fill(Ds, "d5");
for ( int m= 0; m <Ds.Tables["d5"].Rows.Count ; m++)
{
i5 = Ds.Tables["d5"].Rows[m][0].ToString();
string x5= Ds.Tables["d5"].Rows[m][1].ToString();
tn5 = new TreeNode(x5);
tn4.Nodes.Add(tn5);
SqlCommand cmd6 = new SqlCommand();
cmd6.CommandText = Query6;
cmd6.Connection = con;
cmd6.Parameters.AddWithValue( "@i5",i5);
SqlDataAdapter da6 = new SqlDataAdapter(cmd6);
da6.Fill(Ds, "d6");
for (int p= 0; p < Ds.Tables["d6"].Rows.Count; p++)
{
i6 = Ds.Tables["d6"].Rows[p][0].ToString();
string x6 = Ds.Tables["d6"].Rows[p][1].ToString();
tn6 = new TreeNode(x6);
tn5.Nodes.Add(tn6);
SqlCommand cmd7 = new SqlCommand();
cmd7.CommandText = Query7;
cmd7.Connection = con;
cmd7.Parameters.AddWithValue("@i6", i6);
SqlDataAdapter da7 = new SqlDataAdapter(cmd7);
da7.Fill(Ds, "d7");
res=Ds.Tables["d7"].Rows.Count;
for (r = z; r < res; r++)
{
string i7 = Ds.Tables["d7"].Rows[r][0].ToString();
string x7 = Ds.Tables["d7"].Rows[r][1].ToString();
tn7 = new TreeNode(x7);
tn6.Nodes.Add(tn7);
}
z = r;
res = res + res;
}
}
}
}
}
}
tr.Nodes.Add(tn1);
tr.ExpandAll();
}
the proffessional programmer code:
<pre>private void AddTreeNode(TreeNode parentNode, DataTable table, int parentId)
{
var filteredRows = table.AsEnumerable().Where(r => Convert.ToInt32(r["parent_id"]) == parentId).ToList();
foreach(DataRow row in filteredRows)
{
TreeNode node = new TreeNode(row["Re_nm"].ToString());
if (parentNode == null)
tr.Nodes.Add(node);
else
parentNode.Nodes.Add(node);
AddTreeNode(node, table, Convert.ToInt32(row["Re_id"]));
}
}
|
|
|
|
|
|
i know c# is designed from c and c++ concept and it is based on OOPS, i want to know that c# only based on OOPS or any new concept is there?
|
|
|
|
|
|
Ummm... It's Object Oriented Programming (OOP), not OOPS.
|
|
|
|
|
Dave Kreskowiak wrote: not OOPS You have not seen the OPs code !
Never underestimate the power of human stupidity
RAH
|
|
|
|
|
True, and I think I want to protect my eyes, thank you.
|
|
|
|
|
how can i add membership with expiry date ?
user needs to purchase membership on my website with account for getting access to program
|
|
|
|
|
Add the information to the user's account entry in the database.
|
|
|
|
|
i have this code
var Result = from x in db.vams
join y in db.ghests
on new { X1 = x.code_sabt } equals new { X1 = y.code_sabt }
where y.code_vam == (from z in db.vams where z.code_sabt == myuser select z.row_codevam).Max()
group y by x.row_codevam into g
select new
{
sum_ghest = g.Sum(k=>k.price),
i need-----> x.colimns :( :( :(
};
how can i access to
db.vams columns in the select new part??????
|
|
|
|
|
I am having a STUPID amount of trouble with this. Just when I think I have it figured out - I don't. One thing I have found is that events seem to find a seemingly random order and nested events just refuse the way you expect them to and do not trigger in the order you might expect.
Basically : I have XAML form. On this form I have (among other controls), several bound drop down list controls. The first of these is not dependent on any other, the contents of the second drop down list is dependent on the selected value of the first, the third is dependent on the selection in the second and so on.
Problem 1 : The list contents vary in size depending on other form values. This means that when I am creating a list it sometimes throws an index out of bounds error if the previous index was 4 and the new list only contains 2 entries
Problem 2 : I keep getting stuck in loops. Updating the drop list boxes also forces a property change in the selected value which then triggers an update to my list and contents and the cycle continues
Problem 3 : trying to throw OnPropertyChanged at specific points in my code seems to just completely confuse the process with the order that the events are thrown and trapped making very little sense.
Problem 4 : the list goes on.
SO! I arrive here at Code Project. I have make up some sample code and keep it down to an minimum as everything I have done to date seems to be a complete mess. I have also included lines of XAML to show the way the drop down lists are bound to the data.
Part of the issue that is catching me out is the need to also validate and set accordingly the selected property and list contents of the combo boxes. i.e. if the Category is changed I need to update the contents of the Colours combo box and ALSO the selected combo box item. This in turn requires the Shapes combo box and relevant combo box to be validate accordingly.
I am hoping that the below is sufficient to illustrate what is seemingly a simple task. I didn't want to bury this question with a mountain of rubbish code that I have ended up with trying a bunch of experiments to get this to work. I've been working on this ALL DAY today and a fair portion of yesterday so my eyes are getting blurry and productivity has all but left me.
XAML bindings :
<ComboBox Margin="2,2,2,2" BorderThickness="0,0,0,1" Grid.Row="3" Grid.Column="1" ItemsSource="{Binding DataCategoryList}" SelectedIndex="{Binding DataCategory}" DisplayMemberPath="Name" />
<ComboBox Margin="2,2,2,2" BorderThickness="0,0,0,1" Grid.Row="4" Grid.Column="1" ItemsSource="{Binding DataColourList}" SelectedIndex="{Binding DataColour}" DisplayMemberPath="Name"/>
<ComboBox Margin="2,2,2,2" BorderThickness="0,0,0,1" Grid.Row="5" Grid.Column="1" ItemsSource="{Binding DataShapeList}" SelectedIndex="{Binding DataShape}" DisplayMemberPath="Name"/>
C#
public class Base : INotifyPropertyChanged
{
private string _ID;
private string _Name;
public string ID { get { return _ID; } set { _ID = value; OnPropertyChanged( "ID" ); } }
public string Name { get { return _Name; } set { _Name = value; OnPropertyChanged( "Name" ); } }
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged( string propertyName )
{
if( PropertyChanged != null )
PropertyChanged( this, new PropertyChangedEventArgs( propertyName ) );
}
}
public class MyData : INotifyPropertyChanged
{
private Base _Category;
private Base _Colour;
private Base _Shape;
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged( string propertyName )
{
if( PropertyChanged != null )
PropertyChanged( this, new PropertyChangedEventArgs( propertyName ) );
}
public Base Category
{
get { return _Category; }
set
{
_Category = value;
OnPropertyChanged( "Category" );
}
}
public Base Colour
{
get { return _Colour; }
set
{
_Colour = value;
OnPropertyChanged( "Colour" );
}
}
public Base Shape
{
get { return _Shape; }
set
{
_Shape = value;
OnPropertyChanged( "Shape" );
}
}
}
public class MyWindow : INotifyPropertyChanged
{
private MyData _Data;
public MyData Data { get { return _Data; } set { _Data = value; } }
public MyWindow( ) : base( )
{
Data = new MyData( )
{
Category = new Base( ) { ID = "A", Name = "Category A" },
Colour = new Base( ) { ID = "RD", Name = "Red" },
Shape = new Base( ) { ID = "RND", Name = "Round" },
};
Data.PropertyChanged += Data_PropertyChanged;
}
private void ValidateCategoryChange( string id)
{
Base result = null;
foreach( Base colour in DataColourList )
if( colour.ID == id )
result = colour;
Data.Colour = result ?? DataColourList[ 0 ];
}
private void ValidateColourChange( string id )
{
Base result = null;
foreach( Base shape in DataShapeList )
if( shape.ID == id )
result = shape;
Data.Shape = result ?? DataShapeList[ 0 ];
}
private void Data_PropertyChanged( object sender, PropertyChangedEventArgs e )
{
OnPropertyChanged( String.Format( "Cable{0}", e.PropertyName ) );
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged( string propertyName )
{
if( PropertyChanged != null )
PropertyChanged( this, new PropertyChangedEventArgs( propertyName ) );
}
public List<Base> BuildCategoryList( )
{
List<Base> result = new List<Base>();
result.Add( new Base( ) { ID = "A", Name = "Category A" } );
result.Add( new Base( ) { ID = "A", Name = "Category B" } );
return result;
}
public List<Base> BuildColourList( string categoryID )
{
List<Base> result = new List<Base>();
if( categoryID == "A" )
{
result.Add( new Base( ) { ID = "RD", Name = "Red" } );
result.Add( new Base( ) { ID = "BL", Name = "Blue" } );
}
else
{
result.Add( new Base( ) { ID = "BK", Name = "Black" } );
result.Add( new Base( ) { ID = "OR", Name = "Green" } );
result.Add( new Base( ) { ID = "RD", Name = "Red" } );
result.Add( new Base( ) { ID = "BL", Name = "Blue" } );
}
return result;
}
public List<Base> BuildShapeList( string colourID )
{
List<Base> result = new List<Base>();
if( colourID == "RD" || colourID == "BK" )
{
result.Add( new Base( ) { ID = "RND", Name = "Round" } );
result.Add( new Base( ) { ID = "SQR", Name = "Square" } );
result.Add( new Base( ) { ID = "TNG", Name = "Triangle" } );
}
else
{
result.Add( new Base( ) { ID = "RCT", Name = "Rectangle" } );
}
return result;
}
public List<Base> DataCategoryList { get; set; }
public int DataCategory
{
get
{
for( int index = 0; index < DataCategoryList.Count; index++ )
if( Data.Category == DataCategoryList[ index ] )
return index;
return -1;
}
set
{
if( value == -1 )
return;
Data.Category.ID = DataCategoryList[ value ].ID;
OnPropertyChanged( "DataCategory" );
DataColourList = BuildColourList( Data.Category.ID );
ValidateCategoryChange( Data.Category.ID );
}
}
public List<Base> DataColourList { get; set; }
public int DataColour
{
get
{
for( int index = 0; index < DataColourList.Count; index++ )
if( Data.Colour == DataColourList[ index ] )
return index;
return -1;
}
set
{
if( value == -1 )
return;
Data.Colour.ID = DataColourList[ value ].ID;
OnPropertyChanged( "DataColour" );
DataShapeList = BuildShapeList( Data.Colour.ID );
ValidateColourChange( Data.Colour.ID );
}
}
public List<Base> DataShapeList { get; set; }
public int DataShape
{
get
{
for( int index = 0; index < DataShapeList.Count; index++ )
if( Data.Category.ID == DataShapeList[ index ].ID )
return index;
return -1;
}
set
{
if( value == -1 )
return;
Data.Category = DataShapeList[ value ];
OnPropertyChanged( "DataShape" );
}
}
}
|
|
|
|
|
I have never used SelectedIndex and suspect that will be the issue, especially when you are changing the content of the bound list. Try changing the binding to SelectedItem.
EG I would have an observablecollection of colours and a selectedcolour object in my viewmodel.
When you rebuild your lists you lose all your selected item/index etc. Try creating a mapping object that you can FILTER instead of rebuilding the lists endlessly.
Never underestimate the power of human stupidity
RAH
|
|
|
|
|
Talk to people, good afternoon.
I'm having trouble getting my strings from my checklist to do an update on my system.
my real scenario is this, I can do the insertion through the checkbox, concatenating more than one string and storing it in a table called students and storing my selected strings in the activity column.
When I upgrade, I can not get more than one string to refresh my checkbox, it returns only one selected when I click on my button to refresh the information.
follow the code to understand it better.
This is my code to do the update through ArrayLisyt where I get my text box and comboBox
<pre>private void button1_Click(object sender, EventArgs e)
{
SysDBADM obj = new SysDBADM();
ArrayList arr = new ArrayList();
try
{
arr.Add(TB_cod.Text);
arr.Add(TB_nome.Text);
arr.Add(TB_idade.Text);
arr.Add(TB_endereco.Text);
arr.Add(TB_quadra_lote.Text);
arr.Add(MD_telefoneCel.Text);
arr.Add(TB_email.Text);
arr.Add(TB_cidade.Text);
arr.Add(TB_uf.Text);
arr.Add(TB_nomepai.Text);
arr.Add(TB_nomemae.Text);
arr.Add(CB_ativo.Text);
arr.Add(CLB_atividade.Text);
if (obj.Update(arr))
{
TB_cod.Clear();
TB_nome.Clear();
TB_idade.Clear();
TB_endereco.Clear();
TB_quadra_lote.Clear();
MD_telefoneFixo.Clear();
MD_telefoneCel.Clear();
TB_email.Clear();
TB_cidade.Clear();
TB_uf.Clear();
TB_nomepai.Clear();
TB_nomemae.Clear();
CB_ativo.Text = "";
while (CLB_atividade.CheckedItems.Count > 0)
{
CLB_atividade.SetItemChecked(CLB_atividade.CheckedIndices[0],false);
}
MessageBox.Show("Cadastro Atualizado.", "Mensagem do Sistema", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Erro ao Atualizar!", "Mesagem do Sistema", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception erro)
{
MessageBox.Show(erro + "Erro Ocorrido");
}
}
this is my class where are the parameters to perform the update.
public bool Update(ArrayList p_arrUpdate)
{
vsql = "UPDATE alunos SET nome = @nome, idade = @idade, endereco = @endereco, quadra_lote = @quadra_lote, telefone = @telefone, email = @email, cidade = @cidade, uf = @uf, nome_pai = @nome_pai, nome_mae = @nome_mae, situacao = @situacao, atividade = @atividade WHERE id_aluno = @id_aluno";
SqlCommand objcmd = null;
if (this.conectar())
try
{
objcmd = new SqlCommand(vsql, objCon);
objcmd.Parameters.Add(new SqlParameter("@id_aluno", p_arrUpdate[0]));
objcmd.Parameters.Add(new SqlParameter("@nome", p_arrUpdate[1]));
objcmd.Parameters.Add(new SqlParameter("@idade", p_arrUpdate[2]));
objcmd.Parameters.Add(new SqlParameter("@endereco", p_arrUpdate[3]));
objcmd.Parameters.Add(new SqlParameter("@quadra_lote", p_arrUpdate[4]));
objcmd.Parameters.Add(new SqlParameter("@telefone", p_arrUpdate[5]));
objcmd.Parameters.Add(new SqlParameter("@email", p_arrUpdate[6]));
objcmd.Parameters.Add(new SqlParameter("@cidade", p_arrUpdate[7]));
objcmd.Parameters.Add(new SqlParameter("@uf", p_arrUpdate[8]));
objcmd.Parameters.Add(new SqlParameter("@nome_pai", p_arrUpdate[9]));
objcmd.Parameters.Add(new SqlParameter("@nome_mae", p_arrUpdate[10]));
objcmd.Parameters.Add(new SqlParameter("@situacao", p_arrUpdate[11]));
objcmd.Parameters.Add(new SqlParameter("@atividade", p_arrUpdate[12]));
objcmd.ExecuteNonQuery();
return true;
}
catch (SqlException sqlerr)
{
throw sqlerr;
}
finally
{
this.desconectar();
}
else
{
return false;
}
}
modified 6-Sep-17 13:52pm.
|
|
|
|
|
This is an English-language site. Please post all questions in English.
If you don't speak English, Google Translate should get you close enough.
Este é um site em inglês. Poste todas as perguntas em inglês.
Se você não fala inglês, o Google Translate deve aproximá-lo o suficiente.
Quote: Talk to people, good afternoon.
I'm having a hard time getting my strings from my checkedlistbox to do an update on my system.
my real scenario is this, I can do the insert through the checkedlistbox by concatenating more than one string and storing it in a table called students and storing my selected strings in the activity column.
When I do the update I can not get more than one string to update my checklistbox, it returns only one selected when I click on my button to update the information.
follow the code to understand better.
this is my code to do the update through ArrayLisyt where I get my textbox, and comboBox
Quote: This is my class where the parameters are to perform the update.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
I get an 'object reference not set to an instance of an object' error on the ' if (xmlResponse.SelectSingleNode("/Response/Code").InnerText != "")' line. I know that is a vague error and If someone can see what the problem based off the code. I would also like to know where I can go to or how to get a more specific error message if possible. And also I know there is an xmlResolver that can be set to null that can be used but not sure how to use it in this code.
using System;
namespace Shipment_WS_Test_App
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
try
{
string flg = string.Empty;
while (flg != "q")
{
System.Text.StringBuilder request = new System.Text.StringBuilder();
saia.shipment.Shipment shipment = new saia.shipment.Shipment();
shipment.Timeout = 120000;
request.Append("<GetByProNumber>");
request.Append("<UserID>userid</UserID>");
request.Append("<Password>password</Password>");
request.Append("<TestMode>N</TestMode>");
request.Append("<ProNumber>983579110</ProNumber>");
request.Append("</GetByProNumber>");
string xmlreq = "<AmazonTrackingRequest xmlns:xsi=\"www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"AmazonTrackingRequest.xsd\"><Validation><UserID>AMZN</UserID><Password>12345</Password></Validation><APIVersion>4.0</APIVersion><TrackingNumber>123456789</TrackingNumber></AmazonTrackingRequest> ";
string response = shipment.ProcessXML(xmlreq);
System.Xml.XmlDocument xmlResponse = new System.Xml.XmlDocument();
xmlResponse.LoadXml(response);
if (xmlResponse.SelectSingleNode("/Response/Code").InnerText != "")
{
System.Console.WriteLine(xmlResponse.SelectSingleNode("/Response/Code").InnerText);
System.Console.WriteLine(xmlResponse.SelectSingleNode("/Response/Element").InnerText);
System.Console.WriteLine(xmlResponse.SelectSingleNode("/Response/Fault").InnerText);
System.Console.WriteLine(xmlResponse.SelectSingleNode("/Response/Message").InnerText);
}
else
{
System.Console.WriteLine(xmlResponse.SelectSingleNode("/Response/Consignee/AccountNumber").InnerText);
System.Console.WriteLine(xmlResponse.SelectSingleNode("/Response/Consignee/Address1").InnerText);
System.Console.WriteLine(xmlResponse.SelectSingleNode("/Response/Consignee/Address2").InnerText);
System.Console.WriteLine(xmlResponse.SelectSingleNode("/Response/Consignee/City").InnerText);
System.Console.WriteLine(xmlResponse.SelectSingleNode("/Response/Consignee/State").InnerText);
System.Console.WriteLine(xmlResponse.SelectSingleNode("/Response/Consignee/Zipcode").InnerText);
);
}
shipment.Dispose();
request = null;
}
}
catch (System.Exception ex)
{
Console.WriteLine(ex.ToString());
Console.ReadLine();
}
}
}
}
|
|
|
|
|
This is one of the most common problems we get asked, and it's also the one we are least equipped to answer, but you are most equipped to answer yourself.
Let me just explain what the error means: You have tried to use a variable, property, or a method return value but it contains null - which means that there is no instance of a class in the variable.
It's a bit like a pocket: you have a pocket in your shirt, which you use to hold a pen. If you reach into the pocket and find there isn't a pen there, you can't sign your name on a piece of paper - and you will get very funny looks if you try! The empty pocket is giving you a null value (no pen here!) so you can't do anything that you would normally do once you retrieved your pen. Why is it empty? That's the question - it may be that you forgot to pick up your pen when you left the house this morning, or possibly you left the pen in the pocket of yesterdays shirt when you took it off last night.
We can't tell, because we weren't there, and even more importantly, we can't even see your shirt, much less what is in the pocket!
Back to computers, and you have done the same thing, somehow - and we can't see your code, much less run it and find out what contains null when it shouldn't.
But you can - and Visual Studio will help you here. Run your program in the debugger and when it fails, VS will show you the line it found the problem on. You can then start looking at the various parts of it to see what value is null and start looking back through your code to find out why. So put a breakpoint at the beginning of the method containing the error line, and run your program from the start again. This time, VS will stop before the error, and let you examine what is going on by stepping through the code looking at your values.
But we can't do that - we don't have your code, we don't know how to use it if we did have it, we don't have your data. So try it - and see how much information you can find out!
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
Griff has given you good advice. I will say that the reason you are seeing this error is probably because of a fundamental assumption you're making here - that you have /Response/Code as a single node. If you retrieve this into a separate variable, I bet you'll see that you don't actually have this as a response. BTW - quick hint, if you wrap the instantiation of shipment into a using statement, you'll automatically get a Dispose on it, so you won't need to worry about having to manually call Dispose yourself.
This space for rent
|
|
|
|
|
Since it looks like you're writing new code, rather than maintaining existing code, you might want to consider using LINQ to XML instead:
LINQ to XML Overview (C#) | Microsoft Docs[^]
using System;
using System.Xml.Linq;
using System.Xml.XPath;
namespace Shipment_WS_Test_App
{
static class Class1
{
private static readonly XNamespace XsiNamespace = "www.w3.org/2001/XMLSchema-instance";
[STAThread]
static void Main(string[] args)
{
try
{
using (var shipment = new saia.shipment.Shipment())
{
shipment.Timeout = 120000;
var request = new XDocument(
new XElement("AmazonTrackingRequest",
new XAttribute(XNamespace.Xmlns + "xsi", XsiNamespace),
new XAttribute(XsiNamespace + "noNamespaceSchemaLocation", "AmazonTrackingRequest.xsd"),
new XElement("Validation",
new XElement("UserID", "AMZN"),
new XElement("Password", "12345")
),
new XElement("APIVersion", "4.0"),
new XElement("TrackingNumber", "123456789")
)
);
string response = shipment.ProcessXML(request.ToString());
if (string.IsNullOrEmpty(response))
{
Console.WriteLine("No response.");
}
else
{
XDocument xmlResponse = XDocument.Parse(response);
if (xmlResponse.Root == null)
{
Console.WriteLine("No response. ({0})", response);
}
else
{
XElement responseNode = xmlResponse.Root.Element("Response");
if (responseNode == null)
{
Console.WriteLine("Response element not found. ({0})", xmlResponse);
}
else if (!string.IsNullOrEmpty((string)responseNode.Element("Code")))
{
Console.WriteLine(responseNode.Element("Code"));
Console.WriteLine(responseNode.Element("Element"));
Console.WriteLine(responseNode.Element("Fault"));
Console.WriteLine(responseNode.Element("Message"));
}
else
{
XElement consigneeNode = responseNode.Element("Consignee");
if (consigneeNode == null)
{
Console.WriteLine("Consignee element not found. ({0})", responseNode);
}
else
{
Console.WriteLine(consigneeNode.Element("AccountNumber"));
Console.WriteLine(consigneeNode.Element("Address1"));
Console.WriteLine(consigneeNode.Element("Address2"));
Console.WriteLine(consigneeNode.Element("City"));
Console.WriteLine(consigneeNode.Element("State"));
Console.WriteLine(consigneeNode.Element("Zipcode"));
}
}
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
Console.ReadLine();
}
}
}
}
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|