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
MrBishop
Sep 30, 2006

I see what you did there...

Soiled Meat
This has had me scratching my head all day. I've started playing around with config files using System.Configuration. Everything's working great, except for the fact that, if I have my custom configuration section created programmatically, it doesn't write the default values I specify. Instead, it uses system defaults based on type (int's are 0, bool's are false, strings are "", etc.).

My "create" code is this:
code:
Configuration  config = ConfigurationManager.OpenExeConfiguration(
						ConfigurationUserLevel.None);
AppConfigSettings    custSection = config.GetSection( sectionName ) as AppConfigSettings;

if ( custSection == null ) {
  custSection = new AppConfigSettings();

  config.Sections.Add( sectionName, custSection );
  custSection = config.GetSection( sectionName ) as AppConfigSettings;
  custSection.SectionInformation.ForceSave = true;
  config.Save( ConfigurationSaveMode.Full );
}
A sample of a config property with a default value (maybe I'm doing it wrong?):
code:
_isEncrypted = new ConfigurationProperty(
                       "isEncrypted", 
                       typeof(bool), 
                       true, 
                       ConfigurationPropertyOptions.IsRequired );
When I save this property to my config file for the first time (it gets created), the value is saved as "false". However, if I change it in my program to "true", then save it again, it gets saved as "true". Likewise for the other properties, if I change them and save, the new values get saved. It's only my own default values that don't get saved when the section is created.

Is there a way to get it to save my defaults without re-specifying them when I create the section programmatically?

Adbot
ADBOT LOVES YOU

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



Waffle Zone posted:

I've been looking into getting a C# book and learning C# to get back into programming. It has been a few years since I've programmed anything and my experience back then only took me up to the Programming AP test (Computer Science AB I think).

Are there any good in-depth tutorials online for a novice programmer? If not, what book would you recommend?

I don't know that it's exactly what your looking for, but you can't beat the price: http://www.charlespetzold.com/dotnet/

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?
How might I be able to detect login and logout events with a service? I've been doing some poking around with WMI but it's kind of confusing to me. There an easier way or a better explained WMI way? I need this because I have to start a program after login/logout events.

I found something like this:
code:
ObjectQuery oq = new ObjectQuery("Select * From Win32_LogonSession where CachedUnlock=13");
That should supposedly get all current workstation logins.

Fiend
Dec 2, 2001
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?

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.

Fastbreak
Jul 4, 2002
Don't worry, I had ten bucks.

Fiend posted:

Can anyone come up with a code snippet that will do what I need it to do?

Just to make sure I understand what you want, you get an XML document, then you want to resort the XML document with it sorted by price?

What you would need to do is yank all the item nodes out of the document, sort them, them put them back in.

Fiend
Dec 2, 2001

poopiehead posted:

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.
I have a minor feature request that negates 1, but xsl-sortby was the first thing that came to mind.

Fastbreak posted:

Just to make sure I understand what you want, you get an XML document, then you want to resort the XML document with it sorted by price?

What you would need to do is yank all the item nodes out of the document, sort them, them put them back in.
That's exactly what I wanted...
code:
static void Main(string[] aaaaaaaaaaaarrrrrrrrrgs)
{
    XmlDocument xld = new XmlDocument();
    xld.Load(@"c:\path\to\that\xml\file\what.xml");
    Console.WriteLine("Old hawtness: " + xld.OuterXml);
    XmlDocument xldSorted = sortFlights(xld, "@id");
    Console.WriteLine("New Hawtness: " + xldSorted.OuterXml);
}
static XmlDocument sortFlights(XmlDocument getFlightsXml, string theXpathStringIWantToUse)
{
    XmlDocument xmlReturn = new XmlDocument();
    xmlReturn.LoadXml("<root><node></node></root>");
    XmlNode rootNode = xmlReturn.SelectSingleNode("root/node");
    try
    {
        // this is probably better explained somewhere in the MSDN
        XPathNavigator xNav = getFlightsXml.CreateNavigator();
        XPathExpression expr = xNav.Compile("root/node/item");
        expr.AddSort(theXpathStringIWantToUse, XmlSortOrder.Ascending, XmlCaseOrder.None, "", XmlDataType.Number);
        XPathNodeIterator iterator = xNav.Select(expr);
        while (iterator.MoveNext())
        {
            rootNode.InnerXml += iterator.Current.OuterXml.ToString();
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }
    return xmlReturn;
}
Thanks for the direction!
:bravo:

Heffer
May 1, 2003

JediGandalf posted:

How might I be able to detect login and logout events with a service? I've been doing some poking around with WMI but it's kind of confusing to me. There an easier way or a better explained WMI way? I need this because I have to start a program after login/logout events.

I found something like this:
code:
ObjectQuery oq = new ObjectQuery("Select * From Win32_LogonSession where CachedUnlock=13");
That should supposedly get all current workstation logins.

Could you watch the Security Event Log? If I recall, there are events registered each time someone logs in. There may even be a built in listener object that you can set to automatically call your function each time an event is added.

foxxtrot
Jan 4, 2004

Ambassador of
Awesomeness
I am accessing an ODBC Database using C#. The problem I'm having is that the value being pulled from the database seems to have some whitespace appended to the end of it. This is causing a later Query to fail because of the whitespace. When I run this same query through Microsoft Query, the whitespace does not appear to export. Is there something wrong with my query, or should I just trim the whitespace from the end after I build the ListBox?

code:
OdbcCommand cmd = MAS90DataConnection.CreateCommand();
cmd.CommandText = "SELECT ItemNumber FROM " + UPCTable;
OdbcDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
	MessageBox.Show("Testing: " + rdr["ItemNumber"] + ".",
           "DEBUG",MessageBoxButtons.OK);
	if (!ItemBox.Items.Contains(rdr["ItemNumber"]))
	{
		ItemBox.Items.Add(rdr["ItemNumber"]);
	}
}
ItemBox.SetSelected(0,true);

real_scud
Sep 5, 2002

One of these days these elbows are gonna walk all over you
I'm going to ask this here and pray someone can help me out, if not guess I'll stumble my way through.

I was given a task of taking our old .net template file and having it go from tables, to a more proper-semantic CSS styling.

Now I'm not much of a .net developer just a normal web front-end guy so looking at the page is a bit staggering to me.

Does anyone know of an easyish way I can easily fix up the code? Or am I going to have to stumble and bumble my way through it?

Heffer
May 1, 2003

foxxtrot posted:

I am accessing an ODBC Database using C#. The problem I'm having is that the value being pulled from the database seems to have some whitespace appended to the end of it. This is causing a later Query to fail because of the whitespace. When I run this same query through Microsoft Query, the whitespace does not appear to export. Is there something wrong with my query, or should I just trim the whitespace from the end after I build the ListBox?

code:
OdbcCommand cmd = MAS90DataConnection.CreateCommand();
cmd.CommandText = "SELECT ItemNumber FROM " + UPCTable;
OdbcDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
	MessageBox.Show("Testing: " + rdr["ItemNumber"] + ".",
           "DEBUG",MessageBoxButtons.OK);
	if (!ItemBox.Items.Contains(rdr["ItemNumber"]))
	{
		ItemBox.Items.Add(rdr["ItemNumber"]);
	}
}
ItemBox.SetSelected(0,true);

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.

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)

Heffer
May 1, 2003

real_scud posted:

I'm going to ask this here and pray someone can help me out, if not guess I'll stumble my way through.

I was given a task of taking our old .net template file and having it go from tables, to a more proper-semantic CSS styling.

Now I'm not much of a .net developer just a normal web front-end guy so looking at the page is a bit staggering to me.

Does anyone know of an easyish way I can easily fix up the code? Or am I going to have to stumble and bumble my way through it?

I'm not sure what you mean "from tables".

Generally in a proper .net web application, there will be an ".aspx" file and a ".aspx.cs" or ".aspx.vb" with that same file name. The code should lie within that .cs or .vb (the extension varies depending on the language the programmer used), and the html should lie entirely within the .aspx file.

There are two main exceptions to this rule. Sometimes people don't like to split up the files, and put their code into the .aspx file with <script language="C#"> tags or the like. Secondly, they use page directives of the format <% > or <@ > to set page settings or output values to the html page.

Now if it's designed with ASP.NET, you'll see lots of <asp:thingy > tags throughout the page, which are interpreted by the compiler to be a specific control, which in turn is converted into HTML.

In sumnmary, you can muck about in the .aspx page all you want, so long as you don't mess with <asp:thingy> tags, <%> page directives, or <script> tags.

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?

Heffer posted:

Could you watch the Security Event Log? If I recall, there are events registered each time someone logs in. There may even be a built in listener object that you can set to automatically call your function each time an event is added.
Yeah I did find something like that. Trouble is, I'm not sure if a lab computer can read the security event log.

Larger picture: Ok. This program controls three devices in the classroom: projector, audio switcher, and if equipped, a document camera. Thing is, they want it so that you can still control the devices w/o having the need to log in. In other words, the panel appears below the "press CTRL-ALT-DEL" box. I did manage to accomplish that (slightly) but I found out that it launches a 2nd process after you log in and thus the resources (COM ports) are all ready taken up by the first program. I asked about finding log in events so that I may write a service that kills one process before the duplicate loads during logon/logoff events.

Now if anyone has an easier/less complicated way of doing this, believe me, I'm all ears.

Fastbreak
Jul 4, 2002
Don't worry, I had ten bucks.

real_scud posted:

I'm going to ask this here and pray someone can help me out, if not guess I'll stumble my way through.

I was given a task of taking our old .net template file and having it go from tables, to a more proper-semantic CSS styling.

Now I'm not much of a .net developer just a normal web front-end guy so looking at the page is a bit staggering to me.

Does anyone know of an easyish way I can easily fix up the code? Or am I going to have to stumble and bumble my way through it?

Its not as bad as you think. You should be able to tell what things are sense asp control naming is fairly straight forward, a datagrid is a grid of info... etc.

You are looking for '<@' as the start of a control. You can move these around however you want hypothetically and if it was coding correctly. The data they have and will get from the server won't change based on layout; its one of the best things about VS, design and code are almost completely seperated.

So basically just treat every control like its own block. Switching a normal HTML page and an ASPX page over to CSS from tables are virtually the same.

foxxtrot
Jan 4, 2004

Ambassador of
Awesomeness

poopiehead posted:

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)

Yeah, now it probably is a CHAR(X) field. I'm not fully sure what the Database backend I'm working with is, I think it's proprietary for the MAS 90 system. Trimmed and forgotten. Now to fix this crash when I change my selection.

Heffer
May 1, 2003

JediGandalf posted:

Yeah I did find something like that. Trouble is, I'm not sure if a lab computer can read the security event log.

Larger picture: Ok. This program controls three devices in the classroom: projector, audio switcher, and if equipped, a document camera. Thing is, they want it so that you can still control the devices w/o having the need to log in. In other words, the panel appears below the "press CTRL-ALT-DEL" box. I did manage to accomplish that (slightly) but I found out that it launches a 2nd process after you log in and thus the resources (COM ports) are all ready taken up by the first program. I asked about finding log in events so that I may write a service that kills one process before the duplicate loads during logon/logoff events.

Now if anyone has an easier/less complicated way of doing this, believe me, I'm all ears.

Is this program third party, or do you have control of it?

If you have control of it, you could have the GUI be a thin client that sends commands to a service running on the system. The service has control of the COM ports running on the system, and processes the commands one by one.

real_scud
Sep 5, 2002

One of these days these elbows are gonna walk all over you

Heffer posted:

Now if it's designed with ASP.NET, you'll see lots of <asp:thingy > tags throughout the page, which are interpreted by the compiler to be a specific control, which in turn is converted into HTML.
This is the case, and I found that I can edit the page mostly to my liking, however it breaks some kind of javascript they wrote on the backend. The page I'm editing is for our shopping-cart pages and normally certain things are hidden until you select them, then when you do the sub-options appear and you can select to your hearts content.

Something I did, possibly in changing some tr's to spans has made every option viewable all the time. I see nothing in the .ascx page but obiviously it must be there so I'm going to have to go back and re-think what I'm doing tomorrow.

Fastbreak posted:

You are looking for '<@' as the start of a control. You can move these around however you want hypothetically and if it was coding correctly. The data they have and will get from the server won't change based on layout; its one of the best things about VS, design and code are almost completely seperated.
Yeah I think the biggest problem I'm realizing now is that whoever made this page didn't exactly do that, because some things output to tables no matter what I try to change, so someone hardcoded that stuff in and boy does it suck.

Looks like I may end up going to talk to our programmers tomorrow.

Heffer
May 1, 2003

real_scud posted:

This is the case, and I found that I can edit the page mostly to my liking, however it breaks some kind of javascript they wrote on the backend. The page I'm editing is for our shopping-cart pages and normally certain things are hidden until you select them, then when you do the sub-options appear and you can select to your hearts content.

Something I did, possibly in changing some tr's to spans has made every option viewable all the time. I see nothing in the .ascx page but obiviously it must be there so I'm going to have to go back and re-think what I'm doing tomorrow.

Yeah I think the biggest problem I'm realizing now is that whoever made this page didn't exactly do that, because some things output to tables no matter what I try to change, so someone hardcoded that stuff in and boy does it suck.

Looks like I may end up going to talk to our programmers tomorrow.

Check the javascript they wrote. One place I worked at had a bad habit of hard-coding the array indexes of elements and things like that. So if you added a new input, you had to increment the array index of everything after it by one.

Out of curiousity, why go from tables to spans?

wwb
Aug 17, 2004

real_scud posted:

This is the case, and I found that I can edit the page mostly to my liking, however it breaks some kind of javascript they wrote on the backend. The page I'm editing is for our shopping-cart pages and normally certain things are hidden until you select them, then when you do the sub-options appear and you can select to your hearts content.

Something I did, possibly in changing some tr's to spans has made every option viewable all the time. I see nothing in the .ascx page but obiviously it must be there so I'm going to have to go back and re-think what I'm doing tomorrow.

Yeah I think the biggest problem I'm realizing now is that whoever made this page didn't exactly do that, because some things output to tables no matter what I try to change, so someone hardcoded that stuff in and boy does it suck.

Looks like I may end up going to talk to our programmers tomorrow.

They probably did not hardcode tables in, so much as use an ASP.NET control that outputs tables, such as a DataGrid or a DataList. Another possible scenario is they are wrapping things in server-side Panels. Which works great and gives you a nice clean DIV in 1.1, unless ASP.NET thinks your browser is downlevel, then you get a single cell table.

I would also argue that going from a non-semantic table-based layout to span soup helps no one. You really should not have any sorts of tags unless you need new logical elements in your html. And then you probably should use a semantically correct element, not a span.

*Note: I just got done fixing a site where we asked for "clean, semantically correct, CSS-driven layout." The designer apparently interperted this as "there should be no html elements save SPAN and A tags. Dumb loving oval office.

foxxtrot
Jan 4, 2004

Ambassador of
Awesomeness
Okay, another problem. I've tried about a half dozen things. This code executes perfectly fine on it's first iteration, however, when the user makes a selection, it throws "ERROR [S000] [ProvideX][ODBC Driver][PVKIO]Invalid segment number" when I attempt to use rdr.Read() or rdr.HasRows

code:
			OdbcCommand cmd = MAS90DataConnection.CreateCommand();
			cmd.CommandText = "SELECT AliasItem_No FROM " + UPCTable +
				" WHERE (ItemNumber='" + ItemBox.Items[ItemBox.SelectedIndex] +
				"') AND (RowCode='" + ColorBox.Items[ColorBox.SelectedIndex] +
				"') AND (ColumnCode='" + SizeBox.Items[SizeBox.SelectedIndex] + "')";
			OdbcDataReader rdr = cmd.ExecuteReader();
edit: gently caress. Nevermind, it's the same error as above, I was just being a moron.

edit, again: Or, maybe not. Still getting the same error, even after trimming the other two fields.

edit, yet again: I realized that this query should only ever return a single row (barring horrible horrible database corruption) so I just use cmd.ExecuteScalar now, which is what I really wanted anyway.

foxxtrot fucked around with this message at 00:02 on Feb 7, 2007

real_scud
Sep 5, 2002

One of these days these elbows are gonna walk all over you

Heffer posted:

Check the javascript they wrote. One place I worked at had a bad habit of hard-coding the array indexes of elements and things like that. So if you added a new input, you had to increment the array index of everything after it by one.

Out of curiousity, why go from tables to spans?
That's the other thing, I'm looking at the .ascx file and not seeing any javascript in it but I'm going to go digging more.

I was told to do it mostly to clean up our code because we're trying to move away from tables in our site and our configurator is one of the last bastions of table-based layout we have.

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



Why doesn't the parser allow this (in C#):
code:
     booleanValue ? someInt++ : someInt--;
I get a "; expected" on the end of both occurances of someInt and a "Invalid expression term ':'".

However, doing the following is kosher:
code:
     throwawayInt = booleanValue ? someInt++ : someInt--;
I looked through the specification and it seems like "someInt++" should be a valid result expression no matter what I do with the actual result. I mean, I can have a line that just reads "someInt++;", so why not, right?

Edit: Sticking someInt in some ()s lets it pass:
code:
     booleanValue ? (someInt++) : (someInt--);
I swear I tried that before posting but I guess I misplaced something. Anyway, this behavior seems weird to me since the ++ and -- operators bind so tightly. Can anyone explain why this happens? I can't figure it out.


Edit 2: Now it's not building again :wtf: :confused:

Munkeymon fucked around with this message at 18:55 on Feb 12, 2007

Just-In-Timeberlake
Aug 18, 2003
Ok, I'm trying to figure out something that's easy in ASP.NET, but appears to be next to impossible in VB.NET. I am trying to get the type of file a user wants to archive, ie s/he picks an excel file and I get a return value of "ms-application/excel" (or whatever). In ASP.NET you just use the ContentType value of the file stream, but that's not an option in VB.NET.

I suppose I could do it based on the extension, but for lack of a better word, its not as elegant as I'd like, since the extension could be wrong. There has to be a way to do this, but I've spent the last hour on Google to no avail. Any ideas?

SLOSifl
Aug 10, 2002


golgo13sf posted:

Ok, I'm trying to figure out something that's easy in ASP.NET, but appears to be next to impossible in VB.NET. I am trying to get the type of file a user wants to archive, ie s/he picks an excel file and I get a return value of "ms-application/excel" (or whatever). In ASP.NET you just use the ContentType value of the file stream, but that's not an option in VB.NET.
I aked for this a few pages back but got no response, so I'm seconding this question.

I need to get the MIME type from a file if possible, using C#. How do programs like 'file' work?

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.

SLOSifl
Aug 10, 2002


poopiehead posted:

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.
Glorious. Thank you. :buddy:

Potassium Problems
Sep 28, 2001

SLOSifl posted:

I aked for this a few pages back but got no response, so I'm seconding this question.

I need to get the MIME type from a file if possible, using C#. How do programs like 'file' work?
I think I got this from the previous .NET thread, but here's some code to do it outside of an ASP.NET environment. You'll need a 'using' reference to System.Runtime.InteropServices.
code:
    public static class Win32API {
        [DllImport("urlmon.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = false)]
        static extern int FindMimeFromData(IntPtr pBC,
            [MarshalAs(UnmanagedType.LPWStr)] string pwzUrl,
            [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.I1, SizeParamIndex = 3)]
            byte[] pBuffer,
            int cbSize,
             [MarshalAs(UnmanagedType.LPWStr)]  string pwzMimeProposed,
            int dwMimeFlags,
            out IntPtr ppwzMimeOut,
            int dwReserved);

        /// <summary>
        /// Returns the content type of a file based on content
        /// </summary>
        /// <param name="File">File location</param>
        /// <returns>Returns for instance "images/jpeg" </returns>
        public static string GetMIMEType(string File) {
            return GetMIMEType(new FileInfo(File));
        }
        /// <summary>
        /// Returns the content type of a file based on content
        /// </summary>
        /// <param name="File">FileInfo object based on a file location</param>
        /// <returns>Returns for instance "images/jpeg" </returns>
        public static string GetMIMEType(FileInfo File) {
            IntPtr mimeout;
            if(!File.Exists)
                throw new FileNotFoundException(File.FullName + " not found");

            int MaxContent = (int)File.Length;
            if(MaxContent > 4096)
                MaxContent = 4096;
            FileStream fs = File.OpenRead();


            byte[] buf = new byte[MaxContent];
            fs.Read(buf, 0, MaxContent);
            fs.Close();
            int result = FindMimeFromData(IntPtr.Zero, File.FullName, buf, MaxContent, null, 0, out mimeout, 0);

            
            if(result != 0)
                throw Marshal.GetExceptionForHR(result);

            // Here's the "unsafe" version, for kicks

            //unsafe {
            //    char* c = (char*)mimeout.ToPointer();
            //    string mime = new string(c);
            //    c = null;
            //}

            string mime = Marshal.PtrToStringUni(mimeout);                        
            Marshal.FreeCoTaskMem(mimeout);
            return mime;
        }
    }

SLOSifl
Aug 10, 2002


Sweet. I like the registry version, but this one will make a good fallback for when that one doesn't give me an answer.

Here's a screenshot of my Database based file manager thing, which is what I needed this for:


edit: kinda forgot to blur the server address...oops. Fixed.

SLOSifl fucked around with this message at 02:01 on Feb 8, 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?

Heffer posted:

Is this program third party, or do you have control of it?

If you have control of it, you could have the GUI be a thin client that sends commands to a service running on the system. The service has control of the COM ports running on the system, and processes the commands one by one.
This was my chosen route and it has worked

...kind of. It does appear underneath the login box but it disappears after I login then log back out. Something caused it to close and I do not know what. No exception was thrown (least no evidence). I'm pretty good at logging all foreseeable exceptions. I suppose I can have the service constantly monitor whether onscreen.exe is running. If it closes, then boot it back up again.

I shall experiment.

gwar3k1
Jan 10, 2005

Someday soon
I'm trying to write a Windows Live Messenger addin using MessengerClient.dll (writing in C#). I want to know when users sign in but can't seem to find this in the classes nor any tutorials online. Is this possible?

gwar3k1 fucked around with this message at 15:12 on Feb 10, 2007

Toenail Ninja
Sep 10, 2003

Superman is back!
It's great!
I'm currently evaluating our ability to upgrade from Visual Studio 2003 to 2005 and .NET 2.0. I've run into some issues, but the biggest one is our Crystal Reports. We use Crystal Reports Server and Developer 10 in our ASP.NET 1.1 application. I've upgraded a local copy of our web app to 2.0, and when I try to run a Report, I get an "An Enterprise Report Application Server was not found" error. I can run the reports from our development solution perfectly.

Is it possible to continue using CR 10 with VS2005, or do we have to shell out the money to upgrade to 11?

DarkPaladin
Feb 11, 2004
Death is just God's way of telling you you wasted your life.
New Question:

I'm currently working with a .NET account creation form. I have a databound checkbox list on the page and I'm using postbackurl to submit to another page both use a master page. I can find the control on the second page but regardless of what I have checked on the first page, all ListItem.Selected property values are returning false. Any help would be appreciated.

Edit:
I am an idiot, I forgot to trap whether or not it was a postback so it was rebinding the data and clearing selected values.

DarkPaladin fucked around with this message at 21:09 on Feb 14, 2007

shelleycat
Jul 24, 2004

Munkeymon posted:

Why doesn't the parser allow this (in C#):
code:
     booleanValue ? someInt++ : someInt--;

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
Jun 18, 2004

Munkeymon posted:

Why doesn't the parser allow this (in C#):
code:
     booleanValue ? someInt++ : someInt--;
I get a "; expected" on the end of both occurances of someInt and a "Invalid expression term ':'".
The ternary operator's result needs to be assigned. The following compiles:
code:
int q = 0;
bool b = args.Length == 0;
int r = b ? q++ : q--;

Console.WriteLine("q: {0}  r: {1}", q, r);
I am with shelleycat -- you should use an if statement for what you're doing.

foxxtrot
Jan 4, 2004

Ambassador of
Awesomeness

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.

Come on, I used to do that all the time in C++!

The designers of the C# langauge felt using the ternary operator as a basic "if-then-else" was hard to read, and it is. However, it's still something that comes up a lot in setting options, so they use the value as something to be assigned. Frankly, I'd just as soon them left it out instead of crippling it like that, but then they made some goofy decisions with C#, like requiring break; at the end of a case in a switch-case. If you're not going to allow implicit fall through, why not just ASSUME break?

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.

SLOSifl
Aug 10, 2002


foxxtrot posted:

If you're not going to allow implicit fall through, why not just ASSUME break?
Because people ignore warnings and the switch statement is weird enough that a fallthrough is a reasonable expectation.

The compiler error is more like missing a closing brace than anything else.

edit: I wish they just made switch use code blocks.
code:
switch ( comparisonVariable ) 
   case ( someValue ) {
     // do stuff
   } or ( somethingElse ) {
     // do stuff
   } or ( whatever, whateverElse ) {
     // multiple values
   } else {
     // let's not pretend it's not just an if-else if-else statement
   }
I don't know, something like that. My version there looks terrible, but come on, code lables?

SLOSifl fucked around with this message at 23:39 on Feb 14, 2007

Adbot
ADBOT LOVES YOU

Grid Commander
Jan 7, 2007

thank you mr. morrison

SLOSifl posted:

Because people ignore warnings and the switch statement is weird enough that a fallthrough is a reasonable expectation.

The compiler error is more like missing a closing brace than anything else.

edit: I wish they just made switch use code blocks.
code:
switch ( comparisonVariable ) 
   case ( someValue ) {
     // do stuff
   } or ( somethingElse ) {
     // do stuff
   } or ( whatever, whateverElse ) {
     // multiple values
   } else {
     // let's not pretend it's not just an if-else if-else statement
   }
I don't know, something like that. My version there looks terrible, but come on, code lables?

Switch is basically a special case that does not fit your need in this scenario.
Switch can not be used for your example at all.
Edit: Meaning a new programming construct would be required to make code as you have suggested above work.
It looks like you basically need a bunch of if statements here.

Here is what you describe above (except rewritten):

code:
bool handled = false;
if (someValue)
{

  handled = true;
}
else
{
  if (somethingElse)
  {

      handled = true;
  }
  else
  {
    if (whatever && whateverElse)
    {

       handled = true;
    }
    else
    {
    }
  }  
}

if (handled == false)
{
  //your switch else here
}

  • Locked thread