Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Locked thread
Jethro
Jun 1, 2000

I was raised on the dairy, Bitch!

uXs posted:

Is "pkgcode" supposed to be in quotes ? It looks like it should be a variable and you accidently put quotes around it.
From what I can tell, "pkgcode" is a string corresponding the name of the parameter in the request, i.e. blah.aspx?pkgcode=101, and the first string is the name of the parameter in the select query.

My first suggestion would be to give your parameter a name other than "?", in case ASP.NET or Access simply don't like that as a parameter name. Don't change the actual query, just change the part where you add the parameter to
code:
FormViewDataSource.SelectParameters.Add(New QueryStringParameter("pkgcode", "pkgcode"))

Adbot
ADBOT LOVES YOU

boo_radley
Dec 30, 2005

Politeness costs nothing

boo_radley posted:

Is there a way to specify multiple exception types in a catch block?
I'd like to merge two blocks that are similar to
code:
catch (SpecificException e) {
myLog.WriteEntry (...)
}
catch (AnotherSpecificException e) {
myLog.WriteEntry (...)
}
but leave a general catch block for really unforeseen things.

Answering my own question:

General consensus seems to be checking the Exception type in the catch block:
code:
catch (Exception e)
      { 
        
        if ((e is FileNotFoundException) || (e is UnauthorizedAccessException))
        {
        ...
        }
      } 

poopiehead
Oct 6, 2004

If you're going to do it that way don't forget to throw all of the exceptions that aren't the ones you wanted to catch. If you do want to catch all exceptions and only work with those few, make sure to comment why you are catching but not handling others.

code:
catch (Exception e) 
{ 
  if ((e is FileNotFoundException) || (e is UnauthorizedAccessException)) 
  { 
    ... 
  }
  else
  {
    throw;
  } 
}
I'd prefer explicitly catching each exception though. If they have common error handling make it a function call.

uXs
May 3, 2005

Mark it zero!

Jethro posted:

From what I can tell, "pkgcode" is a string corresponding the name of the parameter in the request, i.e. blah.aspx?pkgcode=101, and the first string is the name of the parameter in the select query.

My first suggestion would be to give your parameter a name other than "?", in case ASP.NET or Access simply don't like that as a parameter name. Don't change the actual query, just change the part where you add the parameter to
code:
FormViewDataSource.SelectParameters.Add(New QueryStringParameter("pkgcode", "pkgcode"))

"FormViewDataSource.SelectParameters.Add(New QueryStringParameter("pkgcode", "pkgcode"))" will send "SELECT PackageName, Channel, PackageCode FROM DACPkgs WHERE Pkgcode = 'pkgcode'" to the database. "FormViewDataSource.SelectParameters.Add(New QueryStringParameter("pkgcode", pkgcode))" will give you, for example, "SELECT PackageName, Channel, PackageCode FROM DACPkgs WHERE Pkgcode = 5", which is probably what you want.

MORE CURLY FRIES
Apr 8, 2004

Does anyone know a good crash course in xml data sources for c# .net?

I'm wanting to store some user preferences, mainly a folder name and some file extensions, so that users can have some rules based on file extension to move those files to given folders.

So I want an xml file which has the folder, then a csv set of extensions for it, then I want to get the folder name, iterate through the extensions and see whether they match. Once I know how to read, write and stuff with xml then it shouldn't be too hard, but I'm somewhat lost on how to do it.

Edit:

Ok ignore this, I found a decent enough one here which will let me do what I want to, so it's all gravy.

MORE CURLY FRIES fucked around with this message at 17:25 on Apr 19, 2008

Gumbos
Jul 1, 2003

Oh gosh that's funny. That's really funny. Do you write your own material? Do you?
I am taking an introductory class in .net with C++. I am trying to write a simple program to calculate the total cost for a house based on a variable amount of watts and hours/day from user input.
Right now I have an input box for each the watts and hours. There is a button that when pressed adds the watts and hours to an array of system objects from another class. All of this works perfectly, but after I wrote that I realized that I don't know how to make the array of systems accessible to a different event handler, which would be required in order to read every point on the array and calculate a total bill.
How can I access the array from another event handler? Or how is this problem circumvented?

Pivo
Aug 20, 2004


Pivo posted:

Can anyone think of a reason why WPF would stop updating the screen?
:words:

By the way we fixed this, it was hardware issues. WPF won't throw an exception if hardware rendering fails all of a sudden.

Factor Mystic
Mar 20, 2006

Baby's First Post-Apocalyptic Fiction
How would I use GetProcessIoCounters in C#? I can import the function simply enough with
code:
[DllImport("kernel32.dll")]
static extern bool GetProcessIoCounters(IntPtr hProcess, out IO_COUNTERS lpIoCounters);
but I can't figure out IO_COUNTERS. MSDN shows what it would be in C++ (?),
code:
typedef struct _IO_COUNTERS {
  ULONGLONG ReadOperationCount;
  ULONGLONG WriteOperationCount;
  ULONGLONG OtherOperationCount;
  ULONGLONG ReadTransferCount;
  ULONGLONG WriteTransferCount;
  ULONGLONG OtherTransferCount;
} IO_COUNTERS, 
 *PIO_COUNTERS;
but I don't know how to translate this to C#. Just making a struct with ulong's was my best guess, but it doesn't seem to be working. Pinvoke.net has nothing. Ideas?

Jethro
Jun 1, 2000

I was raised on the dairy, Bitch!

Factor Mystic posted:

How would I use GetProcessIoCounters in C#? I can import the function simply enough with
code:
[DllImport("kernel32.dll")]
static extern bool GetProcessIoCounters(IntPtr hProcess, out IO_COUNTERS lpIoCounters);
but I can't figure out IO_COUNTERS. MSDN shows what it would be in C++ (?),
code:
typedef struct _IO_COUNTERS {
  ULONGLONG ReadOperationCount;
  ULONGLONG WriteOperationCount;
  ULONGLONG OtherOperationCount;
  ULONGLONG ReadTransferCount;
  ULONGLONG WriteTransferCount;
  ULONGLONG OtherTransferCount;
} IO_COUNTERS, 
 *PIO_COUNTERS;
but I don't know how to translate this to C#. Just making a struct with ulong's was my best guess, but it doesn't seem to be working. Pinvoke.net has nothing. Ideas?
That should be what you want. Did you try giving the struct a [StructLayout(LayoutKind.Sequential)] attribute?

gibbed
Apr 10, 2006

Wouldn't that just be
code:
[StructLayout(LayoutKind.Sequential)]
struct IO_COUNTERS
{
    UInt64 ReadOperationCount;
    UInt64 WriteOperationCount;
    UInt64 OtherOperationCount;
    UInt64 ReadTransferCount;
    UInt64 WriteTransferCount;
    UInt64 OtherTransferCount;
}
From windows platform SDK headers:
code:
typedef unsigned __int64    ULONGLONG;

dwazegek
Feb 11, 2005

WE CAN USE THIS :byodood:

gibbed posted:

Wouldn't that just be...
ulong and System.UInt64 are the same thing.

Belgarath
Feb 21, 2003
I'm doing some html screen scraping in C#, and while the actual screen scraping, retrieving the html and extracting content/data from the page isn't a problem, I am struggling with something.

This is in a win forms project, and specifically, the problem is that the page I am interested in scraping has four parts, in a tabbed layout. Scraping the data for the initially selected tab is not a problem as I've said, but I can't quite figure our how to get to the second (or third or fourth) tab programmatically. The tab is changed with a javascript function, which populates the tab dynamically - the data isn't already on the page, it's fetched when the tab is selected.

How can I post back to the website's url that I've "clicked" on the link to change the tab, and get the data back?

poopiehead
Oct 6, 2004

You could probably try installing the livehttpheaders firefox addon. Click on the link and watch the http messages. Then you'll see the kind of message that needs to be sent.

poopiehead fucked around with this message at 17:45 on Apr 20, 2008

csammis
Aug 26, 2003

Mental Institution

Factor Mystic posted:

Pinvoke.net has nothing. Ideas?

Don't forget to add it when you get it figured out :eng101:

gibbed
Apr 10, 2006

dwazegek posted:

ulong and System.UInt64 are the same thing.
I prefer to be explicit when working with interop or raw data.

Factor Mystic
Mar 20, 2006

Baby's First Post-Apocalyptic Fiction
Here's the project, with ulong's changed to UInt64's for the sake of explicitness. Each field of info is 0 every time, when I can clearly see the correct values in Process Explorer. Weirdly, when stepping through, sometimes error_code is 0 (apparently indicating success), but info is still full of 0's. So then I though there might be some handle weirdness, but replacing this.handle with the return of FindWindow or GetForegroundWindow or any of those changes nothing.

code:
        [DllImport("kernel32.dll")]
        static extern bool GetProcessIoCounters(IntPtr hProcess, out IO_COUNTERS lpIoCounters);

        [StructLayout(LayoutKind.Sequential)]
        struct IO_COUNTERS
        {
            public UInt64 ReadOperationCount;
            public UInt64 WriteOperationCount;
            public UInt64 OtherOperationCount;
            public UInt64 ReadTransferCount;
            public UInt64 WriteTransferCount;
            public UInt64 OtherTransferCount;
        }
        
        IO_COUNTERS info;

        private void button1_Click(object sender, EventArgs e)
        {
            if (GetProcessIoCounters(this.Handle, out info) == false)
            {
                int error_code = Marshal.GetLastWin32Error();
                if (error_code != 0) Debug.WriteLine((new Win32Exception(error_code)).Message);
            }
            else
            {
                Debug.WriteLine(info.ReadOperationCount);
            }
        }

        public Form1()
        {
            InitializeComponent();
        }
I bet it's something dumb I'm missing.

MORE CURLY FRIES
Apr 8, 2004

How do I get a C# application to publish with an extra file dependency?

I've got a rules.xml file which I want to be attached to the project, but when I go to publish it it isn't there. I added the file on the "resources" pane, but no joy.

mlnhd
Jun 4, 2002

Factor Mystic posted:

Here's the project, with ulong's changed to UInt64's for the sake of explicitness. Each field of info is 0 every time, when I can clearly see the correct values in Process Explorer. Weirdly, when stepping through, sometimes error_code is 0 (apparently indicating success), but info is still full of 0's. So then I though there might be some handle weirdness, but replacing this.handle with the return of FindWindow or GetForegroundWindow or any of those changes nothing.

code:
        [DllImport("kernel32.dll")]
        static extern bool GetProcessIoCounters(IntPtr hProcess, out IO_COUNTERS lpIoCounters);
I bet it's something dumb I'm missing.
Check the docs for GetProcessIoCounters. hProcess is a handle to the process, not its main form or anything else.
Your call should look like:
code:
GetProcessIoCounters( Process.GetCurrentProcess().Handle, out info )

mlnhd fucked around with this message at 21:40 on Apr 20, 2008

Factor Mystic
Mar 20, 2006

Baby's First Post-Apocalyptic Fiction

Melonhead posted:

Check the docs for GetProcessIoCounters. hProcess is a handle to the process, not its main form or anything else.
Your call should look like:
code:
GetProcessIoCounters( Process.GetCurrentProcess().Handle, out info )

Haha, I'm retarded, thanks. I was going over it and over it, but sometimes, your eyes just skip over the key parts. Even the parameter definition is "hProcess". Thank you.

uXs
May 3, 2005

Mark it zero!

MORE CURLY FRIES posted:

How do I get a C# application to publish with an extra file dependency?

I've got a rules.xml file which I want to be attached to the project, but when I go to publish it it isn't there. I added the file on the "resources" pane, but no joy.

There's a "Copy to output directory" property for files, maybe that'll work.

memknock
Jul 4, 2002
Could someone point me towards a good example for using a checkbox inside the properygrid as a pop up dialog box.

memknock fucked around with this message at 19:03 on Apr 21, 2008

Begby
Apr 7, 2005

Light saber? Check. Black boots? Check. Codpiece? Check. He's more machine than kid now.
I am printing to a Zebra thermal printer directly on the network using EPL2. I do something like this

code:
// Open a connection to the printer
TcpClient printer = new TcpClient(hostName, IP_PORT);

// Get a stream
NetworkStream strm = printer.GetStream();

// Send stuff that I created earlier with a stringbuilder
strm.Write(sendBytes, 0, strLength);

strm.Close();
printer.Close();
My labels print out all beautiful, so well that it makes me horny....

However, is there a way I can check to see if the printer is alive and responsive so that I can show a meaningful error? I would like to test if the IP is on the network and reachable, then also check if the port is available or in use by someone else or whatever, then wait for a little bit and try again.

This is the first time I have every worked with IP stuff in code.

Richard Noggin
Jun 6, 2005
Redneck By Default
Can't you just catch the SocketException that's thrown if the connection fails?
http://msdn2.microsoft.com/en-us/library/115ytk56.aspx

Begby
Apr 7, 2005

Light saber? Check. Black boots? Check. Codpiece? Check. He's more machine than kid now.

Richard Noggin posted:

Can't you just catch the SocketException that's thrown if the connection fails?
http://msdn2.microsoft.com/en-us/library/115ytk56.aspx

Holy poo poo you are smart! Thanks.

Richard Noggin
Jun 6, 2005
Redneck By Default

Begby posted:

Holy poo poo you are smart! Thanks.

Actually, I'm probably the stupidest .NET guy here. I just happened to use similar code last week. :smith:

Z-Bo
Jul 2, 2005
more like z-butt
So, yesterday was my first day using Visual Studio. I swear, today is my last.

Unfortunately, I still have to develop a prototypical WPF Browser Application.

All I really need to do in order to uninstall Visual Studio is learn how to compile XAML from the command line. I've tried searching for a XAML Command Line Compiler, but it seems MS deprecated two such tools (camlc.exe and ac.exe) during Longhorn development. It seems MSBuild is the only way to go, but I've never even used MSBuild. Can someone point me to information on how to compile XAML with MSBuild and bypass these worthless code generated "Solutions" Visual Studio provides?

csammis
Aug 26, 2003

Mental Institution

Z-Bo posted:

Can someone point me to information on how to compile XAML with MSBuild and bypass these worthless code generated "Solutions" Visual Studio provides?

shaim compiles its WPF projects on the command line all the time...by pointing msbuild at the worthless code-generated .csproj for the WPF project in question. It would really help to know what you're having problems with instead of grandiose bitching about Visual Studio. Are you trying to do something like take a loose XAML file and turn into an EXE?

IAmKale
Jun 7, 2007

やらないか

Fun Shoe
I'm having a bitch of a time figuring out how to dynamically add "sub items" to a ContextMenuStrip ToolStripMenuItem.



Whenever a user adds a new item to the list box shown on the left, I want to dynamically add all the list items as options in a "sub menu" of the "Items" menu Item. "Stufffffff" would be the first item on this "sub menu", and additional items would go beneath it.

I've figured out how to add additional items underneath "Items", but nothing I've read helps me dynamically add options as a branch of that menu item. Any ideas on how I can do this? By the way, I'm using C#.

Cancelbot
Nov 22, 2006

Canceling spam since 1928

I'm currently having problems with master pages not behaving at all (or at least how I would think they would behave)

I have a master page with a DropDownList used to determine which subsection to load, the problem being that the control isn't remembering its viewstate after a postback and any attempts to set it manually are resulting in no values being set or null reference exceptions when trying to get the list from a child page.

The DropDownList is as follows:

code:
<li><label>Type: </label>
                <asp:DropDownList runat="server" ID="list_expenseType" AutoPostBack="true" 
                    onselectedindexchanged="list_expenseType_SelectedIndexChanged">
                    <asp:ListItem Value="0">-</asp:ListItem>
                    <asp:ListItem Value="1">Mileage</asp:ListItem>
                    <asp:ListItem Value="2">Car Parking</asp:ListItem>
                    <asp:ListItem Value="2">Car Hire</asp:ListItem>
                    <asp:ListItem Value="2">Congestion Charge</asp:ListItem>
                    <asp:ListItem Value="2">Taxi Fares</asp:ListItem>
                    <asp:ListItem Value="2">Traim / Tram / Tube Fares</asp:ListItem>
                    <asp:ListItem Value="2">Air Fares</asp:ListItem>
                </asp:DropDownList>
            </li>
Now on postback the masterpage reads the control successfully (from the list_expenseType_selectedIndexChanged event) but nothing happens at all on Page_Load) and for some reason it wont read the SelectedIndex property into a session variable so I can restore the selected item. I have also tried doing this on a child page;

code:
DropDownList findBox = (DropDownList)Master.FindControl("list_expenseType");
Response.Write(findBox.SelectedItem.Text);
Which again produces no result or a null reference.

The masterpage & mastertype properties are specified in all child pages.

To summarise:

Listbox selected (not in a content placeholder) -> Postback -> List is reset to item 0 rather than the item previously selected.

SLOSifl
Aug 10, 2002


Karthe posted:

I've figured out how to add additional items underneath "Items", but nothing I've read helps me dynamically add options as a branch of that menu item. Any ideas on how I can do this? By the way, I'm using C#.
Sorry if I'm misunderstanding, but ItemsMenu.DropDownItems.Add ( ... ) is probably what you want.

IAmKale
Jun 7, 2007

やらないか

Fun Shoe

SLOSifl posted:

Sorry if I'm misunderstanding, but ItemsMenu.DropDownItems.Add ( ... ) is probably what you want.
Perfect, that was exactly what I was looking for! Thanks!

Biscuit Hider
Apr 12, 2005

Biscuit Hider
I'm having a bitch of a time trying to get some data out of the database. Let me try to explain what I mean and hopefully someone can help me. I am about to go insane :(. (Please do not criticize me for the DB stuff, I am working with a legacy system)

I have a table whose primary key is "Marketing_Campaign_Id". The datatype on this field is Binary(8).

code:
select Marketing_Campaign_Id from Marketing_Campaign

result:  0x00000000000000AF
code:
select Cast(Marketing_Campaign_Id as BigInt) from Marketing_Campaign

result: 1365
There is a query that is hard coded into this third party vendor solution we use that runs the query without a cast, and in the resulting DataSet, that column is a byte[] array with 8 indexes that look like this:

code:
byte[0] = 0
byte[1] = 0
byte[2] = 0
byte[3] = 0
byte[4] = 0
byte[5] = 0
byte[6] = 0
byte[7] = 175
How in the world do I take that byte array and make it equal to 1365, the same as if I had cast the result in the select statement?

mantaworks
May 6, 2005

by Fragmaster
175 in decimals is AF in hex, so that's correct. I have no clue how your program comes up with the int 1365. But then again I don't really have to deal with that kind of stuff.

mantaworks
May 6, 2005

by Fragmaster
-doublepost-

Biscuit Hider
Apr 12, 2005

Biscuit Hider

mantaworks posted:

175 in decimals is AF in hex, so that's correct. I have no clue how your program comes up with the int 1365. But then again I don't really have to deal with that kind of stuff.

The "program" doesnt come up with 1365, MS SQL does. Doing "Select Cast(Marketing_Campaign_Id as BigInt) from Marketing_Campaign returns 1365

SLOSifl
Aug 10, 2002


Can you put try some other numbers to see if you can find a pattern?

Some good test numbers would be 0, 1, 2, 1000, etc.

Grigori Rasputin
Aug 21, 2000
WE DON'T NEED ROME TELLING US WHAT TO DO
Blah, I can't get a validator to work for my listbox. Basically, the listbox starts out empty and I populate it with names. The way it should work is that if it's empty it should fail and if it has items.count > 1 it should work. It pushes data through every time regardless of the listbox's status.

Here's the code:

code:
                    <asp:CustomValidator runat="server" ID="ValidatePolicyNames" ControlToValidate="lbx_PolicyNames" ErrorMessage="you messed up!"
                        display="dynamic" ValidateEmptyText="false" OnServerValidate="Validate_Policy_Names"> </asp:CustomValidator>


    Protected Sub Validate_Policy_Names(ByVal source As Object, ByVal args As ServerValidateEventArgs)
        Trace.Warn("This should wooooooooooooork")

        If Me.lbx_PolicyNames.Items.Count > 0 Then
            args.IsValid = True
        Else
            args.IsValid = False

        End If


    End Sub

Biscuit Hider
Apr 12, 2005

Biscuit Hider

SLOSifl posted:

Can you put try some other numbers to see if you can find a pattern?

Some good test numbers would be 0, 1, 2, 1000, etc.

Sorry, you lost me. Where do you want me to try those test numbers at?

SLOSifl
Aug 10, 2002


In the database. Whatever column you are getting 1365 from. I'm curious what the value of 0 or 1 look like in the byte array.

Adbot
ADBOT LOVES YOU

Z-Bo
Jul 2, 2005
more like z-butt
In WPF, how do I declare a CustomViewSource in XAML for a run-time data resource, like the results of a SQL query? I want strongly typed access to my run-time data resource, but can't come up with the correct syntax so that I can:

1) Define a class implementing IObservableCollection<Person> in a code-behind file (I can do this)

2) Define an instance of that class in the code-behind file and have strongly typed direct access to it in the XAML file (I don't know if this is possible)
3) Do everything related to rendering in the XAML file, such as:
3a) defining a CustomViewSource with CustomViewSource.GroupDescriptions
3b) for GroupDescriptions, automatically convert fields like DateTime to Date or an enumeration like "Today", "Last Week", "Older than a week".
3c) have the DataTemplate data bind to the CustomViewSource by resource key

It seems like right now if I can figure out 2), then 3) should become very easy. I know I can define an event handler in XAML and have strongly typed access to it in the code-behind, but what I want to do is define the data model in the code-behind and have strongly typed access to it in the XAML file.

Has anyone here leveraged XAML this way? Right now, I am a XAML pup, I've been programming in it for a week, but I'm finding that it's more intuitive to just define in procedural code stuff like the 3 items listed above. In fact, it's the only way I've been able to get it to work. Yet, I really want to push everything except for the Data Model into the XAML file. From a purist/idealistic perspective, stuff like how I want the DataTemplate to render should be defined only in XAML.

Z-Bo fucked around with this message at 15:46 on Apr 25, 2008

  • Locked thread