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
Hey!
Feb 27, 2001

MORE MONEY = BETTER THAN
Sorry, I'm not quite sure that's what I'm asking. Let me flesh it out more:

Let's say I have a ToDoList class. It has two members, an array of type ToDoItem called ToDoItemArray, and a string called CurrentItemName.

ToDoItem only has one member, ItemName, a string.


Now let's say I want to show every ToDoItem in every ToDoList. That's simple, I just have a GridView bound to the ToDoLists, and inside of that, a repeater bound to the ToDoItemArray:
code:
<asp:GridView runat="server" DataSource='<%# ToDoLists %>'>
  <Columns>
    <asp:TemplateField>

      <asp:Repeater runat="server" DataSource='<%# Eval("ToDoItemArray") %>'>
          <ItemTemplate> Eval("ItemName") </ItemTemplate>
      </asp:Repeater>

    </asp:TemplateField>
  </Columns>
</asp:GridView>
But say I want to show every ToDoItem in every ToDoList, plus I want to highlight the current item in every ToDoList. But I can't do that because the CurrentItemName property of the ToDoList is outside the "scope" of the Repeater's ItemTemplate. The Repeater is bound to an array of ToDoItems, it doesn't know anything about a ToDoList at all. It can't get a handle on which ToDoList the GridView is currently binding to, in order to get the correct CurrentItemName.

Sorry for the contrived example, it was the best I could think of.

Adbot
ADBOT LOVES YOU

wwb
Aug 17, 2004

Hmm, possibly the best way to handle this would be to upgrade the repeater to a user control. That user control would take a datasource property, which could be Container.DataItem. Then you could bind the repeater to the ToDoArray and have access to the item to do lookups against.

Dromio
Oct 16, 2002
Sleeper
I've got a new hosted application coming out that uses both an ASP.NET site (with web services and pages) AND an svn server. One system can host multiple copies of this application. I have a windows service which spawns svn server processes for each copy of the application.

Management wants to charge customers based on bandwidth. So I need to track bandwidth usage per application -- both what's going out through ASP.NET and each svn server.

I'm at a loss on how to do this. I suppose if I try hard enough I can figure out how to get the bandwidth usage per application, but I'm really lost on how to tell what's passed back and forth through the svn server(s). Anyone have any ideas?

Inquisitus
Aug 4, 2006

I have a large barge with a radio antenna on it.
OK, WPF noob question:

How would I go about making a WPF form in XAML that actually looks like a normal Windows form, with the correct visuals for the current visual style? Furthermore, is there an easy way to convert an existing Windows Forms form into XAML (at least partially)?

The Chive
Nov 7, 2003

Alea iacta est!

Hey! posted:

Sorry, I'm not quite sure that's what I'm asking. Let me flesh it out more:

Let's say I have a ToDoList class. It has two members, an array of type ToDoItem called ToDoItemArray, and a string called CurrentItemName.

ToDoItem only has one member, ItemName, a string.


Now let's say I want to show every ToDoItem in every ToDoList. That's simple, I just have a GridView bound to the ToDoLists, and inside of that, a repeater bound to the ToDoItemArray:
code:
<asp:GridView runat="server" DataSource='<%# ToDoLists %>'>
  <Columns>
    <asp:TemplateField>

      <asp:Repeater runat="server" DataSource='<%# Eval("ToDoItemArray") %>'>
          <ItemTemplate> Eval("ItemName") </ItemTemplate>
      </asp:Repeater>

    </asp:TemplateField>
  </Columns>
</asp:GridView>
But say I want to show every ToDoItem in every ToDoList, plus I want to highlight the current item in every ToDoList. But I can't do that because the CurrentItemName property of the ToDoList is outside the "scope" of the Repeater's ItemTemplate. The Repeater is bound to an array of ToDoItems, it doesn't know anything about a ToDoList at all. It can't get a handle on which ToDoList the GridView is currently binding to, in order to get the correct CurrentItemName.

Sorry for the contrived example, it was the best I could think of.

Why can't the Repeater control have access to its parent which you would cast to the GridView and then get the property you need?

Small
Aug 18, 2005

I've finished a prototype for someone on Rent A Coder in C# written in VS2005. I've never redistributed a .NET app before. I built in the Release configuration and sent him the executable from the Release folder. He says that nothing happens when he clicks on it. I compiled the default Windows Application and that does run for him.

I tested on another computer, without development tools installed, and it worked there. Since the empty form project ran, does that mean that he has .NET 2.0 installed for sure? I'm using the Microsoft.Office.Interop.Word and .Excel assemblies -- I referenced the Office 11 versions in my project but the other computer I tried only has Office 10 and it still ran (and the client has Office 11). I had him install the Redistributable Primary Interop Assemblies as well, just in case, but that didn't help either.

Is there any easy way to remotely figure out what's preventing my program from starting? What kinds of problems can make a .NET app not even open?

jwnin
Aug 3, 2003
Sounds like he doesn't have VSTO installed, and that you're probably swallowing an exception somewhere.

http://www.microsoft.com/downloads/details.aspx?FamilyID=f5539a90-dc41-4792-8ef8-f4de62ff1e81&DisplayLang=en

Small
Aug 18, 2005

All my exception-handling blocks create messageboxes, and I have them around everything that interacts with Office. I had a friend run the app and he got an unhandled "System.io.filenotfound" exception before the program even had a chance to do anything, though, so I guess the client could just have the exceptions supressed somehow.

I'll have him install the VSTO -- though I just developed this as a pure Windows application and just added the references to the Interop assemblies manually. I figured all I needed was the PIA.

Thanks for the tip. The client's in India (and they're outsourcing to the US?!) so I won't know whether this worked for a while.

Dude Koz
Dec 8, 2004
Women have nice parts.
I have an HTTPWebRequest question from the System.Net Namespace.

So I have a URL that I'm hitting in my web browser, and it returns just fine in about 1 second. I hit the exact same URL with my request object and it throws an exception that claims the operation has timed out. I even made the timeout up to 60 seconds, and still no dice.

This code works with the majority of URLs, but for some reason I've hit a few that just don't want to come back.

Something is clearly going wrong here, but I've never had this problem before with the browser working and the object not. I'm thinking it might have something to do with redirection?? Any insight would be most appreciated.

note: VB.NET
code:
try
   dim request as HttpWebRequest = HttpWebRequest.Create(URL)
   request.Timeout = 60000
   dim response as HttpWebResponse = request.GetResponse()
catch ex as System.Net.WebException
   dim response as httpWebResponse = ex.response
end try
return response
Thanks!

Update: I'm hitting several URLs from the same domain in a row. My boss says that IIS can do some non-standard things like trying to maintain state as it expects you to make another request. His best guess is some network timing issue. Still haven't solidified anything yet.

Update: So if I hit the same URL 8 times in succession, it succeeds the first two times, and the final 6 fail. Question now is if there's a way to "reset" in some fashion so that I can keep making httpwebrequests.

Dude Koz fucked around with this message at 16:27 on Sep 18, 2007

Richard Noggin
Jun 6, 2005
Redneck By Default

Dude Koz posted:

I have an HTTPWebRequest question from the System.Net Namespace.


note: VB.NET
code:
try
   dim request as HttpWebRequest = HttpWebRequest.Create(URL)
   request.Timeout = 60000
   dim response as HttpWebResponse = request.GetResponse()
catch ex as System.Net.WebException
   dim response as httpWebResponse = ex.response
end try
return response

You're not supposed to use the HttpWebRequest constructor. http://msdn2.microsoft.com/en-us/library/system.net.httpwebrequest(VS.71).aspx

Try

code:
try
   dim request as HttpWebRequest = [b]WebRequest.Create[/b](URL)
   request.Timeout = 60000
   dim response as HttpWebResponse = request.GetResponse()
catch ex as System.Net.WebException
   dim response as httpWebResponse = ex.response
end try
return response

fankey
Aug 31, 2001

Dude Koz posted:

I have an HTTPWebRequest question from the System.Net Namespace.

So I have a URL that I'm hitting in my web browser, and it returns just fine in about 1 second. I hit the exact same URL with my request object and it throws an exception that claims the operation has timed out. I even made the timeout up to 60 seconds, and still no dice.

This code works with the majority of URLs, but for some reason I've hit a few that just don't want to come back.

Something is clearly going wrong here, but I've never had this problem before with the browser working and the object not. I'm thinking it might have something to do with redirection?? Any insight would be most appreciated.

note: VB.NET
code:
try
   dim request as HttpWebRequest = HttpWebRequest.Create(URL)
   request.Timeout = 60000
   dim response as HttpWebResponse = request.GetResponse()
catch ex as System.Net.WebException
   dim response as httpWebResponse = ex.response
end try
return response
Thanks!

Update: I'm hitting several URLs from the same domain in a row. My boss says that IIS can do some non-standard things like trying to maintain state as it expects you to make another request. His best guess is some network timing issue. Still haven't solidified anything yet.

Update: So if I hit the same URL 8 times in succession, it succeeds the first two times, and the final 6 fail. Question now is if there's a way to "reset" in some fashion so that I can keep making httpwebrequests.

Try playing with System.Net.ServicePointManager.MaxServicePointIdleTime. I had an issue talking to an embedded web server that didn't play nicely with persistent connections. The first connection would work but the next one to the same server would fail since the embedded server had decided to close the connection. Setting that value to something less than the embedded servers concept of persistent fixed the problem.

Dude Koz
Dec 8, 2004
Women have nice parts.

Dude Koz posted:

I have an HTTPWebRequest question from the System.Net Namespace.

So I have a URL that I'm hitting in my web browser, and it returns just fine in about 1 second. I hit the exact same URL with my request object and it throws an exception that claims the operation has timed out. I even made the timeout up to 60 seconds, and still no dice.

This code works with the majority of URLs, but for some reason I've hit a few that just don't want to come back.

Something is clearly going wrong here, but I've never had this problem before with the browser working and the object not. I'm thinking it might have something to do with redirection?? Any insight would be most appreciated.

note: VB.NET
code:
try
   dim request as HttpWebRequest = HttpWebRequest.Create(URL)
   request.Timeout = 60000
   dim response as HttpWebResponse = request.GetResponse()
catch ex as System.Net.WebException
   dim response as httpWebResponse = ex.response
end try
return response
Thanks!

Update: I'm hitting several URLs from the same domain in a row. My boss says that IIS can do some non-standard things like trying to maintain state as it expects you to make another request. His best guess is some network timing issue. Still haven't solidified anything yet.

Update: So if I hit the same URL 8 times in succession, it succeeds the first two times, and the final 6 fail. Question now is if there's a way to "reset" in some fashion so that I can keep making httpwebrequests.
Thanks guys I appreciate the help!

The issue seemed to be response streams that were left open...I'm guessing that the server only allows so many per client.

I needed to do a "response.Close()" to cleanup correctly. Since it is all synchronous, this should be fine.
The code is now:
code:
try
   dim request as HttpWebRequest = HttpWebRequest.Create(URL)
   request.Timeout = 60000
   dim response as HttpWebResponse = request.GetResponse()
   if response isNot Nothing
     response.Close()
   end if
catch ex as System.Net.WebException
   dim response as httpWebResponse = ex.response
    if response isNot Nothing
     response.Close()
   end if
end try
return response
Thanks again!

Inquisitus
Aug 4, 2006

I have a large barge with a radio antenna on it.

Inquisitus posted:

OK, WPF noob question:

How would I go about making a WPF form in XAML that actually looks like a normal Windows form, with the correct visuals for the current visual style? Furthermore, is there an easy way to convert an existing Windows Forms form into XAML (at least partially)?
Surely someone knows how to do this? :confused:

Boogeyman
Sep 29, 2004

Boo, motherfucker.

Dude Koz posted:

Thanks guys I appreciate the help!

The issue seemed to be response streams that were left open...I'm guessing that the server only allows so many per client.

I needed to do a "response.Close()" to cleanup correctly. Since it is all synchronous, this should be fine.

What's the error you're getting? If it's saying "The underlying connection was closed: A connection that was expected to be kept alive was closed by the server.", then it's some retarded problem with making subsequent requests and keepalives. Here's the easy way to fix it.

code:
Dim req As HttpWebRequest = CType(WebRequest.Create("http://www.blowme.com/default.aspx"), HttpWebRequest)

With req
  .Timeout = 60000
  .ConnectionGroupName = Guid.NewGuid.ToString
End With

Dim resp As HttpWebResponse

Try
  resp = CType(req.GetResponse, HttpWebResponse)
Catch ex As WebException
  ' Oh poo poo, something bad happened
Finally
  If resp IsNot Nothing Then
    resp.Close
  End If
End Try
Setting the connection group name to a random value ensures that it won't try to reuse that connection in the future.

Aimee
Jan 2, 2007

I'm working on a website for a company that sells a bunch of machine parts. Each machine part has different sizes and variations. On the products listing page (which is an online shopping system), I am supposed to have a dropdownlist for each product with the size, weight, and whatever other information might be associated with it. The way the layout was handed off to me it's sort of like a multi-columned dropdownlist.

I did a little research with Google and found that sure, there are a ton of these .NET controls available, like Telerik's RadComboBox, but they all cost $300-$700.

Are these controls overpriced? Is it actually easy to display a multi-column data set inside a dropdownlist?

Before I decided to start looking for controls, I was generating the textfield for the dropdownlist dynamically and calculating the spaces necessary based on the length of each value. I think that's very sloppy though and I'd like to avoid it if I can.

I've also looked at some prewritten, already compiled free controls out there that do this but they all seem to not work properly or are not implemented very nicely like this.

Any ideas?

wwb
Aug 17, 2004

Would something like this work? If not, I would go with the telerik or ComponentArt controls as they tend to be the better ones out there with decent support. Code project is very, very buyer beware these days as they have no quality control over what goes up there.

uXs
May 3, 2005

Mark it zero!
I am co-developing a fairly large intranet application. There are a number of pages where users do data entry, and obviously I'm doing several checks on the data before committing it.

I want the app to show the user in what fields an error was found, so I'm showing a little image next to those fields. They have a tooltip with the error message in it. There's also an area at the top of the page where all the error messages are shown as well.

We're using a custom control to handle the display of the images and the error area on top of the page.

Unfortunately, because we need to keep track what fields are giving the errors, the actual error checking is done in the aspx.cs-page of every entry form. I don't like this and would prefer it to be done somewhere else, in the objects themselves or a business rules tier or whatever. The error checking would work just fine there, but I have no idea what the best way would be to store in what fields the errors have occured.

Anyone here has a brilliant idea that doesn't involve storing too much extra data on what entry field correlates with what property of a business object ?

Aimee
Jan 2, 2007

wwb posted:

Would something like this work? If not, I would go with the telerik or ComponentArt controls as they tend to be the better ones out there with decent support. Code project is very, very buyer beware these days as they have no quality control over what goes up there.

I thought of using the AJAX CascadingDropDown control, but was told that the data values share a 1:1 relationship(in other words, there are no cases where someone will pick value A and somehow end up with two possible value Bs, so if I have a list variations of a product with attributes like Size, Weight, A, B, and R, the end user needs to be able to see all 5 of those things at once from the start.

But thanks for the help. I may end up having to go with the Rad controls after all. I just wanted to be sure that there wasn't some awesome free alternative out there that I could use before giving my boss the bad news that we'd have to pay $300 for a single control that we may not reuse in the future.

Dromio
Oct 16, 2002
Sleeper

uXs posted:

I am co-developing a fairly large intranet application. There are a number of pages where users do data entry, and obviously I'm doing several checks on the data before committing it.

Isn't that what validation server controls are for? You put a validator control on the page, point it to the input control (textbox, listview, whatever), and it handles the rest. You can even provide a ValidationSummary on the page to show all the errors in one place.

The default ones validate against a range, regex, etc, but you can even use a CustomValidator to use your own method to validate the data.

Or, I've heard CLSA.NET thrown around a lot when it comes to business logic and validation. I haven't looked into it much, but it seems to be popular.

Dromio fucked around with this message at 18:57 on Sep 21, 2007

Dromio
Oct 16, 2002
Sleeper
I've got the following ObjectDataSource:
code:
    <asp:ObjectDataSource ID="UsageReportDataSource" runat="server"
        SelectMethod="GetRows" TypeName="UsageReportData" SortParameterName="sort">
        <SelectParameters>
            <asp:Parameter Name="sort" Type="String" DefaultValue="Date DESC" />
        </SelectParameters>
    </asp:ObjectDataSource>
It's calling this function:
code:
[DataObjectMethod(DataObjectMethodType.Select)]
    static public List<UsageReportRow> GetRows(string sort)
    {
       //Blah blah blah.
    }
But it doesn't seem to be using the default value for the sort parameter. When GetRows() is called the first time, sort is empty. Am I missing something?

atherix
Dec 20, 2005

Kiss Kiss Bang Bangalore

uXs posted:

I am co-developing a fairly large intranet application. There are a number of pages where users do data entry, and obviously I'm doing several checks on the data before committing it.

I want the app to show the user in what fields an error was found, so I'm showing a little image next to those fields. They have a tooltip with the error message in it. There's also an area at the top of the page where all the error messages are shown as well.

We're using a custom control to handle the display of the images and the error area on top of the page.

Unfortunately, because we need to keep track what fields are giving the errors, the actual error checking is done in the aspx.cs-page of every entry form. I don't like this and would prefer it to be done somewhere else, in the objects themselves or a business rules tier or whatever. The error checking would work just fine there, but I have no idea what the best way would be to store in what fields the errors have occured.

Anyone here has a brilliant idea that doesn't involve storing too much extra data on what entry field correlates with what property of a business object ?

Create custom control classes to handle the display and validation of form fields that require unique business logic be applied to them. Let's say the boss requires that dates be entered into three seperate text boxes (for month, day & year) and that all years be entered in a 4-digit format.

DON'T use 3 <asp:TextBox .. > controls and 3 <asp:CustomValidator .. > controls every time you need to collect date information. Instead, create a CUSTOM date control that contains 3 text boxes and 3 CustomValidator instances and place it in your .aspx pages using <mycontrols:ControlDate . . >

So when the boss decides he wants to have a dynamic javascript calendar instead of 3 text boxes all you have to do is update your custom Date class without altering a single .aspx file. Or, if it turns out 2-digit years are ok, you can fix that by editing just few lines of code, re-compiling your web site and volia, you're done.

atherix
Dec 20, 2005

Kiss Kiss Bang Bangalore
The ASP.NET RequiredFieldValidator control has a very annoying habit of inserting inline CSS when rendering. So the CSS class that I want to use is being overwritten:

code:
<asp:RequiredFieldValidator CssClass="FormFieldError" runat="server" id="rfvModVersion" EnableClientScript="false" ControlToValidate="ModVersion" Display="Dynamic" ErrorMessage="The version of this mod must be entered."></asp:RequiredFieldValidator>
Ends up inserting a very annoying inline CSS style. See if you can spot it:

code:
<span id="ctl00_ctl00_PageBody_CatalogContent_rfvModTitle" class="FormFieldError" style="color:Red;">Please enter the name of this mod.</span>
Do you see it? I can get the color I want if I set the ForeColor property of the RequiredFieldValidator. The thing is I then have to set the ForeColor every time I want error messages to display correctly. And I have to manually set this for hundreds of controls in the event that the color needs to change. This is an incredible waste of time. It also effectively shits all over the "Cascading" in CSS.

Roope
Dec 9, 2006
What is the recommended naming scheme for Windows Forms controls? Is the Hungarian notation still being used? I haven't done Forms programming for ages and don't have a clue how to give meaningful and short names to monsters like toolStripMenuItem1. The code looks like disgusting mess with the long default names (ButtonMenuFileStripContainerItemViewBlahBlahObjectEtc123).

uXs
May 3, 2005

Mark it zero!

Roope posted:

What is the recommended naming scheme for Windows Forms controls? Is the Hungarian notation still being used? I haven't done Forms programming for ages and don't have a clue how to give meaningful and short names to monsters like toolStripMenuItem1. The code looks like disgusting mess with the long default names (ButtonMenuFileStripContainerItemViewBlahBlahObjectEtc123).

Normally I keep the control type in front, like TextBoxTitle or DropDownListMonth or whatever. But the names of controls in a menu or statusbar become way too long that way, so I shorten those to, for example, MenuMain and MenuEdit. Or perhaps MenuItemMain and MenuItemEdit, I dunno. Definitely not the ridiculously long default names though.

uXs fucked around with this message at 13:23 on Sep 22, 2007

poopiehead
Oct 6, 2004

As much as I hate hungarian notation, I use it for naming controls.

txtName for TextBox
selState for DropDown (<select>:))
rptRows for Repeater
etc.

Roope
Dec 9, 2006

poopiehead posted:

As much as I hate hungarian notation, I use it for naming controls.

txtName for TextBox
selState for DropDown (<select>:))
rptRows for Repeater
etc.

I used this style too and quite liked it. The problem now seems to be, that there's so many controls in VS 2005, that there will be clashes in naming like lstFirstName could be ListBox or ListView or who knows what else. I remember seeing a document for VB6 years ago, which listed the recommended prefixes (lst, txt, mnu etc.) for all the controls. I wonder if MS is still publishing it for later versioins of VS? That would pretty much solve my problem.

I don't know why I pay so much attention to the naming, because it doesn't even affect how the progran works. I just want the code to look compact and clean and to be able to know the exact type of an variable just by reading its name in the code view. Coming from C/C++, the VS generated C# code (in Windows Forms) sometimes looks very ugly to me.

edit. uXs: your naming style looks nice too. I'll try something like that myself.

Roope fucked around with this message at 13:47 on Sep 22, 2007

wwb
Aug 17, 2004

I don't do winforms stuff, but hungarian notation is a tool of the devil. The only place I ever use it is for minor UI elements attached to a control--like validators or labels. Biggest issue is what happens when you realize that textbox really needs to be a drop down? Do you go and change all the calls to txtFuckup or do you leave them and make a note that txtFuckup should be ddlFuckup?

@uXs:

First, I think that trying to make the business layer directly manage UI-layer errors is a very, very difficult thing to pull off without making your core logic too dependant upon certain features of the UI. Having separate UI-layer validation vs core-logic layer validation is OK. Hell, sometimes they are eve divergent for different UIs as an application develops. The admin scripting interface might let you do things the web interface won't.

That said, there are some pretty good validation frameworks baked into things these days. I am not a huge fan of CLLA.net, but The Enterprise Library 3.0 has a very slick validation framework which feels much more flexible.

Insofar as your validators go, you can kill that font issue easily by setting the ForeColor to Transparent, which removes the color style. If you wish to get fancier and centralize control, you should check out control adapters. For a very good guide to using them, see this whitepaper.

poopiehead
Oct 6, 2004

wwb posted:

Biggest issue is what happens when you realize that textbox really needs to be a drop down? Do you go and change all the calls to txtFuckup or do you leave them and make a note that txtFuckup should be ddlFuckup?

Right Click, Refactor, Rename.

As long as it's not a public API or something that should work in most cases.

Point taken on the naming clashes, I use the prefix more as a general guide than an exact reference. I'm also guilty of using intellisense to refresh my memory if I'm not sure.

poopiehead fucked around with this message at 15:32 on Sep 22, 2007

JediGandalf
Sep 3, 2004

I have just the top prospect YOU are looking for. Whaddya say, boss? What will it take for ME to get YOU to give up your outfielders?
ASP.NET pregunta here.

I have an panel object that I use for both added and editing user details. When I edit, the textbox fields are populated with db fields. However, if I go over to add, the fields still remain populated. I've tried emptying the ViewState. I've tried disabling the View State. While that works, the TextBox fields don't contain their data for some reason.

Push comes to shove I guess I can do poo poo like this:
txtUsername.Text = string.Empty;
...

But I really don't want to end up doing that. What's a quick way of emptying out previously populated text boxes?

wwb
Aug 17, 2004

poopiehead posted:

Right Click, Refactor, Rename.

As long as it's not a public API or something that should work in most cases.

But you really should not have to do that. Moreover, with intllisense it is easy to see what type of object things are, so having to remember up-front is kind of counter productive. If I need to put that information in the ID, I usually do something like FirstNameTextBox. It makes me feel better.

@JediGandalf:

Playing with the viewstate could work if done at the right time, but you are probably going to have to just clear those values. Now, if you just want to clear all textboxes in a panel, you could do something like:

code:
foreach (Control c in MyMotherfuckingPanel)
{
   if (c is TextBox)
   {
      TextBox tb=(TextBox)c;
      tb.Text=string.Empty;
   }
}

Mecha
Dec 20, 2003

「チェンジ ゲッタ-1! スイッチ オン!」
Is there a way to order the collection you get out of a TableLayoutPanel.Controls call? When I iterate through it, it seems to give me the controls sorted by their name(since the panel only holds a bunch of radio buttons, and they're cut-n-pasted, so they basically run from "radioButton59" to "radioButton75"). Trying to rename each button manually in the designer has me cursing VS. :(

Boogeyman
Sep 29, 2004

Boo, motherfucker.
Here's a tough one. I need to connect to my DHCP server (Windows 2003 Server) from an ASP.NET web application to add/remove IP address reservations. I found an API from Microsoft that should allow me to do this kind of stuff. I'm in the process of writing all of the p/invoke code to wrap the functions, and I'm running into a problem. Here's what I have...

code:
<StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Unicode)> _
Public Structure DHCPDS_SERVER
  Dim Version As UInt32
  Dim ServerName As String
  Dim ServerAddress As UInt32
  Dim Flags As UInt32
  Dim State As UInt32
  Dim DsLocation As String
  Dim DsLocType As UInt32
End Structure

<StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Unicode)> _
Public Structure DHCPDS_SERVERS
  Dim Flags As UInt32
  Dim NumElements As UInt32
  Dim Servers As IntPtr
End Structure

Declare Unicode Function DhcpEnumServers Lib "Dhcpsapi.dll" (ByVal Flags As UInt32, _
  ByVal IdInfo As IntPtr, _
  ByRef Servers As IntPtr, _
  ByVal CallbackFn As IntPtr, _
  ByVal CallbackData As IntPtr) As UInt32

Public Shared Function EnumServers() As DHCPDS_SERVER()

  Dim retVal As UInt32 = 0
  Dim servers As IntPtr

  Try
    DhcpEnumServers(0, Nothing, servers, Nothing, Nothing)
  Catch ex As Exception
    Throw New Exception("Error code:  " & retVal.ToString, ex)
  End Try

  If retVal = 0 And servers <> IntPtr.Zero Then
    Dim serverArray As DHCPDS_SERVERS = _
      CType(Marshal.PtrToStructure(servers, GetType(DHCPDS_SERVERS)), DHCPDS_SERVERS)

    Dim serverList(CType(serverArray.NumElements, Int32)) As DHCPDS_SERVER

    Dim current As IntPtr = servers

    For i As Int32 = 0 To CType(serverArray.NumElements - 1, Int32)
      serverList(i) = CType(Marshal.PtrToStructure(current, GetType(DHCPDS_SERVER)), DHCPDS_SERVER)

      Marshal.DestroyStructure(current, GetType(DHCPDS_SERVER))

      current = IntPtr.op_Explicit(current.ToInt64() + Marshal.SizeOf(serverList(i)))
    Next

    Marshal.FreeCoTaskMem(servers)

    Return serverList
  ElseIf retVal = 0 And servers = IntPtr.Zero Then
    Throw New Exception("No servers found.")
  Else
    Throw New Exception("Error code:  " & retVal.ToString)
  End If

End Function
When I call the function above, I get to the line where it tries to assign a value to serverList(i), then it bombs out hardcore and gives me the following error:

quote:

The runtime has encountered a fatal error. The address of the error was at 0x7a0b6759, on thread 0x9e0. The error code is 0xc0000005. This error may be a bug in the CLR or in the unsafe or non-verifiable portions of user code. Common sources of this bug include user marshaling errors for COM-interop or PInvoke, which may corrupt the stack.

I'll admit right now that I know jack poo poo about p/invoke and unmanaged code, so I'm assuming that I'm not marshaling the array properly. I'm using the library documentation from above to convert the function definitions, and I used this article to create the code that (attempts to) map the array of servers to a managed array of DHCPDS_SERVER. Any ideas as to what I'm doing wrong?

EDIT: loving HURRRRRRRRRRRRRRRRRR. I made a stupid mistake. Changing

code:
Dim current As IntPtr = servers
to

code:
Dim current As IntPtr = serverArray.Servers
fixed the problem. The pointer in the first one points to the DHCPDS_SERVERS structure instead of the array of DHCPDS_SERVER that it contains.

Boogeyman fucked around with this message at 18:54 on Sep 25, 2007

wwb
Aug 17, 2004

^^^Not exactly sure, but have you seen PInvoke.net?

GI_Clutch
Aug 22, 2000

by Fluffdaddy
Dinosaur Gum
Is there a quick and easy way to generate a single XML element? I need to generate some XML that is then later copy/pasted into an existing XML document that is generated by a third party application. Currently, I just use the XMLTextReader to do this. I make a bogus root element, and with a For Each loop I cycle through the rows of a table and spit out the elements into an xml file. Then I just open up the xml file I created and copy and paste the necessary rows where they need to go.

I'd rather just be able to generate an element on the fly. I'm trying to make this helper tool a little more robust. For example, I'd like to just highlight an item in a listbox, and then boom, the element would appear in a textbox. Like, I would click 'Apples' and '<item id="apples" price="1.00" />' would appear in the textbox. Obviously, I can't just do something along the lines of "<item id=""" & itemname & """ price=""" & price & """ />" because depending on the characters, it could totally blow up the XML.

Any ideas? This is a winform app in VB.Net. I apologize if there is some simple solution out there. I'm not the biggest XML champion out there, and I've tried googling a few things with no luck,

Dude Koz
Dec 8, 2004
Women have nice parts.
WinForms Auto Scrolling Question.

I have a ListView and I'm trying to find the first Checked Item and scroll down to it. I thought you do this with the AutoScrollOffset Method, but it doesn't want to work. Anyone know what's wrong?

Note: This is VB.NET

code:
dim pos as System.Drawing.Point = ListView.CheckedItems(0).Position
ListView.AutoScrollOffset = pos   
Thanks!

Dude Koz
Dec 8, 2004
Women have nice parts.

Dude Koz posted:

WinForms Auto Scrolling Question.

I have a ListView and I'm trying to find the first Checked Item and scroll down to it. I thought you do this with the AutoScrollOffset Method, but it doesn't want to work. Anyone know what's wrong?

Note: This is VB.NET

code:
dim pos as System.Drawing.Point = ListView.CheckedItems(0).Position
ListView.AutoScrollOffset = pos   
Thanks!

Found a solution:

ListView.CheckedItems(0).EnsureVisible()

This method will ensure that the item is visible, even if it involves scrolling.

Atimo
Feb 21, 2007
Lurking since '03
Fun Shoe
I need a method of consuming web services, and have spent all day google searching without an answer.

I fear I am going to be clumsy trying to describe this so bear with me.

I am designing an nteir business app, so I need a layer that sits between the UI and the phyiscal business layer.

It's defined like so:

code:
public class EmployeeFacade : FacadeParent<IEmployeeAPI>
{...}
The IEmployeeAPI interface defines things like GetAllEmployees ect. The CRUD stuff.
An example:
code:
public class EmployeFacade...
...
        public StaffLynx.EmployeesDataTable GetList()
        {
            DataTable table = [b]apiMethod.GetAllEmployees()[/b].Tables[0];
            StaffLynx.EmployeesDataTable employees = new StaffLynx.EmployeesDataTable();
            employees.Merge(SetDataSetSchema(employees.TableName, employees.Columns, table));
            return employees;
        }
....
The FacadeParent class is defined:

code:
    public class FacadeParent<ApiInterface>
    {
        protected ApiInterface apiMethod;
        public FacadeParent()
        {
            this.InitAPIMethod(System.Configuration.ConfigurationManager.AppSettings[this.GetType().Name]);
        }
        private void InitAPIMethod(string apiClassName)
        {
            PortChooser<ApiInterface> port = new PortChooser<ApiInterface>(apiClassName);
            apiMethod = port.GetDefaultPort();
        }
So basically, create a method of communicating with an generic interface.


Here is the PortChooser object:

code:
    public class PortChooser<ApiInterface>
    {
        private string apiUrl="";
        public PortChooser(string apiName)
        {
            apiUrl = apiName;
        }
        public ApiInterface GetDefaultPort()
        {
            string defaultPortKey = System.Configuration.ConfigurationManager.AppSettings["DefaultPort"];

            switch (defaultPortKey)
            {
                case "WCF": 
                    return new Skeletron.Common.ConnectToWCFService<ApiInterface>().GetService(ConfigurationManager.AppSettings["WCF_URLBASE"] + apiUrl);
                case "WebService":
                    return new Skeletron.Common.ConnectToWebService<ApiInterface>().GetService(ConfigurationManager.AppSettings["WEBSERVICE_URLBASE"] + apiUrl + ".asmx");
            }
            throw new Exception("No default Port was found, unable to connect to middle teir.");
        }
    }
It is using a defined value for which communication model to use, WCF or WebService.


Here is the problem -

In WCF all you need to do is create a ChannelFactory, pass in the Interface you want (thats hosted somewhere else the "WCF_URLBASE + apiUrl") and you get back the apprioprate object. In the example facade you'd get back a refrence to the WCF end point.

Like so:
code:
    public class ConnectToWCFService<GenericInterface>
    {
        public GenericInterface GetService(string url)
        {
            WSHttpBinding dataBinding = new WSHttpBinding();
            EndpointAddress dataAddress = new EndpointAddress(url);
            ChannelFactory<GenericInterface> dataChannelFactory = new ChannelFactory<GenericInterface>(dataBinding, dataAddress);
            return dataChannelFactory.CreateChannel();
        }
    }
I cannot seem to find a similar method for WebServices. Almost every example involves using a strongly typed Proxy class, which doesnt fit into my Generic's model here.

Can you consume a web service with just the Url and a common interface?

Can you see a way to make it *somehow* work in my framework?

Is my framework inherantly flawed, and can you suggest a diffrent track perhaps?


Oh, one more point. The channel factory does NOT throw errors if you pass it the Webservice url in the ConnectToWFCService class. Everything is peachy until you acutally try to make a call on the object, where it always returns "405 -HTTP Error 405 Method not allowed"

Atimo fucked around with this message at 22:49 on Oct 3, 2007

chocojosh
Jun 9, 2007

D00D.
Hopefully this hasn't already been asked/answered elsewhere (I don't have search yet..).

How do we programmatically access assemblies (in a format similar to what is provided by ILDASM)? I want to build a program (this program doesn't need to be in .NET per se), that can load an assembly, and be able to retrieve the text for different classes/methods, and then do some basic parsing.

Is it possible to say retrieve the IL code for a specific function/class in an assembly?

SLOSifl
Aug 10, 2002


GI_Clutch posted:

Any ideas? This is a winform app in VB.Net. I apologize if there is some simple solution out there. I'm not the biggest XML champion out there, and I've tried googling a few things with no luck,
What type of data source are you using? If it's MS SQL, you can have it spit out the results in XML to begin with if you want. (Look up FOR XML) If you need a specific format, you can control it through the query.

Or you can just create an XmlDocument and create elements using code like this:
code:
XmlDocument doc = new XmlDocument ();

doc.LoadXml ( "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Whatever></Whatever>" );

XmlNode node = doc.CreateElement ( "Something" ); 
node.InnerText = "What";

XmlAttribute att = doc.CreateAttribute ( "Nipples" );
att.Value = "Yep";
node.Attributes.Append ( att );

doc.AppendChild ( node );
node.OuterXml would be something like:
<Something Nipples="Yep">What</Something>

Adbot
ADBOT LOVES YOU

jwnin
Aug 3, 2003

chocojosh posted:

Hopefully this hasn't already been asked/answered elsewhere (I don't have search yet..).

How do we programmatically access assemblies (in a format similar to what is provided by ILDASM)? I want to build a program (this program doesn't need to be in .NET per se), that can load an assembly, and be able to retrieve the text for different classes/methods, and then do some basic parsing.

Is it possible to say retrieve the IL code for a specific function/class in an assembly?

You should take a look at reflector http://www.aisto.com/roeder/dotnet/. He does what you seem to want to do, so while it doesn't solve your problem it should be doable by an independent party.

The tool is named appropriately, as it seems you want to go after Reflection: http://msdn2.microsoft.com/en-us/library/f7ykdhsy.aspx

  • Locked thread