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
poopiehead
Oct 6, 2004

Victor posted:

Mods: please fix the post icon.

In Part I, we discussed how the ASP.NET engine munges control IDs with runat="server" when they are nested inside another control, whether it be a datagrid, a content section of a master page, or a control in a user control. This causes problems for javascript and CSS that target tags based on IDs. To some extent, this can be solved by doing
code:
<%=lblWhatever.ClientID%> {font-weight: bold;}
and
code:
someInitFunction($(<%=btnWhatever.ClientID%>));
Is this the accepted way to do things? Unless it's safe to depend on a mangled ID, it would appear that styling elements with runat="server" based on ID in a separate CSS file isn't possible; is this true?

I tend to just use a unique class name. It's ugly, but it works.

Adbot
ADBOT LOVES YOU

poopiehead
Oct 6, 2004

Sorry this is going to be long:

I'm getting a weird error in an ASP .NET 2.0 page....

This only happens in IE7. Fine in firefox and IE6.

error posted:

Invalid postback or callback argument. Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.

I have a repeater control with a bunch of child controls in the item template:
code:
<table class="layout">
<asp:Repeater ID="pagesDisplay" runat="Server" OnItemCreated="listing_ItemCreated">
  <ItemTemplate>
    <tr >
      <td class="bioListRow">
        <asp:Image ID="imgThumb" runat="server" style="float: left;" />
      </td>
      <td class="bioListRow">
        <strong><asp:Literal ID="lblName" runat="server" /></strong><br />
        <asp:Literal ID="lblTitle" runat="server" ><br /></asp:Literal>
        <asp:Literal ID="lblDescription" runat="server" ><br /></asp:Literal>
        <asp:LinkButton ID="btnMoreInfo" runat="server" 
                                OnClick="btnMoreInfo_Click">
                                  More Information
                                </asp:LinkButton>
      </td>
    </tr>
    <tr><td></td></tr>
    <asp:HiddenField ID="hdFacultyID" runat="server" />
  </ItemTemplate>  
</asp:Repeater>
</table>
And here is most of the codebehind. In the page_load, I databind the control. In the item_created event, I set up all the controls in the itemTemplate. In the button click, I just need to find out which one was clicked and redirect.
code:
    protected void Page_Load(object sender, EventArgs e)
    {
    Util.SetNavScript(this.Master, "mNav", "dist", "dist", null);

    BLL.FacultyTypeIdent pageType;
    bool isDefault = false;
    switch (Request["pageType"])
    {
      case "faculty":
        pageType = BLL.FacultyTypeIdent.Faculty;
        break;
      case "secondary":
        pageType = BLL.FacultyTypeIdent.SecondaryFaculty;
        break;
      case "visiting":
        pageType = BLL.FacultyTypeIdent.VisitingScholars;
        break;
      case "adjunct":
        pageType = BLL.FacultyTypeIdent.AdjunctProfessors;
        break;
      case "staff":
      case "researcher":
        pageType = BLL.FacultyTypeIdent.Staff;
        break;
      case "associate":
        pageType = BLL.FacultyTypeIdent.FacultyAssociates;
        break;
      default:
        pageType = BLL.FacultyTypeIdent.Faculty;
        isDefault = true;
        break;
    }

    using (DAL.DataConnector conn = new DAL.DataConnector())
    {
      BLL.FacultyType facType = 
        new BLL.FacultyType(conn, pageType);
      this.lblTitle.Text = facType.DisplayName;

      BLL.FacultyCollection fac =  
        BLL.Faculty.FetchVisibleRowsByFacultyType(conn,pageType);
      pagesDisplay.DataSource = fac;
      pagesDisplay.DataBind();

      this.pnlMainPage.Visible = false;
      if (isDefault)
      {
        this.pnlMainPage.Visible = true;
        this.visitingDisplay.DataSource = 
          BLL.Faculty.FetchVisibleRowsByFacultyType(conn, 
            BLL.FacultyTypeIdent.VisitingScholars);
        this.visitingDisplay.DataBind();
      }
    }
    }

  protected void listing_ItemCreated(object sender, RepeaterItemEventArgs e)
  {
    Control cont = (Control)e.Item;
    Literal name = (Literal)cont.FindControl("lblName");
    Literal description = (Literal)cont.FindControl("lblDescription");
    Literal title = (Literal)cont.FindControl("lblTitle");
    Image thumb = (Image)cont.FindControl("imgThumb");
    HiddenField facultyID = (HiddenField)cont.FindControl("hdFacultyID");

    BLL.Faculty fac = (BLL.Faculty)e.Item.DataItem;
    if (fac != null)
    {

      name.Text = fac.Name;

      string shortDesc = fac.ShortDesc;
      if (shortDesc != null && shortDesc.Length > 0)
      {
        System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(
          "</?([^>]*)>",
          System.Text.RegularExpressions.RegexOptions.IgnoreCase |
            System.Text.RegularExpressions.RegexOptions.Multiline);
        shortDesc = regex.Replace(shortDesc, " ");

        int oldShortDescLength = shortDesc.Length;

        shortDesc = shortDesc.Substring(0, Math.Min(400, shortDesc.Length));
        if (oldShortDescLength > 400)
        {
          shortDesc += "...";
        }
        description.Text = shortDesc + description.Text;
      }
      else
      {
        description.Visible = false;
      }

      if (fac.Title != null && fac.Title.Length > 0)
      {
        title.Text = fac.Title + title.Text;
      }
      else
      {
        title.Visible = false;
      }      


      facultyID.Value = fac.ID.ToString();



      bool thumbExists = false;
      thumb.Visible = false;
      if (fac.Thumbnail != null)
      {
        string filepath = thumbnailLocation + fac.Thumbnail;
        if (System.IO.File.Exists(Server.MapPath(filepath)))
        {
          thumb.ImageUrl = resizerPrefix + filepath;
          thumb.Visible = true;
          thumbExists = true;
        }
      }

      if (!thumbExists && fac.Image != null)
      {
        string filepath = imageLocation + fac.Image;
        if (System.IO.File.Exists(Server.MapPath(filepath)))
        {
            thumb.ImageUrl = resizerPrefix + filepath;
            thumb.Visible = true;
        }
      }
    }
    
  }

  protected void btnMoreInfo_Click(object sender, EventArgs e)
  {
    HiddenField hf = (HiddenField)((Control)sender).Parent.FindControl("hdFacultyID");
    int id = int.Parse(hf.Value);
    Response.Redirect("FacultyBio.aspx?id=" + id, true);
  }
After doing some reading on the error, it seems that the problem is that I'm re-databinding the control and ASP .NET doesn't like that. So if I put the databinding part inside of an if(!IsPostback), the error does go away, but then when I get to the click event, the HiddenField has no value.

I was able to avoid the problem by getting rid of the useless postback that shouldn't have been there in the first place and just making it a link.
code:
<a href="FacultyBio.aspx?id=<%# DataBinder.Eval(Container.DataItem,"ID") %>">More Information</a>
But does anyone understand what problem I was actually running into? I can't seem to figure out what I was doing wrong or how to fix it other than to disable validation.

poopiehead
Oct 6, 2004

superb0wr posted:

Anybody know what those [SquareBracket] directives or whatever you can use in c# are called, and if its possible to write custom ones? Like [STAThread] or [WebMethod]?

They're called Attributes and they're accessible through Reflection.

I've never used them before, but this looks like a good explanation:

poopiehead
Oct 6, 2004

csammis posted:

String.IsNullOrEmpty() :eng101:

Isn't there some kind of bug associated with that function? It seems so convenient but I've been nervous to use it since I heard it doesn't always work.

poopiehead
Oct 6, 2004

Victor posted:

The bug has to do with JITing code in loops; it isn't a problem with String.IsNullOrEmpty itself. If you don't use the method in loops, you're golden, otherwise you might want to look up the bug details.

Thanks. good to know. I'll have to look up the details.

poopiehead
Oct 6, 2004

Heffer posted:

Here's example #1 of how things could go wrong. Say you have a table that contains a field for an ID number (2 bytes) a date (8 bytes) and the file itself (32,000 bytes). The rows for the table ordinarily get stored consecutively on the disk, and the database only keeps track of where the first row is, apart from indexes and such.

You want to do a simple thing, like get the file that was uploaded at a specific date. The database reads the first chunk of the table at 64KB per read. The first read gets it two rows to check. Neither match. It goes back to the disk and reads the next 64K. Neither of the new ones match. It does this for 1000 times. It's read 64 megabytes of your disk, looking for a single 32K file out of two thousand.

If you had done this by storing the 240 character filename instead of the actual file, you read 2000 * 250 = 500KB, which only takes 8 read operations instead of 1000.


Wouldn't this be solved by having an an index on the date field? Then it just has to read through the index which is something like 10 bytes per entry. If you're already inserting large files into the database, you're probably not worried about the overhead of an index.

I can see where example 2 makes sense though.

poopiehead
Oct 6, 2004

In C# ASP .NET 2.0, is there a way to get a mime type from a file extension. I've seen one way by searching through the registry, but I was hoping there was a less hackish way....

Any ideas?

poopiehead
Oct 6, 2004

Grid Commander posted:

Yes, figure out what each file formats' header is. Most binary files have special header at the top of the file. It will be different for different file types. It will be stored at a different location for each file type. It will likely be stored in the first 12 bytes of the file.

The registry is easier, but can sometimes "lie" since you are just checkng for file associations instead of actually using the semantics of the file itself to check its type.

For a good example look up most unix file types, or look at the bitmap or jpeg file formats.

Have fun.

Thanks for the info.

What I, and I'm assuming Grid Commander, are looking for is to return the same Content-Type header as the web server would for a given file. Servers just look up extensions in a table they have and return the associated content type. I probably didn't make that clear in the original question.

In my case, what I'm trying to do is dynamically serve up files through a server side script. I'll know the extension that the file originally had, so I'd like to get the content type from that. I can store the content type when the files are uploaded, but would rather avoid it.

poopiehead fucked around with this message at 07:55 on Jan 13, 2007

poopiehead
Oct 6, 2004

Frank Butcher posted:

I'm thinking of starting to programme in C# instead of VB. I have a large VB project and was wondering if it's possible to begin writing new classes (or even forms) in C# within this project? I heard that all code compiles the same so I was wondering if it's possible.

Besides what was already mentioned, there are a bunch of guidelines that you should follow to make sure that they will work across all languages. This has nothing to do with internal code, only externally accessible things. The most important thing would be to not have identifiers in C# differ only by case, because VB wouldn't be able to make sense of it.

I couldn't find a good link but found this from an old class web page.
guidelines

poopiehead
Oct 6, 2004

Mind Riot posted:

Reposting from another thread:

I've got a program I've been working on that I'm developing a very basic Login control for, and I'm trying to keep the control as reusable as possible.

Now I want the program to be able to set the login control to use one of the program's own functions to validate the username and password, instead of building that logic into the control itself.

I'm doing this in C#, so I believe I need to use a delegate, but I'm really not to sure how it'd work in this situation. Any ideas?

I can see two ways that are pretty much the same.

1) Add a TryLogin event to the login control. The implementing page can add a delegate to the event. When a login is attempted, fire the event and pass a reference to the login control as a parameter. Then the delegate can set a public IsLoggedIn or LoggedInUerId property when it gets called.

2) Create a delegate. Something with a signature like "bool TryLogin(string username,string pass)". Then have a public property of the type of that delegate. The implementing page can set the property. When a user attempts to log in, use the provided delegate to perform the login.

poopiehead
Oct 6, 2004

wwb posted:

^^^Those are basically the same thing. The event is essentially a specifically formed delegate.

poopiehead posted:

I can see two ways that are pretty much the same.

;)

poopiehead
Oct 6, 2004

Grid Commander posted:

On a side note -- I think it might be possible to host php on IIS? There might even be a php variant that targets MSIL. I didn't research that much though, so I can't say for sure.

It can definitely be installed on IIS.

http://www.php.net/downloads.php

edit:

the above link is just to run on windows. The cgi version is what runs on IIS:

http://us2.php.net/security.cgi-bin

poopiehead fucked around with this message at 21:16 on Jan 18, 2007

poopiehead
Oct 6, 2004

Essential posted:

Hey all I have some very basic Asp.net questions (I just started getting into Asp.net but I have a vb6/vb.net 2005 background). I have been using vs 2005 for the last 2 years or so.

I'm having a hard time finding an online tutorial that explains how to design and set up a good web form. It's easy for desktop apps, either I use the visual designer or use code to place objects.

So now trying to build decent looking web apps I'm not sure how to place stuff on the form. I'm pretty sure it has to be done in code, not sure if it's done in style sheets, or in the <form></form> code or in the <div> code <asp:button maybe location stuff goes here??>? One of the tutorial's I went through had me adding stuff with a table object, but I thought that table's were not to be used nowadays?

What's making things harder is I'm picturing my web app to look almost identical to my desktop app but I know that the look will change drastically, I just can't help but see it that way.

I understand about master pages and that seems to work good for the menu but it's placing all the labels,text boxes, etc. that I'm having trouble with.

I'm not sure I'm making much sense here so I think I can sum it up with: How do I align stuff up and make everything look pretty and does anyone have a screenshot of a webapp they have created that is similar to a desktop app?

Are you familiar with HTML? I've never seen an editor for web pages that works like the VS Form Designer and actually works well.

poopiehead
Oct 6, 2004

Essential posted:

Also I must be a real jerk to not realize I would need html/css for formatting

I think MS did intend for people to use the designer, especialy coming from an app dev point of view. So it wasn't a ridiculous assumption. You definitely need to know HTML to work with it effectively, though.

I like w3schools for quick overviews. Here's a tutorial

I'd definitely try to get to the point where I can lay out a simple flat web page in html before diving into asp .net. Most introductory asp .net stuff assumes programming experience, which you do have, and html experience, which you will.

poopiehead
Oct 6, 2004

pliable posted:

That didn't work, since DocumentElement is a property :(. Is it a method in Visual Basic? I'm not very familiar with VB, so.


Booyah, loving perfect. I love you guys :).

EDIT: Ah ballhair, one more question...

If no inner text was present (ex: <BallSack></BallSack>), and currentNode.InnerText was called...what in the gently caress does it return? I tried doing an if statement to test and see if it was and empty string or null, and it's apparently none of them.

I'm confused :psyduck:.

It should be an empty string.

code:
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication12
{
	class Program
	{
		static void Main(string[] args)
		{

			string xml = @"<Ball>
   <Sack>
      <BallSack></BallSack>
      <BallSack>nuts lol</BallSack>
   </Sack>
</Ball>";

			System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
			doc.InnerXml = xml;

			foreach (System.Xml.XmlNode node in doc.SelectNodes("//BallSack"))
			{
				Console.WriteLine(node.InnerText.Length);
				Console.WriteLine(node.InnerText.Equals(string.Empty));
				Console.WriteLine(node.InnerText.Equals(""));
			}

			Console.Read();
		}
	}
}
output:
code:
0
True
True
8 
False
False

poopiehead
Oct 6, 2004

Jethro posted:

Book Question:

I'm sure this has been asked before, but it's kinda difficult to search for c#, being two characters and all.

I'm looking for a good C#/.NET book, or other resource. Pretty much all of my programming would be for use with my company's SharePoint server. As far as my programming experience goes:
  • I have a little bit of C experience, so I'm at least a little bit comfortable with C/C++ syntax
  • I do plenty of .bat scripting; I have a little bit of perl
  • I used to do a lot of mIRC scripting
  • I took Pascal way back in high school
  • I sometimes hack away at PHP
I don't really have much experience in the way of OOP, though I kinda have a basic idea of the concepts behind it. Encapsulation makes at least a little sense to me. Inheritence and polymorphism less so: I kinda know what they are, but I don't totally understand when and why you use them.

So, as I mentioned before, I was looking for a book. Does anyone have any experience with Learning C# 2005: Get Started with C# 2.0 and .NET Programming? Would my lack of OOP knowledge make this a good book for me, or would people suggest just diving right in to Programming C#, or is there a better book that you would suggest?



Progamming C# might be a bit tough with no OO experience. I've heard good things about(but have not read myself) Learning C# for less OOP experienced people.

poopiehead fucked around with this message at 20:19 on Jan 22, 2007

poopiehead
Oct 6, 2004

I'm trying to make the defaultbutton for a textbox be a linkbutton. Sounds simple enough, but not really. There seems to be a bug(or at least weird feature) in ASP .NET that makes this not possible on firefox. Looking at their JS, they try to use the defaultbutton's click() method which firefox doesn't define for anchor tags.

This script fixes it so that there is a click method.
code:
var el = document.getElementById('<%=btnSearch.ClientID %>');
if(!el.click)
el.click = eval( "function (){  " + el.href.substring(11) + "; }")
In the linkbutton, the generated code has href="java script:__do_postback(....)", so I just grab that and call it.

Is there anything wrong with this besides the fact that if MS changes their LinkButton Control, then my code might die?

poopiehead
Oct 6, 2004

Goonamatic posted:

I just use my function


public static void SetDefaultButton(TextBox textBox, Button button)
{
textBox.Attributes.Add("onkeypress", "checkEnter('" + button.ClientID.ToString() + "', event);");

StringBuilder sb = new StringBuilder();

sb.Append("function checkEnter(btn, event)");
sb.Append("{");
sb.Append(" if (document.all)");
sb.Append(" {");
sb.Append(" if (event.keyCode == 13)");
sb.Append(" {");
sb.Append(" var o = document.getElementById(btn);");
sb.Append(" event.returnValue=false;");
sb.Append(" event.cancel = true;");
sb.Append(" o.click();");
sb.Append(" }");
sb.Append(" }");
sb.Append(" else if (document.getElementById)");
sb.Append(" {");
sb.Append(" if (event.which == 13)");
sb.Append(" {");
sb.Append(" var o = document.getElementById(btn);");
sb.Append(" event.returnValue=false;");
sb.Append(" event.cancel = true;");
sb.Append(" o.click();");
sb.Append(" }");
sb.Append(" }");
sb.Append(" else if (document.layers)");
sb.Append(" {");
sb.Append(" if(event.which == 13) ");
sb.Append(" {");
sb.Append(" var o = document.getElementById(btn);");
sb.Append(" event.returnValue=false;");
sb.Append(" event.cancel = true;");
sb.Append(" o.click();");
sb.Append(" }");
sb.Append(" }");
sb.Append("}");

textBox.Page.ClientScript.RegisterClientScriptBlock(textBox.Page.GetType(), "CheckEnter", sb.ToString(), true);
}

Thanks for that. I think I'll end up using this cases when I don't want to use a Panel to set the DefaultButton because it renders a div tag that may mess with layout.

My current problem is with LinkButton though, which renders as something like this:
<a href="java script:__doPostBack('ct100_btn','')">Go</a>

MS's implementation of DefaultButton in 2.0 lets you choose a linkbutton as the default button but it tries to use the click() method to click it. That's fine in IE, but firefox doesn't have a click() method on the <a> tag object.

poopiehead
Oct 6, 2004

havelock posted:

Unless I missed something, that string is static. There's no reason not to just use a literal for it. Even if you break it up on multiple lines.
string s = "line 1 " +
"line 2 " +
"line 3 ";

The compiler is smart enough to assemble one monster string for you.

Also using @"" works great for those situations because then you can read your javascript relatively easily.

code:
string js = @"
  function checkEnter(btn, event)
  {
    if (document.all)
    {
      if (event.keyCode == 13)
      {
        var o = document.getElementById(btn);
        event.returnValue=false;
        event.cancel = true;
        o.click();
      };
    }
  }";
That does make the file a bit bigger with all the spacing though.

poopiehead
Oct 6, 2004

marcan posted:

C# newb here (I've used C, Java, and others, but this is the first time I mess with C#)

I'm having threading troubles. I'm trying to build an app to read data from a serial port and update a bunch of controls on a form in real time. In my current setup, a separate thread does the reading, and after processing it ends up calling Invoke on the form to run the GUI update code on the GUI thread. The problem is (I believe, from what I've been able to tell using lots of debug statements) that when I close the Form, the serial code does a join on the reading thread, which sometimes (in fact, almost always) happens to be waiting for a just-queued event on the GUI for updating. Since the event is queued after FormClosing, and FormClosing waits on the other thread, the app deadlocks. Removing the join just shifts the problem from a deadlock to an exception on the Invoke, as the Form is dead by then.

Any ideas on how to avoid this situation?

<edit> Replacing Invoke with BeginInvoke seems to work fine. Any other suggestions, or is this fine?



You also might find the Abort method of the Thread class. When you start the thread, save the object and on FormClosing, call Abort. (never used the abort method myself but it looks like what you need)

poopiehead
Oct 6, 2004

Essential posted:

So would you typically set up your session objects in the Global.asax file?

No need. Just do:
Session["asdadad"] = anyobject;
in any page.

If you end up keeping things all in the same page, then Viewstate is better as long as you're not trying to save huge things.

I generally use Viewstate and a bunch of panels based on what I want to display in these kinds of cases, though the WizardView is probably better. I just never used it before.

poopiehead
Oct 6, 2004

Essential posted:

I want to see if I get this right. You might have, say a home page panel, a products page panel and a contact us panel and just load/show whatever panel based on where the user wants to go? And all these panels are on one page? If that's the case does this make for a faster site?

Not exactly. Home and products would be separate pages. My products page would most likely accept a product ID in the query string from a normal link on another page. If I was using something other than a link, like a select box to get to the product page, then I would use Response.Redirect() to get to the product page.

I'm having trouble coming up with a good example for a single page that could be multiple page...... Let's assume you have a mortgage calculator. The first page is a form to fill out your financial stuff and the second is to display some graphs or something of ways to pay off your mortgage or whatever. Assume the form is really long, so it wouldn't look good if you just put the forms and graphs on the same page. I'll probably have two panels. One for the form and one for the graphs. Initially, the graphs are not visible and the form is visible. On postback, I do processing and then toggle the visibility of each panel so that only the graphs are showing.


quote:

The other thing they want is in depth knowledge of asp.net 2.0 page lifecycle. Are they refereing to "state" issues or page_init, page_load type stuff? Any ideas?

They most likelye mean page_init, page_load etc. They also might be interested in if you know the order in which child controls get their events fired(wrt to parents) or how master pages fit into the picture.

poopiehead
Oct 6, 2004

Essential posted:

Referring to master pages though, you mean how a master page is used to set up a consistent default look, with respect to header, footer and menu navigation (as well as anything else you want to set up). Then you add content pages that use the master page as the parent page and add your page specific interface into the ContentControl? (I think it's called ContentControl)

Exactly, but I meant the order in which events fire on the master page. Like does the load of the master page or the page get called first. And then also do the load events of child controls get called before or after their parents' loads. I'm not sure of the answer without looking it up but figured that may be a question they'd ask when they specifically mentioned they want you to already know the page lifecyle.

poopiehead
Oct 6, 2004

Victor posted:

These are considered tips and are very welcome as far as I'm concerned. Just a thought: if they're preceded by Tip: or something like that, a script could be written to aggregate them.

Or even better, put them inside [tip][/tip] tags. That way a script would only grab the tips and not the rest of the post, like Fiend's edit.

poopiehead
Oct 6, 2004

Nurbs posted:

If I use an sqlcommand object and add parameters, how can I make the value of a parameter null? I want to update a field to null or insert nothing (and I have a fixed amount of data, I don't want to dynamically build the command text)

Just add a null value. I forget the exact syntax but:

code:
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "InsertPossiblyNull";
cmd.Parameters.Add(new SqlParameter("@name",null));
cmd.ExecuteNonQuery();
For a stored procedure:

code:
CREATE PROCEDURE InsertPossiblyNull
@name varchar(20) = NULL
AS
INSERT INTO SomeTable
(name)
VALUES
(@name)
edit: in this example, you don't even have to actually add the parameter because the default would be null. But that should cover what you need to do anyway.

poopiehead
Oct 6, 2004

Nurbs posted:

Thanks.

edit:

I do need to add parameter because I can't say insert this parameter if it isn't there?

I'm getting this error:

System.Data.SqlClient.SqlException was unhandled
Message="Parameterized Query '(@ID uniqueidentifier,@name nvarchar(36),@organizationTypeID uni' expects parameter @description, which was not supplied."

commandtext is

selectStatement = "SELECT ID FROM tableOrganization WHERE name = @name AND description = @description AND websiteAddress = @websiteAddress AND organizationTypeID = @organizationTypeID";

for an executescalar operation. (I'm checking to see if it already exists)

The following sets all the defaults. I have IF statements that change the values of the null parameters to data if its available. In the case of this error, these are all null.
sqlCommand.Parameters.AddWithValue("@ID", mediusOrganizationID);
sqlCommand.Parameters.AddWithValue("@name", emcOrganizationName);
sqlCommand.Parameters.AddWithValue("@organizationTypeID", mediusOrganizationTypeID);
sqlCommand.Parameters.AddWithValue("@creationDate", DateTime.Now);
sqlCommand.Parameters.AddWithValue("@creationUser", CommonVariables.userName);
//
sqlCommand.Parameters.AddWithValue("@description", null);
sqlCommand.Parameters.AddWithValue("@websiteAddress", null);
sqlCommand.Parameters.AddWithValue("@bsrNumber", null);
sqlCommand.Parameters.AddWithValue("@notes", null);

try adding System.DBNull.Value. (again I'm probably off a bit with the spelling/name.).

sqlCommand.Parameters.AddWithValue("@notes", System.DBNull.Value);

poopiehead
Oct 6, 2004

Fiend posted:

I'm using C# & VS 2005.

I have a method that returns an XmlDocument object from data in a database, and is sorted by the Price node by default. I'd like a method to sort the xml document by name or description, but haven't had a lot of luck so far.
code:
<root>
    <node>
        <item id="34334343434">
            [b]<price>333.33</price>[/b]
            <name>Cave Bat</name>
            <description></description>
        </item>
        <item id="34343433">
            [b]<price>343.43</price>[/b]
            <name>Fruit Bat</name>
            <description>Looks like a flying leprechaun</description>
        </item>
        <item id="34343434">
            [b]<price>434.34</price>[/b]
            <name>Spooky Bat</name>
            <description>I'm afraid of scary bats</description>
        </item>
    </node>
</root>
Can anyone come up with a code snippet that will do what I need it to do?

2 options I can think of. both pretty much suck.

1. Use XSL which supports sorting to make a new XML document.

2. Implement a sorting algorithm on your own and just move around the nodes.

poopiehead
Oct 6, 2004

Heffer posted:

It could be a fixed with column. Depending on your database, that could mean it pushed out a lot of blank characters after your text to fill it up to the fixed width. Just trim it and forget about it.

Just to clarify..... If you have a column of type char(x), it is always x characters long with extra whitespace to reach that size. varchar(x) will only be as long as it needs to be up to length x. (There are other fixed with types also but it sounds like you're dealing with char)

poopiehead
Oct 6, 2004

The reason it's easy to get from a file upload control is that the browser sends a mime type as part of the http post when you fill in a file form field. So that's not really available in a .NET application.

This is what I'm using. The second function is the only one that's actually necessary. The other was just to cache the results.
code:
public class MimeTranslator
{
    private static System.Collections.Generic.Dictionary<string, string> MimeTypes = 
        new System.Collections.Generic.Dictionary<string, string>();
    private MimeTranslator()
    {
    }

    public static string GetMimeType(string extension)
    {
        extension = extension.ToLower();
        if (!extension.StartsWith("."))
        {
            extension = "." + extension;
        }
        if (!MimeTypes.ContainsKey(extension))
        {
            MimeTypes[extension] = GetRegistryMimeType(extension);
        }
        return MimeTypes[extension];
    }

    private static string GetRegistryMimeType(string extension)
    {
        extension = extension.ToLower();

        RegistryKey key = Registry.ClassesRoot.OpenSubKey("MIME\\Database\\Content Type");

        foreach (string keyName in key.GetSubKeyNames())
        {
            RegistryKey temp = key.OpenSubKey(keyName);
            if (extension.Equals(temp.GetValue("Extension")))
            {
                return keyName;
            }
        }
        return "";
    }

}

poopiehead fucked around with this message at 00:32 on Feb 8, 2007

poopiehead
Oct 6, 2004

This is probably more of a haus of tech support question, but people here are more likely to know.

How do you uninstall an add-in from VS .NET 2005?

The VMWare add-in, which I don't use doesn't like Vista, so I need to get rid of it.

I know I can hold the left shift button when starting up to have it not load, but I was hoping to just make it go away.

poopiehead
Oct 6, 2004

shelleycat posted:

Could it be that someInt++ is of type int. int is not a boolean, and cannot be equated to boolean in C#. (someInt++ == 0) would be a boolean result.

I cannot be bothered to try this, because the construction like you are using makes my simple head hurt. I would do it with ifs.

Victor already answered the actual question, but to answer yours. The ternary operator requires that the 1st operand is a boolean and that the second two operands are of the same type of each other, but not necessarily the same as the first.

poopiehead
Oct 6, 2004

With C#, is there a way to listen on a port that's already being listened to by a windows service or something?

It's a long story, but I wrote a program to run on a VM to let it work as a proxy for the host machine to talk to the VPN. It works perfectly for a bunch of ports, but if I need to pass on RPC port(TCP 135) to a machine on the VPN, it won't let me listen because windows is already listening on the port.

Now is there a way to intercept those packets when they come in over a certain IP? So I want to be able to listen on 169.254.80.32:135 without otherwise interfering with windows. (that IP is a direct connection between the host and vm).

Is that possible?

EDIT: that's probably a security concern and impossible....... How about anyone know a way to switch the port before it gets there, either on the way out of the host or into the VM?

poopiehead fucked around with this message at 02:29 on Feb 23, 2007

poopiehead
Oct 6, 2004

^^^^^Do you mean something like this:

code:
    class ColorList : System.Collections.Generic.List<System.Drawing.Color>
    {

    }
(This works)

poopiehead
Oct 6, 2004

wwb posted:

I have some experience with using the where predicates. And, in most cases, you are probably better off just using (or inheriting) from a List<IWhatever> because that is what you actually want.

But then you lose the advantage of the class being generic. If you don't want a generic class, then that makes sense. But, let's say you want a list that can be cloned. You have to make sure the entries are ICloneable, and then use the Clone() method of the items in your Clone() method. But if you just do CloneableList : List<ICloneable>, then you can't use it as a generic list. You have to a lot of casting and can't guarantee that everything in the list is the same type.

poopiehead fucked around with this message at 17:07 on Feb 23, 2007

poopiehead
Oct 6, 2004

rotor posted:

This idea never occurred to me, as I've never used other languages in my c# apps. Can I use the BigInteger code from J#? And if so, how much lard will this add to the binary?

The binary just has MSIL for any language, so there shouldn't be any extra lard for using a different language.

poopiehead
Oct 6, 2004

I don't use Express, but it might have this functionality. In SQL Server Management Sudio, I right click on a database, then choose tasks, then generate scripts and you can script at least the tables and procedures. I don't think you can get data that way though. There is an export data wizard that can make a flat file, that you could then probably import to GoDaddy

poopiehead
Oct 6, 2004

Yaksha posted:

Where is the export wizard?

I was finally able to get Microsoft SQL Server Management Studio Express to open (had to uninstall everything, including the 2.0 framework, then reinstall) and while I can export my table structures, I can't get any of the data to go with it.

To restate my problem:

Visual Web Developer Express Edition creates a database file, called ASPNETDB.MDF. I can't simply upload this to GoDaddy and have everything work.

I need to be able to export all table structures (and probably all the stored procedures and such) as well as all the data to a .sql file so I can use the Query Analyzer to get all the DB data to GoDaddy.

Does anyone know I can export all of my .mdf information into a .sql file?

This might not be included on the express version.

poopiehead
Oct 6, 2004

Yaksha posted:

I do have a "Generate Scripts" option, however, this is what I did earlier and it only seemed to export the table structure, not the data. (I don't have import/export).

Perhaps there was an option I forgot to set to true? Append to file? Script Full Text Indexes?

That sounds about right. Generate Scripts can do stored procedures and tables, etc, but not the data in the tables. If you don't have an export option in that menu, you may be screwed(at least using this application)

poopiehead
Oct 6, 2004

You can just read through the stream. When you see one of the nodes you're concerned with, figure out which one they are and then get the text.

edit: this is what I mean:

code:
       enum Status
        {
            Waiting,
            Title,
            URL,
            Owner
        }

        static void Main(string[] args)
        {
            System.Xml.XmlReader reader = System.Xml.XmlReader.Create(@"C:\test.xml");

            Status theStatus = Status.Waiting;
            while (reader.Read())
            {
                switch (reader.NodeType)
                {
                    case System.Xml.XmlNodeType.Element:
                        switch (reader.Name)
                        {
                            case "Title":
                                theStatus = Status.Title;
                                break;
                            case "URL":
                                theStatus = Status.URL;
                                break;
                            case "Owner":
                                theStatus = Status.Owner;
                                break;
                        }
                        break;
                    case System.Xml.XmlNodeType.Text:
                        switch (theStatus)
                        {
                            case Status.Title:
                                Console.WriteLine("read title = " + reader.Value);
                                theStatus = Status.Waiting;
                                break;
                            case Status.URL:
                                Console.WriteLine("read url = " + reader.Value);
                                theStatus = Status.Waiting;
                                break;
                            case Status.Owner:
                                Console.WriteLine("read owner = " + reader.Value);
                                theStatus = Status.Waiting;
                                break;
                        }
                        break;
                }

            }
            Console.Read();
        }
This falls on its face if those elements have nested elements, but seems to be ok for the kind of variation you're seeing.

That said, a DOM probably won't really hurt you with such tiny XML.

poopiehead fucked around with this message at 16:39 on Mar 8, 2007

Adbot
ADBOT LOVES YOU

poopiehead
Oct 6, 2004

Qaz Kwaz posted:

Not sure what these other guys used, but when learning ASP.Net I found the Wrox Professional ASP.Net 2.0 book to be very solid. You should give it a look.

That book was very helpful to me when I had to learn ASP .NET. It's not perfect, but it's pretty drat good.

As far as data binding goes, as someone said above, in almost every case, I've gotten by with just assigning a collection of my business objects to the datasource property of the databound control.

  • Locked thread