Saturday, February 19, 2011

ASP.NET TreeView javascript before postback

Hi,

I'm trying to code what I think is a fairly routine AJAX pattern using TreeViews and UpdatePanels. My situation is this:

I have a TreeView within an UpdatePanel. I have a Literal within another UpdatePanel. When the user clicks on a node within the TreeView, the contents of the Literal are updated. Now, since the whole thing is asynchronous, there is of course a time lag between the click and the update of the Literal contents. During this time, I'd like to do two things:

1) Show an UpdateProgress, and

2) Clear the contents of the Literal

This is so that the user doesn't have to stare at the old contents while the new text is getting loaded asynchronously.

I can't seem to figure out an easy way to accomplish (2). I've been reading up on client side callbacks and using GetCallbackEventReference, but it seems like a very complicated approach to what is seemingly a simple problem.

Ideally, I would like to leave TreeView alone to do it's work. I don't want to get the contents myself and add them to the TreeView using JS. I'd just like to detect the node change event at the client side, clear up the Literal, and let TreeView go about with its normal operation.

Is this possible? Or are client call backs my only option?

From stackoverflow
  • You'll be wanting to play with the PageRequestManager from the ASP.NET AJAX library. Here's the MSDN reference for the PRM - http://msdn.microsoft.com/en-us/library/bb311028.aspx.

    Just be for warned Microsoft have stated that the TreeView can be problematic within the UpdatePanel and you'll also want to be very careful of the performance, particularly if you have a large TreeView (see my article on optimising the UpdatePanel performance - http://www.aaron-powell.com/blog.aspx?id=1195). You should really look at something like a jQuery plugin (eg: http://bassistance.de/jquery-plugins/jquery-plugin-treeview/).

    But to actually answer you're question you need to:

    • Have a BeginRequest event handler which will then clear your literal and can even show a Loading (I'm not a fan of the UpdateProgress, I prefer much more granular control I get from doing it myself)
    • Use the EndRequest event to ensure that the Loading component vanises

    You could also make the TreeView a AsyncPostbackTrigger of the 2nd UpdatePanel on the page, or just call the Update method on it during the async postback of the TreeView

Round Robin Assignment implementation (database)

I'm currently in the process of implementing a number of different assignment algorithms for a SalesLead <--> SalesPerson situation. The general idea is quite simple:

  1. A SalesLead signs up on a public website

  2. The code automatically assigns the SalesLead to a SalesPerson using round-robin scheduling (Leads are assigned to SalesPersons in the same order)

I'm having some serious coders-block in how to actually perform this outside of making sure I pull the agents from the database in the same order each time, and using another table to store the last agent that was assigned a SalesLead (which may actually be useful for building a report, or at least having a trace-back method later on). Am I way off base?

Clarification: The code doesn't currently match a sales person to a lead. This is a completely new function. Currently they can sign up for a specific SalesPerson, but we'd like them to be able to be assigned automatically.

From stackoverflow
  • If you have a table that matches SalesLeads and SalesPersons together and you timestamp it, you don't need a separate table to keep track of the last SalesPerson picked.

  • Pretty simple really: when a SalesPerson is created, give them a LastActivityDate. When they are assigned a SalesLead, update that date to the current date. Give a SalesLead, as it comes in, to a SalesPerson with the least recent activity date.

    Can be done easily in SQL or code.

    dmercer : I like this, it's simple, but effective. I'd never considered adding a timestamp column.
    cletus : You just have to cover a few corner cases. Like if a SalesPerson goes on leave, set their activity date to NULL (so its not picked up) and when they get back, set it to now so they go back in the rotation. This system is then quite fair.
  • In SQL Server you'd actually want it to be a datetime, not a timestamp field, but @David's idea is the same. Keep track of the last sales lead assigned to a sales person and record the time at which it was assigned. You can then pick the next sales person to assign a lead to by finding the sales person who does not have one assigned or the sales person whose last assigned lead is the oldest.

  • Check out how Salesforce does it: http://forums.sforce.com/sforce/board/message?board.id=custom_formula&message.id=533

    MOD an ID by the number of salespeople + 1 and then assign 1 to Joe, 2, to Tom, etc.

How do I tell Apache which PHP to use?

I am running Apache2 on a Mac OS X (10.5). I just compiled PHP 5.2.8 and finally got pdo-mysql working (or so I think). My command line "php --version" is showing 5.2.8 and I have the right modules installed. But, when do a phpinfo(), Apache dumps out PHP 5.2.6 (my earlier version, without pdo_mysql). How do I tell Apache which PHP to load? The httpd.conf has the line:

LoadModule php5_module libexec/apache2/libphp5.so

But, I don't know what or where that is. Is that what I have to change?

From stackoverflow
  • Apache should be looking for modules in "/usr/libexec/httpd/". In there you'll find either a file or symlink called "libphp5.so". If it's a symlink, you'll need to relink to the new 5.2.8 libphp5.so, otherwise just copy the 5.2.8 libphp5.so to "/usr/libexec/httpd/" and restart apache with "sudo apachectl restart".

  • You can find files on your system with the locate command:

    # locate libphp5.so
    

    It will print the full paths of all files with that name. I have one at /usr/libexec/apache2/libphp5.so.

  • When you compiled php did you use make install? If you did find the path that it installed your module to and change your apache config to point to it. Mac has it's own version of apache and php5 already installed which is why you are seeing a different version.

How do I access query parameters in the request content body in javascript?

If I use a GET to request a page, then I can access any query parameters from javascript using window.location.search. Is there a similar way to access query parameters which are in the request content body rather than the request location, when the page is a result of a POST?

From stackoverflow
  • Because the data is being handled on the server side, the client (where JS lives) has no access to these variables.

Zend Framework: How do I set a custom validator on a form element?

I'm writing a custom validator that checks that at least one field has a value. I want to validate that either 'namefield' or 'idfield' has a value. One of them can be empty, or both can have a value, but at least one of them must have a value.

$nameField = new Zend_Form_Element_Hidden('namefield');
$nameField->setValue($this->nameFieldValue)
          ->addValidator('AtLeastOneHasValue', false, array('idfield'));

From what I understand, my validator will not validate unless I set my form element to required.

->setRequired(true)

But if I set it to required, it automatically validates that it is not empty, and the error message says that it is empty. I want to allow the field to be empty, and validate multiple fields with my custom validator. How do I validate a form element with my custom validator, without setting the form element to required?

From stackoverflow
  • Check this documentation page for the setAllowEmpty() method. This should help you get where you are trying to go.

    setAllowEmpty($flag) and getAllowEmpty() allow you to modify the behaviour of optional elements (i.e., elements where the required flag is false). When the 'allow empty' flag is true, empty values will not be passed to the validator chain.

    Andrew : ->setAllowEmpty(false) This was just what I needed. Thanks!

How do you select what properties will be displayed when databinding to a DataGridView?

Binding a List collection to a datagrid. How can you limit what properties will be displayed?

DataGridViewAirport.DataSource = GlobalDisplayAirports
From stackoverflow
  • Turn off AutoGenerateColumns, and then you can explicitly create the columns you need. For example here's an example:

    <asp:GridView ID="myGrid" runat="server" AutoGenerateColumns="False" CellSpacing="0">
        <Columns>
         <asp:BoundField DataField="Total" HeaderText="Amount" DataFormatString="{0:C}"/>
    
        </Columns>
    

    Another option would to be hide the columns after you data bind, but this above is a better approach.

    : Thanks Josh, sorry should have been more specific, I am using Windows Forms.
    JoshBerke : Ok solution is still the same, just my sample is off.
  • Depending on your dataSource you could mark the properties you don't want to show then you can leave autogenerate columns on.

    I believe this is correct VB:

    <System.ComponentModel.Browsable(false)> _
    

    in C# it is

    [System.ComponentModel.Browsable(false)]
    

    Another Useful attribute is

    [DisplayName("Total Amount")]
    

Are routed events weak in WPF

Does routed events in WPF store strong reference to the handler that is attached to them?

From stackoverflow
  • Hello,

    If the control author implemented the WeakEvent pattern then yes. I believe the stock controls use this pattern.

    UPDATE: They in fact do NOT. Here is a reference on this and other potential performance problems:

    http://msdn.microsoft.com/en-us/library/aa970683(VS.85).aspx

    Here is a reference on weak events:

    http://msdn.microsoft.com/en-us/library/aa970850.aspx

    HTH

    Colby Africa

    ligaz : The standard controls did not implement weak event pattern.
    Colby Africa : Oh my... I didn't know that either. I assumed, which is never smart. I just did a bunch of reading on this. Here is a good reference for you on this and other potential performance issues: http://msdn.microsoft.com/en-us/library/aa970683(VS.85).aspx I apologize for the last post.

Capturing Events For Logging Purpose

When an application is launched, I need to know for certain methods when they are fired. How to do this using attributes and AOP techniques?

The simplest way is to record the time in the event method such as this:

private void Page_load()
{
  DateTime dt = DateTime.Now;
}

And save the Datetime into a database. But this is definitely not desirable as doing this will leave the method will a lot of cross cutting functions, making the maintenance job harder. I am thinking about using attributes to solve this problem. PostSharp seems to be a good candidates here as it can intercept method calls and do whatever pre and post processing you want. But one thing that is clearly lacking is that it can't handle events without me writing a lot of custom code.

Is there any framework that can handle events naturally?

From stackoverflow
  • You don't need to have a separate method for every event you want to log like this.

    Write a single method to do the logging:

    public static void LogEventRaised(string event)
    {
        ...
    }
    

    then subscribe to the events using an anonymous method:

    Load += delegate { LogEventRaised("Load") };
    

    Yes, it's imperative rather than declarative, and repeats the event name - but it's still pretty compact. You could attach handlers to all events using reflection, but that would probably be overkill.

  • The Spring framework has an Aspect Oriented Programming module that provides logging support.

  • Postsharp can probably help you here

    Perpetualcoder : Post sharp is one of the easiest .net AOP frameworks. Glad people like it. +1 to you
    Ngu Soon Hui : Thanks, but unfortunately PostSharp doesn't support events: http://www.postsharp.org/forum/postsharp-laos/equivalent-oneventboundaryaspect-t617.html

How can I embed images in an ASP.NET Generated Word File

Hi everyone!

I have a quite common problem, as I saw in the various user groups but could not find a suitable answer.

What I want to do is generate an ASP.NET page in my website which will have the option of being exported into Microsoft Word .doc format.

The method I have used is this:

Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=Test.doc");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/msword";

StringWriter sw = new StringWriter();
HtmlTextWriter htmlWrite = new HtmlTextWriter(sw);
Page.RenderControl(htmlWrite);
Response.Write(sw.ToString());
Response.End();

However this eventhough it generates a word doc, the images are note embedded in the document, rather they are placed as links. I have looked for a way to do this, but have not found something that actually worked.

I would appreciate any help I can get, since this as "last minute" requirement (talk about typical)

Thanks

From stackoverflow
  • Short Answer: You need to provide absolute URLs for the source of the images in your page.

    Longer Answer:

    Microsoft Word will open an HTML document if you rename it with a *.doc extension. This is what the code that you provided is doing. In this case, the images are not embedded in the document like they would be if you created a document in actual Word format. If your images are using relative URLs then Word will not know where to look for them, hence the need for absolute URLs.

    NOTE: This means that anyone viewing the document without an internet connection will not see the images, as they are requested from the server every time the document is opened.

    A more elegant solution would be to create the document in the real Word format. A great library for this is Aspose.Words. Using this library you would be able to embed the images directly into the document so that they do not rely on the server.

    Nikos Steiakakis : It took a while to accept the answer, but I had been working on another project so long, so I couldn't accept it without trying it out first!
    AJ : Glad to hear that it was helpful... did you end up using a third party component or going with absolute urls? If you used a component, which one did you go with?
  • Thanks AJ for your answer.

    The problem is that we are developing a web application that is hosted in the customers premises each time. So the approach of absolute URLs might be a little tricky. We will most probably have to try a third party library after all.

    Thanks anyway!

  • I Also have the same problem. How I can embed the image in the doc from the ASP.net application? Any body know the answer.

Hyper-V Manager MMC SnapIn in Windows 2008 Web Edition. Possible?

Hello!

Is there any possibility to run Hyper-V Manager MMC SnapIn on Windows 2008 Web edition ?

Thanks

From stackoverflow
  • No, this is against the Web Editions EULA.

  • Too bad. But this is quite strange if you think about it. MS has released Hyper-V Manager MMC SnapIn for Vista so why they could'n release it for Windows 2008 Web Edition? This is only a manager ..

Overlaying of charts

I want to know whether this is possible using Google Charts API: First, create a bar chart with the given input data. And then overlay a line chart (or a line) on top of it.

My use case here, is to show a student's performance in a test when compared to the rest of the crowd which is already available as a bar chart.

EDIT: Dug and found out about markers. Will explore and may be answer my own question :)

From stackoverflow

Nant on Windows Vista 64

Hi

I was wondering if anyone has successfully ran Nant on Windows Vista 64 bit version. It keeps failing with

set-props:

[sysinfo] Setting system information properties under sys.*

BUILD FAILED

Property name 'sys.env.CommonProgramFiles(x86)' is invalid.

Thanks.

From stackoverflow
  • Yes, it works. NAnt is by default built for 32-bit. Therefore, one has to remember to run this in a 32-bit command prompt or PowerShell. I run NAnt scripts out of PowerShell (x86) mode on a Vista 64 machine, but an SDK prompt (32-bit) would works as well.

  • It also has worked well for me. I do run as Scott said in a 32bit command prompt.

    It could also be just a specific thing you are trying to capture that nAnt is not expecting.

C# Syntax - Your preferred practice for getting 2 or 3 answers from a method

I'm just wondering how other developers tackle this issue of getting 2 or 3 answers from a method.

1) return a object[]
2) return a custom class
3) use an out or ref keyword on multiple variables
4) write or borrow (F#) a simple Tuple<> generic class
http://slideguitarist.blogspot.com/2008/02/whats-f-tuple.html

I'm working on some code now that does data refreshes. From the method that does the refresh I would like to pass back (1) Refresh Start Time and (2) Refresh End Time.
At a later date I may want to pass back a third value.

Thoughts? Any good practices from open source .NET projects on this topic?

From stackoverflow
  • For two, usually 4)

    More than that, 2)

    Scott Dorman : Doesn't help yet, but .NET 4.0 will include a generic Tuple class in the BCL.
    le dorfier : Sounds like a typical Microsoft solution - add yet another obscure feature.
    Jonathan Allen : Obscure? People have been asking for Tuples and Multiple Return Values since version 1.
  • I use out if it's only 1 or 2 additional variables (for example, a function returns a bool that is the actual important result, but also a long as an out parameter to return how long the function ran, for logging purposes).

    For anything more complicated, i usually create a custom struct/class.

  • I think the most common way a C# programmer would do this would be to wrap the items you want to return in a separate class. This would provide you with the most flexibility going forward, IMHO.

  • It entirely depends on what the results are. If they are related to one another, I'd usually create a custom class.

    If they're not really related, I'd either use an out parameter or split the method up. If a method wants to return three unrelated items, it's probably doing too much. The exception to this is when you're talking across a web-service boundary or something else where a "purer" API may be too chatty.

    drax : +1 Agree on this. Methods which return > 2 different things propably do way too much
    annakata : >1 unrelated things anyway, big fan of class i/o for methods +1
    Matt Briggs : 99% of the time you want to make a custom struct, not a class, but +1 anyways
    Jon Skeet : @Google Ninja: No, I don't believe you usually *do* want a custom struct. I find that custom structs are *very* rarely appropriate.
    Michael Stum : I normally agree, but I sometimes (seldom) group functions that return two unrelated items, but get them from a rather expensive operation that i only want to run once.
    Jon Skeet : That sounds similar to my last sentence - not exactly the same, but along the same lines. Where possible it's nice to extract the bits out, of course, but you do need to be pragmatic.
  • It depends. For an internal only API, I'll usually choose the easiest option. Generally that's out.

    For a public API, a custom class usually makes more sense - but if it's something fairly primitive, or the natural result of the function is a boolean (like *.TryParse) I'll stick with an out param. You can do a custom class with an implicit cast to bool as well, but that's usually just weird.

    For your particular situation, a simple immutable DateRange class seems most appropriate to me. You can easily add that new value without disturbing existing users.

  • Code Architeture wise i'd always go with a Custom Class when needing somewhat a specific amount of variables changed. Why? Simply because a Class is actually a "blueprint" of an often used data type, creating your own data type, which it in this case is, will help you getting a good structure and helping others programme for your interface.

  • If 2, a Pair.

    If more than 2 a class.

    tyndall : Never noticed the System.Web.UI.Pair class. Guess you would just use the Tuples coming in VS2010 moving forward.
  • Your question points to the possibility that you'll be returning more data in the future, so I would recommend implementing your own class to contain the data.

    What this means is that your method signature will remain the same even if the inner representation of the object you're passing around changes to accommodate more data. It's also good practice for readability and encapsulation reasons.

    tyndall : +1 Good point about future needs. By using a class you can add to the class without changing the method or the caller.
  • If you're wanting to send back the refresh start and end times, that suggests a possible class or struct, perhaps called DataRefreshResults. If your possible third value is also related to the refresh, then it could be added. Remember, a struct is always passed by value, so it's allocated on the heap does not need to be garbage-collected.

  • Personally, I hate out/ref params, so I'd rather not use that approach. Also, most of the time, if you need to return more than one result, you are probably doing something wrong.

    If it really is unavoidable, you will probably be happiest in the long run writing a custom class. Returning an array is tempting as it is easy and effective in the short teerm, but using a class gives you the option of changing the return type in the future without having to worry to much about causing problems down stream. Imagine the potential for a debugging nightmare if someone swaps the order of two elements in the array that is returned....

  • Another solution is to return a dictionary of named object references. To me, this is pretty equivalent to using a custom return class, but without the clutter. (And using RTTI and reflection it is just as typesafe as any other solution, albeit dynamically so.)

    Daniel Earwicker : Anything you do in the CLR is dynamically typesafe, so that isn't saying much!
  • Some people use KeyValuePair for two values. It's not great though because it just labels the two things as Key and Value. Not very descriptive. Also it would seriously benefit from having this added:

    public static class KeyValuePair
    {
        public static KeyValuePair<K, V> Make(K k, V v) 
        { 
            return new KeyValuePair<K, V>(k, v); 
        }
    }
    

    Saves you from having to specify the types when you create one. Generic methods can infer types, generic class constructors can't.

  • For your scenario you may want to define generic Range{T} class (with checks for the range validity).

    If method is private, then I usually use tuples from my helper library. Public or protected methods generally always deserve separate.

  • Return a custom type, but don't use a class, use a struct - no memory allocation/garbage collection overhead means no downsides.

  • It depends on the type and meaning of the results, as well as whether the method is private or not.

    For private methods, I usually just use a Tuple, from my class library.

    For public/protected/internal methods (ie. not private), I use either out parameter or a custom class.

    For instance, if I'm implementing the TryXYZ pattern, where you have an XYZ method that throws an exception on failure and a TryXYZ method that returns Boolean, TryXYZ will use an out parameter.

    If the results are sequence-oriented (ie. return 3 customers that should be processed) then I will typically return some kind of collection.

    Other than that I usually just use a custom class.

  • If a method outputs two to three related value, I would group them in a type. If the values are unrelated, the method is most likely doing way too much and I would refactor it into a number of simpler methods.

Standalone java base java formatter

Is there a Java-based program(jar) that can format java code(indenting/spacing). If it would be configurable that would be great.

From stackoverflow
  • You bet: JIndent.

  • CheckStyle is another and FREE. CheckStyle:Indentation.

    Milhous : Can you give a specific example of using this tool?
    Adeel Ansari : Once I have used this as a Netbeans plugin. There are plugins available for Eclipse, IntelliJ, Netbeans, JBuilder, JEdit and Emacs JDE. The plugin I used before is http://www.sickboy.cz/checkstyle/screenshots.html

Is there a way to find out if a web service has security?

I've got a web service: http://machine001/Services/conversionService.asmx

This web service has one method in it called convert(string pInput).

I am trying to find out if there is a way to figure out, without logging into machine001 and without actually calling the convert method, if this web service has security applied.

If I am able to reach http://machine001/Services/conversionService.asmx, see the service description, create the proxy class and instantiate the web service object from any client does that mean there is no security?

From stackoverflow
  • Use your browser and go to:

    http://machine001/Services/conversionService.asmx?wsdl

    And see if the description contains WSE Security declarations. And to you're last paragraph, yes if you can do all of that and you did not do anything else to authenticate, it is unsecured.

outputting the value of a "Watch" in Eclipse to a log file.

I have a piece of Java code I can't edit which I want to debug.

The issue is that one of my 10,000 records has a data error and is causing the application to crash.

I can remote debug the live application and add watch which would pick up the id of the record as each is processed. The problem is when the "bad record" is processed and the method is exited the value held in the watch is lost so I don't know which record it was that causes the problem.

Is there any way of storing/printing the value held in the watch

Thanks

From stackoverflow
  • May be yu could launch your own modified eclipse with a watchExpressionDelegates extension point in it.

    Your class which would implement that delegate class org.eclipse.jdt.internal.debug.ui.JavaWatchExpressionDelegate may have the opportunity to do whatever it wants, including logging informations.

    I have not tested it but if you do successfully implement that, let us know.

  • If the bad record is causing your application to crash by throwing an exception, try putting a breakpoint on that exception, and maybe the record info will still be available in the stack frame of that method. Haven't tried this, just a thought. Good luck.

How do I make C# talk to PHP session

I have a C# web-app that I wants to integrate an PHP shopping cart, it is possible? Thanks

From stackoverflow
  • It's not possible unless it is in a database and you write a (de)serialization algorithm that works between both languages. If it's supposed to be a read-only access, I'd make a user with read-only access just for this purpose.

    If it is stored on the filesystem I'd consider it insecure to access it.

  • Well you need to describe the pieces in more detail really, but it will be non-trivial if it is possible.

    How about Response.Redirect to cart.php?inputparams=foo -> do work -> PHP redirect to thankyou.aspx?inputparams=bar

    Can you consume the PHP as a service?

    Or request the output of the PHP as an HTTPWebRequest?

  • Indeed it depends on the details. Do you want the PHP app to run within your .NET environment? if so I would take a look at Phalanger, but I don't think it will work as you want.

    You can also tak a look at PHP on IIS, but that also would not give you a lot of info.

    As annakata mentioned I assume you would be better calling/redirecting to/from the PHP script into your ASP.NET website.

    And I have a feeling that will not be an easy job to do, so... lucky you ;)

  • There are a few options here. While Java has more options for integration, particularly for sessions, C#/.Net will probably rely upon other products to communicate.

    If this were background processing (eg processing of completed orders after checkout), it would probably be simpler. You want to mix web apps however. How and what you want to mix them could (and probably does) make this rather difficult--or at least uncharted waters. PHP runs under Apache and .Net web apps under IIS after all.

    You're going to have to go through another technology layer. Others have mentioned databases but that's not a viable or performant solution for session storage on live web apps.

    Your best bet is probably memcached, for which there is at least one C# client library. Here's an example of cross-platform serialization using memcached.

    beanstalkd may also be worth considering if you have background work processing. It's a distributed work queue process that has several client libraries (eg Ruby, PHP, Perl, Erlang). I couldn't see a C# version but that could probably be done. Refer to the protocol docuentation.

    I mention this because you could have PHP write work requests to beanstalkd rather than C# polling or interrogating the PHP session.

  • PHP stores its session in files. A client cookie contains the file name, the php.ini contains the path.

    It should be relatively simple to access php session data from dotnet. I'm looking for a library that does this, but if I cannot find one I'll write one myself.

Large public datasets?

I am looking for some large public datasets, in particular:

  1. Large sample web server logs that have been anonymized.

  2. Datasets used for database performance benchmarking.

Any other links to large public datasets would be appreciated. I already know about Amazon's public datasets at: http://aws.amazon.com/publicdatasets/

From stackoverflow
  • Well for the web server logs you could always just generate them for the format you need. If you are going to test code against it etc. it will have to be tailored to the fields you want to store/parse.

    For the datasets used for database performance benchmarking, you'll probably want to look at a tool that can generate data for you. Red Gate has a great one for not too much money.

  • Just a thought:

  • Google Fusion Tables has a few.

    http://tables.googlelabs.com/

  • Find some Public Open Datasets at Edigitalz

Is there anyway to change the content type of an XML document, in the XML document?

Is there anyway to change the content-type of an XML document, in the XML document?

I'm working with a really old system that passes back HTML (and we are trying to make it return XML). I'm retrieving it from XMLHttpRequest, and I noticed using netcat that it isn't passing back any content-type headers.

When I receive the XMLHttpRequest.responseXML, the responseText exists but the responseXML is null.

I've already checked the XML being returned to see if it is well formed and it appears to be (it's a very short document).

From stackoverflow
  • No. The Content-Type as you refer to it (in the comments to your question) is part of the HTTP headers.

    And HTTP is the mere means of transportation for (say) XML documents. They are payload, they know nothing about the HTTP headers, so they can't change them.

    What you probably mean is "Is there an equivalent to <meta http-equiv="... in XML. No, there is not. Even HTML can't change the HTTP headers, it can only make the user agent behave differently. This is useful if the HTML file was saved to disk, and upon load no headers are available to the user agent.

    In XML, all the necessary information is in the processing instruction (<?xml version="1.0" encoding="UTF-8"?>) at the top of the file. No header info is are needed to load/display it correctly.

  • No.

    By the time the UA could get to any such tag, it would already have to have decided what kind of document it's parsing.

  • I figured it out, it's a matter of taking the xhr.responseText string and creating an XML document from it:

    function createDOMFromString(sXml){
    
     var browser = navigator.appName;
     var oXmlDom = null;
    
     // IE Implementation...
     if(browser == "Microsoft Internet Explorer") {
       oXmlDom=new ActiveXObject("Microsoft.XMLDOM");
       oXmlDom.async="false";
       oXmlDom.loadXML(sXml);
     }
     // FF Implementation...
     else {
      var oParser = new DOMParser();
      oXmlDom = oParser.parseFromString(sXml, "text/xml");
     }
     // TODO: If we need it Safari implementation.
    
     return oXmlDom;
    }
    

    Cheers!

    leeand00 : Hey I can't check my answer...and it's the one that worked!
    Tomalak : Nobody can check his own answer (or everybody would). Honestly, shouldn't you have asked the question more clearly in the first place? Your edit made all the difference, the question was close to unintelligible in its original state. Please don't expect your readers to have visionary powers...

Can a two-dimensional gradient be created (or faked) in SVG?

I'm trying to create a color-picker which must dynamically generate its images and figured it would be a whole lot easier to generate SVG than a raster image. Unfortunately, I can't figure out how to represent the big, two-dimensional gradient which will form the centerpiece of the picker.

For example, if the currently selected axes are blue and green, I need to paint a square which has the lower-left corner black, the upper-left blue, the lower-right green, and the upper-right cyan.

If there's a way to accomplish this by overlaying two linearGradient-filled squares and playing with their opacity, I wasn't able to work it out. I also tried creating a gradient whose start end end colors were other gradients (hoping I was being clever), but all that got me was a "big black nothing". Google searches have thus far gotten me nowhere.

I'd hate to resort to a stack of 256 1-pixel high gradients, both because of the increase in size and complexity and because I suspect it wouldn't resize well. Perhaps someone with a bit more working knowledge of SVG can suggest something

From stackoverflow
  • There is an implementation of a color picker in svg here:

    http://www.kevcom.com/colorpicker/picker.html

    I haven't tested it because I have no svg capable browser here. The code is available, so you can see how it was implemented there.

C# .NET Convert a JPEG Image into a Bitmap structure

Hello everyone,

I have a JPEG "image" (actually a BLOB in a database) which I want to import/convert into a "Bitmap" structure in memory. The reason is that I use a third party library which is unable to work with JPEG images and I need to pass an uncompressed bitmap (as a pointer). All I found so far are ways to convert between different formats on disk but saving the image as bitmap first and re-import it will take far too long.

I don't know much about .NET but I think a System.Drawing.Bitmap should be able to hold the uncompressed data. I'm working with C# and Visual Studio 2008.

From stackoverflow
  • // blob is a byte[] retrieved from DB
    Bitmap bmp = new Bitmap(new MemoryStream(blob));
    
    Jon Skeet : Just as a word of warning - *don't* close the stream yourself! (Not that the answer did, but it's an obvious thing to try.) After constructing the Bitmap, it "owns" the stream. Disposing of the bitmap will close the stream. It will get upset if you close the stream first.
    Mehrdad Afshari : I updated the answer to avoid the pitfall that Jon mentioned.
    codinguser : When I try this on Windows Mobile 6.1, I get an ArgumentException which says the parameter is invalid. I know that the array in the MemoryStream does contain a Jpeg image and starts with 0xff 0xd8. Any idea why this might be happening?

Broadcast ARP response - will dropping it cause problems?

Are there common machines or OSs that will have problems connecting on a network where unicast ARP requests or broadcast ARP responses are not supported? I am providing a public Wi-Fi service, and considering blocking these types of ARP packet. Will this cause connectivity issues for contemporary clients?

From stackoverflow
  • The ARP specification has recently been updated with RFC 5227 which talks about the use of gratuitous ARP packets for "address conflict detection".

    If you block ARP response broadcasts this ACD is not possible.

  • Broadcast ARP is used by some High-Availability IP-Takeover schemes to announce the new MAC-address on switch-over.

    Alnitak : very true, but probably not relevant for a wifi access point.

C# Serialization XML

Hello Everybody,

just a simple question. Is there an attribute to skip empty arrays in the xml-serialization of c#? This would increase human-readability of the xml-output.

Thanks in advance

Matze

From stackoverflow
  • Well, you could perhaps add a ShouldSerializeFoo() method:

    using System;
    using System.ComponentModel;
    using System.Xml.Serialization;
    [Serializable]
    public class MyEntity
    {
        public string Key { get; set; }
    
        public string[] Items { get; set; }
    
        [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
        public bool ShouldSerializeItems()
        {
            return Items != null && Items.Length > 0;
        }
    }
    
    static class Program
    {
        static void Main()
        {
            MyEntity obj = new MyEntity { Key = "abc", Items = new string[0] };
            XmlSerializer ser = new XmlSerializer(typeof(MyEntity));
            ser.Serialize(Console.Out, obj);
        }
    }
    

    The ShouldSerialize{name} patten is recognised, and the method is called to see whether to include the property in the serialization. There is also an alternative {name}Specified pattern that allows you to also detect things when deserializing (via the setter):

    [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
    [XmlIgnore]
    public bool ItemsSpecified
    {
        get { return Items != null && Items.Length > 0; }
        set { } // could set the default array here if we want
    }
    
  • Thanks a lot! It works! Really fast replies here!

    Have a nice Holiday Season

    Marc Gravell : No problem; if that answers it, click the tick ;-p
    Charles Graham : Yeah, if it works, hen give him props and mark it as answered.

Ajax Asynchronous in IE - Error "The Data Necessary to Complete This Operation is Not Yet Available"

Hey there. I have a 100% valid Ajax model written in Javascript with a few inputs I use being, Get or Post method, What page to communicate with, What String to send to that page and What element on my own page I might be fiddling with when I receive my response. The problem is that, should I set the request to Asynchronous (Hence Ajax), IE returns the error "The Data Necessary to Complete This Operation is Not Yet Available" in the onreadystatechange event where all I do is check if the readystate is 4 and the status is 200. The error doesn't come up in Firefox or Chrome as I would exepect as the Ajax is Asynchronous.

Heres a snippet from the Post method

xmlhttp.open("POST", commPage, true);
xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        j = xmlhttp.responseText;
        i.innerHTML = j;
    }
}
xmlhttp.send(str);

Edit: I should point out that in IE, I'm using the ActiveX Control -> Msxml2.XMLHTTP or Microsoft.XMLHTTP or whichever returns true first.

From stackoverflow
  • Ho humm

    Outside of the onreadystatechange function I had a call for responsetext to check whether it existed yet, but aparently you can't do that if it doesn't exist yet so I just had to restructure some thigs. All is okay but this was the script that caused the problem

    ajaxRequest(){
        [...]
    }
    if(xmlhttp.responseText){
        myFunc();
    }
    
  • Not sure if that's your case but I've just been struggling with this error for three hours until I found the problem. The web service class wasn't decorated with ScriptService attribute that allows methods to be called from client script! I wouldn't blame IE because IE is just strict on errors and reports everything what other browsers ignore. IE is good for debugging. Hope this helps. Well... probably not you as your post is now very old.

LDAP through Ruby or Rails

I've been attempting to hook a Rails application up to ActiveDirectory. I'll be synchronizing data about users between AD and a database, currently MySQL (but may turn into SQL Server or PostgreSQL).

I've checked out activedirectory-ruby, and it looks really buggy (for a 1.0 release!?). It wraps Net::LDAP, so I tried using that instead, but it's really close to the actual syntax of LDAP, and I enjoyed the abstraction of ActiveDirectory-Ruby because of its ActiveRecord-like syntax.

Is there an elegant ORM-type tool for a directory server? Better yet, if there were some kind of scaffolding tool for LDAP (CRUD for users, groups, organizational units, and so on). Then I could quickly integrate that with my existing authentication code though Authlogic, and keep all of the data synchronized.

From stackoverflow
  • Have you checked out thoughtbot's ldap-activerecord-gateway? It might be something for you to consider...

    http://github.com/thoughtbot/ldap-activerecord-gateway/tree/master

    Clinton Judy : Hmm. I'm still trying to understand what this could do for us. Essentially, I would start this ldap server when starting the rails application. Then, if there's a way to replicate data between this and the real AD server, do that. Then use my ldap server for data. Does that make sense?
  • Have you tried this: http://wiki.rubyonrails.org/rails/pages/HowtoAuthenticateViaLdap

    Or looking these, although these are more in the lines of authenticating against AD:

    http://wiki.rubyonrails.com/rails/pages/WindowsDomainAuthentication

    http://www.noitulove.ch/ldap-authentication-plugin-for-rails/

    http://saush.wordpress.com/2006/07/18/rubyrails-user-authentication-with-microsoft-active-directory/

    http://xaop.com/blog/2008/06/17/simple-windows-active-directory-ldap-authentication-with-rails/

    Chris Markle : mrT - Many of the links that presumably once worked in your answer are now broken. Could you be persuaded to update them? Thanks in advance.
    Charles Ma : new how to authenticate with ldap link: http://wiki.rubyonrails.org/rails/pages/howtoauthenticatewithrubynetldap
  • This is more anecdotal than a real answer...

    I had a similar experience using Samba and OpenLDAP server. I couldn't find a library to really do what I wanted so I rolled my own helper classes.

    I used ldapbrowser to see what fields Samba filled in when I created a user the "official" way and and basically duplicated that.

    The only tricky/non-standard LDAP thing was the crazy password encryption we have:

    userPass:

    "{MD5}" + Base64.encode64(Digest::MD5.digest(pass))
    

    sambaNTPassword:

    OpenSSL::Digest::MD4.hexdigest(Iconv.iconv("UCS-2", "UTF-8", pass).join).upcase
    

    For the def authenticate(user, pass) function I try to get LDAP to bind to the domain using their credentials, if I catch an exception then the login failed, otherwise let them in.

    chmeee : +1 Thanks, I was looking for a way to generate an nt password hash in ruby :)
  • I began using ruby-activedirectory, and even extended it/fixed a few things, hosting judy-activedirectory in Github.

    Doing the next iteration, I've discovered ActiveLdap has a much better code base, and I'm seriously contemplating switching to it. Does anyone have personal experience with this?

    chmeee : +1 for ruby-activedirectory