Wednesday, April 13, 2011

Classic Asp Web Service Problem

I'm trying to create a code to allow an existing classic asp program to use an asp.net web service. Updating from the classic asp is not an option, as I'm working in a big company and things are the way they are.

I've been browsing through a chunk of tutorials supposedly helping in this, but I haven't managed to get them to work yet. As a beginner I might've made some real obvious mistakes but I just don't know what.

First, the web service is located on an external server. The method "Greeting" needs a String parameter by which it determines which String is sent back. Inputting "g" to it procudes this xml:

  <?xml version="1.0" encoding="utf-8" ?> 
  <string xmlns="http://server1/Logger_WebService/">Greetings and welcome!</string> 

I assume the xpath for getting the contents is either "string/*" or "*"?

Next, my web service itself looks like this:

    <WebMethod()> _
    Public Function Greeting(ByVal stringel As String) As String

        If stringel.ToLower = "g" Then
            Return "Greetings and welcome!"
        Else
            Return "Bye then!"
        End If

    End Function

The web service works fine from a regular asp.net solution.

Now here's the problem, the classic asp code looks like this (4 different ways I've tried to get this to work, SOAP toolkit is installed on the web service server, all examples taken and modified from tutorials):

'******* USING GET METHOD
Dim wsurl="http://server1/Logger_WebService/service.asmx/Greeting?g"
Dim xmlhttp
Set xmlhttp=Server.CreateObject("MSXML2.ServerXMLHTTP")
xmlhttp.open "GET",wsurl,false
xmlhttp.send
Dim rValue
'rValue=xmlhttp.responseXML.selectSingleNode("string")    'use XPATH as input argument
' or you can get response XML
rValue=xmlhttp.responseXML
Set xmlhttp=nothing

'------------------------------------------------------

'******* USING POST METHOD
Dim wsurl="http://server1/Logger_WebService/service.asmx/Greeting"
Dim xmlhttp
Set xmlhttp=Server.CreateObject("MSXML2.ServerXMLHTTP")
xmlhttp.open "POST",wsurl,false
xmlhttp.send "stringeli=g"
Dim rValue
rValue=xmlhttp.responseXML.selectSingleNode("string")
' or you can get response XML
' rValue=xmlhttp.responseXML
Set xmlhttp=nothing

'------------------------------------------------------

Response.Write consumeWebService() 

Function consumeWebService() 
    Dim webServiceUrl, httpReq, node, myXmlDoc 

    webServiceUrl = "http://server1/Logger_WebService/service.asmx/Greeting?stringel=g"

    Set httpReq = Server.CreateObject("MSXML2.ServerXMLHTTP") 

    httpReq.Open "GET", webServiceUrl, False 
    httpReq.Send 

    Set myXmlDoc =Server.CreateObject("MSXML.DOMDocument")
    myXmlDoc.load(httpReq.responseBody) 

    Set httpReq = Nothing 

    Set node = myXmlDoc.documentElement.selectSingleNode("string/*")

    consumeWebService = " " & node.text

End Function

'------------------------------------------------------

  Response.Write(Helou())

  Public Function Helou()
     SET objSoapClient = Server.CreateObject("MSSOAP.SoapClient")
     objSoapClient.ClientProperty("ServerHTTPRequest") = True

    ' needs to be updated with the url of your Web Service WSDL and is
    ' followed by the Web Service name
    Call objSoapClient.mssoapinit("http://server1/Logger_WebService/service.asmx?WSDL", "Service")

    ' use the SOAP object to call the Web Method Required  
    Helou = objSoapClient.Greeting("g")    
  End Function

I seriously have no idea why nothing works, I've tried them every which way with loads of different settings etc. One possible issue is that the web service is located on a server which in ASP.Net required me to input this "[ServiceVariableName].Credentials = System.Net.CredentialCache.DefaultCredentials". I do this from within company network, and there are some security and authorization issues.

I only need to be able to send information anyhow, not receive, as the actual method I will be using is going to insert information into a database. But for now, just getting the Hello World thingie to work seems to provide enough challenge. :)

Thx for all the help. I'll try to check back on holiday hours to check and reply to the comments, I've undoubtedly left out needed information.

Please, talk as you would to an idiot, I'm new to this so chances are I can understand better that way. :)

From stackoverflow
  • You might be missing the SOAPAction header. Here's a working example:

    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class GreetingService : WebService
    {
        [WebMethod]
        public string Greet(string name)
        {
            return string.Format("Hello {0}", name);
        }
    }
    

    And the calling VBS script:

    Dim SoapRequest
    Set SoapRequest = CreateObject("MSXML2.XMLHTTP")
    
    Dim myXML 
    Set myXML = CreateObject("MSXML.DOMDocument")
    
    
    myXML.Async=False
    SoapRequest.Open "POST", "http://localhost:4625/GreetingService.asmx", False
    SoapRequest.setRequestHeader "Content-Type","text/xml;charset=utf-8"
    SoapRequest.setRequestHeader "SOAPAction", """http://tempuri.org/Greet"""
    
    Dim DataToSend
    DataToSend= _
        "<soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:tem=""http://tempuri.org/"">" & _
            "<soapenv:Header/>" & _
            "<soapenv:Body>" & _
                "<tem:Greet>" & _
                    "<tem:name>John</tem:name>" & _
                "</tem:Greet>" & _
            "</soapenv:Body>" & _
        "</soapenv:Envelope>"
    
    SoapRequest.Send DataToSend
    
    If myXML.load(SoapRequest.responseXML) Then
        Dim Node
        Set Node = myXML.documentElement.selectSingleNode("//GreetResult")
        msgbox Node.Text
    
        Set Node = Nothing
    End If
    
    Set SoapRequest = Nothing
    Set myXML = Nothing
    
  • You might consider writing a bit of .NET wrapper code to consume the web service. Then expose the .NET code as a COM object that the ASP can call directly. As you've seen, there is no tooling to help you in classic ASP, so consider using as much .NET as possible, for the tooling. Then, use COM to interoperate between the two.

  • Might want to double-check the version of the MSXML components. Are you using Windows Authentication? I've noticed some odd XML parsing problems with IIS 7, Classic ASP, and MSXML.

    It would also help to get a useful error. Check the ** myXML.parseError.errorCode** and if its not 0 write out the error.

    Reference Code:

    If (myXML.parseError.errorCode <> 0) then
        Response.Write "XML error: " & myXML.parseError.reason
    Else
        'no error, do whatever here
    End If
    'You get the idea...
    
  • A colleague finally got it working after putting a whole day into it. It was decided that it's easier by far to send information than it is to receive it. Since the eventual purpose of the web service is to write data to the DB and not get any message back, we attempted the thing by simply writing a file in the web service.

    The following changes were needed:

    First, in order to get it to work through the company networks, anonymous access had to be enabled in IIS.

    The web service needed the following change in the web.config:

    <webServices>
      <protocols>
        <add name="HttpGet"/>
      </protocols>
    </webServices>
    

    And the web service code-behind was changed like so:

    <WebMethod()> _
        Public Function Greeting(ByVal stringel As String) As String
    
            Dim kirj As StreamWriter
            'kirj = File.CreateText("\\server1\MyDir\Logger_WebService\test.txt")
            'if run locally, the line above would need to be used, otherwise the one below
            kirj = File.CreateText("C:\Inetpub\serverroot\MyDir\Logger_WebService\test.txt")
    
            kirj.WriteLine(stringel)
            kirj.Close()
            kirj.Dispose()
    
            Return stringel
        End Function
    

    As we got the above to work, it was a simple matter of applying the same to the big web method that would parse and check the info and insert it into the database.

    The classic asp code itself that needs to be added to the old page, which was the biggest problem, turned out to be relatively simple in the end.

    function works()
        message = "http://server1/mydir/logger_webservice/service.asmx/Greeting?" & _
          "stringel=" & "it works"
        Set objRequest = Server.createobject("MSXML2.XMLHTTP")
    
        With objRequest
        .open "GET", message, False
        .setRequestHeader "Content-Type", "text/xml"
        .send
        End With
    
        works = objRequest.responseText
    end function
    works()
    

    Took about a week's worth of work to get this solved. :/ The hardest part was simply not ever knowing what was wrong at any one time.

no mapping between account and security windows service

During the setup of windows service I get the error:

error 1001 no mapping between account and security windows service We use a custom user account for the server. (administrator account)

From stackoverflow
  • It sounds to me like you may not be fully qualifying the account name that you are using for your service. While this link may be slightly off topic I think it should be helpful.

Add metadata to an XSD definition

Hi.

Not all that familiar with XSD, I wonder if it is possible to do the following:

<xs:group name="SomeGroup">
    <xs:sequence>
        <xs:element name="Groupingcode" type="OurType" origin="DB" />
        <xs:element name="Description" type="StringType" origin="XML" />

To explain: I have an XSD schema file. I need to generate an XML file according to the XSD (this part works fine) containing database data. However, some elements need additional data to be able to find the proper field to get from the database. That's where the origin tag would come in. It would allow me to describe in the XSD where to look for the data. The tag need not be present in the generated XML, but if possible that same XSD would be used to validate the generated XML. Another way would be to use a separate XML file to describe this, I know. But I would like to know if it would at all be possible to do this in my XSD.

The above fragment would generate to the following XML:

<SomeGroup>
    <Groupingcode>None</Groupingcode>
    <Description>This item does not belong to any group.</Description>

Hope this makes sense.

From stackoverflow
  • Go right ahead. Just put your extra attributes into a namespace of your own, and create a schema that defines them. Microsoft does this for the .XSD files generated when you create a DataSet.

Library or any API for plotting dendrograms

I have an MySQL database which contains some data,it interacts with JSP pages,the thing is that I have to plot dendrograms from various files stored in the database.

I found some java API for this like JTree or others, but I'm not familiar with java, so I am wondering if there is an alternative to do it with a CGI or php pages that call a program or something.

Any idea or suggestion is welcome.
Thanks in advance.

From stackoverflow
  • GraphViz

  • This is many months later, but the machine-learning toolkit orange: http://www.ailab.si/orange/

    lets you draw dendrograms. You would not need many lines of python code to glue this together as a CGI program.

Sign in into a page using PHP

I have a PHP engine login page which i want to sign in using another PHP file without me physically inputting the details on that page, so i should be able to run a PHP file and sign into another login page on my server

From stackoverflow
  • If it's a HTTP authentication, use cURL with options CURLOPT_HTTPAUTH and CURLOPT_USERPWD

  • simply have your other PHP file post the required login credentials to your login page's action url

  • I'm confused, I don't know if I really understood your question! But if it's the case, just send the details of your login form through a post method. And in this other page you'll just check if the login & password are good and start a session for this user!

  • without me physically inputting the details on that page

    sounds like XSRF :P

    Just duplicate the login page with the exact same form actions, method and input names and name it whatever you want and host it on your server. Does that answer the question?

    rzlines : I have a whole php component installed on my server, i want to automate the process of logging in to that system without changing those PHP files so my code will work with future versions of the PHP component
  • Assuming this php login page is part of the same site, then should it not just be a case of setting the required session variables / cookies from your other php file? This seems pretty straightforward to me.

    (Note that the above would assume that your other php file has some kind of login process - if it does not, then just set the post action to the url of the php login page).

  • i suggest you give us more detailed information to enable us help you better. because we can't seem to get a full understanding of what you really want to achieve.

DateTime in Calendar Extender

Hi guys, I am using calendarextender control in asp.net.It displays only date ,not time.But while inserting to database ,time is inserted automatically.But while retrieving the data from database using date in where condition ,no correponding records displays.What modification in storedprocedure i can do to resolve this problem.

From stackoverflow
  • The problem you are most likely encountering is that if you are looking for a date equal to 3/11/2009 you'll probably never find it, because of the time stamp. A few methods you could use to change the strored procedure would be to consider the range for the date:

    Using the Between Statement will give you an inclusive range

    Select myname,mydate from sometable 
        where mydate between 3/10/2009 and 3/11/2009
    

    Or

    Using > and < to give you an exclusive range

    Select myname,mydate from sometable 
        where mydate >3/10/2009 and mydate < 3/12/2009
    

    Or

    Leverage the DateAdd function to strip the time off the field. There are some good examples of this at the SQLTeam Blog

    dateadd(dd,0, datediff(dd,0,myDate))
    

    Or If you can change the Table itself and you are using SQL Server 2008 you could use the new SQL Server 2008 Date DataType, a date with no time component to deal with. There's a good blog over on MSDN blogs about the new Date and Time enhancements in SQL Server 2008.

    Don't forget you could also look into the insert procedure(if applicable) and zero out the time.

    Also when dealing with datetime make sure to factor in >= and <= so you don't miss any records.

    Hope this gives you enough options to solve your problem.

Display Full Name in ASP.NET LoginName control

I have an .aspx page using a login control with custom authentication. I was wondering if it's possible to have a "Welcome [FirstName] [LastName]" message using the LoginName control instead of the [UserName] that is accessed by default.

I'm thinking of storing these info in the Session object if it's not possible.

Thanks!

From stackoverflow
  • You'll need to override the RenderContents method or make your own LoginName control. Something like this will do the trick:

    protected override void RenderContents(HtmlTextWriter writer)
    {
          if (string.IsNullOrEmpty(Profile.FullName))
                return;
    
          nameToDisplay = HttpUtility.HtmlEncode(Profile.FullName);
          string formatExpression = this.FormatString;
          if (formatExpression .Length == 0)
          {
                writer.Write(nameToDisplay);
          }
          else
          {
                try
                {
                      writer.Write(string.Format(CultureInfo.CurrentCulture, formatExpression, new object[1] { nameToDisplay });
                }
                catch (FormatException exception)
                {
                      throw new FormatException("Invalid FormatString", exception1);
                }
          }
    }
    

    Also, see here for a brief article on working with LoginName.

    Leon Tayson : I'm not using the default ASP.NET providers and not using Profile also. I settled with storing the user's full name in the session object instead. Thanks!
  • First of all, see http://stackoverflow.com/questions/620118/personal-names-in-a-global-application-what-to-store. Even if your site is limited to the US, I'm pretty sure I've seen some foreigners around here.

  • You could use the FormatString property to set the welcome message to any string you want. When combined with expression builders (e.g. <%$ expressionPrefix: expressionValue %>) you would have a flexible way to define output.

ASP.NET/UserControls: How do I sepparate the "controller" from the "view"?

Is it possible to sepparate the ascx ("view") and the ascx.cs ("controller") pars of a user control. Id like to move the controller part to App_Code to be resued while the view part is changed between projects?

From stackoverflow
  • Yes, write the codebehind in some service class which extends UserControl, and in your .ascx file inherit that class

    <%@ Control
    Language           = "C#"
    Inherits           = "Project.Business.Service.MyControl"
    %>
    
    Niels Bosma : How do I reference childcontrols of that control?
    Spikolynn : If in your .ascx file you have a control In control code define protected Label myLabel, then set myLabel.Text = "x" for instance.
  • In regular ASP.NET, even if you separate the code-behind and the ascx - they are still tightly coupled. It isn't a true "controller" (as separate from a view).

    If you want this purity, consider ASP.NET MVC, which (obviously) addresses this in a different way.

defined? method in Ruby and Rails

I have a quite old templating system written on top of ERB. It relies on ERB templates stored in database. Those are read and rendered. When I want to pass data from one template to another I use the :locals parameter to Rails render method. For setting default variables of those variables in some templates I use the defined? method which simply tells me if local variable has been defined and if not I initialize it with default value like this:

unless defined?(perex)
  perex = true
end

I am upgrading the app to latest Rails and I see some weird behavior. Basically this sometimes works (sometimes perex is undefined) and sometimes it does not (perex is defined and set to nil). This happens without anything else changing.

I have two questions: Is there any better way other than using defined? which is proving unreliable (was reliable for several years on top Rails 1.6)? Such a way should not result in me rewriting all the templates. I have been going through Ruby docs and was not able to find anything about defined? method. Was it deprecated or am I just plain blind?

Edit: The actual issue was caused by what seems to be a Ruby/eRB bug. Sometimes the unless statement would work, but sometimes not. The weird thing is that even if the second line got executed perex stil stayed nil to the rest of the world. Removing defined? resolved that.

From stackoverflow
  • First: actually, defined? is an operator.

    Second: if I understand your question correctly, the way to do it is with this Ruby idiom:

    perex ||= true
    

    That'll assign true to perex if it's undefined or nil. It's not exactly what your example does, since yours doesn't evaluate the assignment when the value is nil, but if you are relying on that then, in my opinion, without seeing it, you're not writing clear code.

    Edit: As Honza noted, the statement above will replace the value of perex when it's false. Then I propose the following to rewrite the minimum number of lines:

    perex ||= perex.nil?  # Assign true only when perex is undefined or nil
    
    Honza : This is not true. perex ||= true does the same as perex = perex || true which sets perex to true if it is undefined, nil or false. The last case would break everything.
  • The safest way of testing if a local is defined in a Rails template is:

    local_assigns[:perex]
    

    This is documented in the Rails API together with the explanation that defined? cannot be used because of a implementation restriction.

  • Per mislav's answer, I went looking for that documentation in the Rails API, and found it in Class ActionView::Base (under the heading "Passing local variables to sub templates"). It was hardly worth the search, though, since it barely said anything more than mislav did. Except that it recommends this pattern:

    if local_assigns.has_key? :perex
    

What is the name of this factory type pattern and how do I represent it in UML?

Example: I have several types, e.g. Wheel, Brake, Engine, Clutch, AutoBox, ManualBox, ElectricWindow, RearParkingSensor, HeatedSeats. These will all inherit a ICarPart marker interface (could be an attribute (java annotation), but doesn't matter at this stage).

I then write my Car class that can represent all car types, e.g.

class Car
{
    string Name;
    DateTime creationDate;
    string ID;

    IList<ICarPart> parts;
}

I then write a factory to create cars. The factory could refer to some XML which is an ingredients list for different car types. E.g. (and please ignore format, this is just for illustration):

<ExpensiveCar>
  <Name>Expensive Car</Name>
  <Parts>
    <HeatedSeats/>
    <Wheel count=4/>
    <RearParkingSensor/>
    <ElectricWindow type=FrontAndBack/>
  </Parts>
</ExpensiveCar>

The factory would parse this ingredients list and create the car object. New car types would be available to the system providing the parts had been coded and the ingredient list XML written.

Questions:

  1. What is this pattern called? Or is it just multiple patterns combined?
  2. Is any of this an antipattern?
  3. How do I represent this in a UML? I could do a class diagram for the parts and for the base car class. How would I show the instances of that class that are currently supported and the parts they have?

Thanks in advance. If any of this is unclear please comment and I'll amend/udpate/provide more details.

From stackoverflow
  • What is this pattern called? Or is it just multiple patterns combines?

    You have the factory method pattern (creating car objects) and good-old composition (creating a car out of wheel, seat etc). The latter is a variation of composition.

    ng5000 : Is the use of an "ingredients list" and dynamically building the objects just an extension of 'factory method' or is it a different pattern?
    ng5000 : Not sure this is "private inheritance" as the car will not inherit any of the part objects. Rather it is composed of them but in a dynamic fashion and by interface rather than concrete type.
    dirkgently : Right. That's composition, then. Will edit.
  • I think this may be the Abstract Factory Pattern, as you want the set of parts to be compatible with each other. You probably don't want truck tires on a compact car's wheels.

    1. What is this pattern called? Or is it just multiple patterns combined?

    The pattern described is the Builder Pattern. The builder pattern builds complex objects from a set of simpler parts. Sometimes the objects built by the builder pattern are Composite Objects (though not neccessarily in the question's case).

    The builder pattern is often demonstrated using hard coded ingredients lists, though there is nothing in the pattern that requires this, nor does there seem to be a specific pattern documented describing the "ingredients list" approach.

    1. Is any of this an antipattern?

    No

    1. How do I represent this in a UML?

    Probably by:

    1. Define the class diagram showing the parts as classes as well as the Car class. Show that each part class implements the ICarPart interface.
    2. Perhaps on a seperate (but linked) class diagram show named instances of the car class using the UML instance notation. The instance class representation allows you to specify the values that attributes have in that class, e.g.
    ------------------------------------------
    |ExpensiveCar : Car                      |
    ------------------------------------------
    |parts = {                               |  
    |HeatedSeats,                            |
    |Wheel (count = 4),                      |
    |RearParkingSensor,                      |
    |ElectricWindows (type = FrontAndBack) } |
    ------------------------------------------
    

    Note that because this is an instance the text "ExpensiveCar : Car" should be underlined but SO doesn't allow me to do this.

    The notation I've used here to initialise an array with parts isn't great and might not be the best approach. Perhaps an alternative would be to add a UML note containing the actual XML. The important thing is that a client can see what makes an expensive car and so can a programmer.

    Ted Johnson : Cool, you answered your own question. Thanks for sharing as all to often the post just dies.

Automatically add properties when running JUnit in Eclipse

In order to run my unit tests on my Eclipse, I need to set some properties for the VM.

Thus, when I first run my JUnit test, I go in "Open Run Dialog", then in my JUnit configuration for this test, I go in "Arguments" tab and put everything I need in the "VM arguments" text area.

Is there a way to automatically add a set of properties when I run my JUnit, so I will be able to only right-click on the test class, and click on "Run as > Junit Test" to run a test?

Technical information: Eclipse 3.3.2, JUnit 4, Java 5


Edit, regarding response from Aaron Digulla:

These properties are used in Spring configuration files*. Thus, I can't use the idea given by Aaron, as Spring will be initialized before the test is run.

In addition to that, I just need to know if I can achieve that in a easy way in Eclipse. Thus the solution must not have any impact on the compilation of the application outside Eclipse, as my application will finally be compiled (and tested) by Maven2.

* few "unit" tests indeed need my Spring configuration to be run. Ok, I know that it is not real unit tests ;o)

Edit 2: In fact, I was indeed starting the Spring configuration by a test unit. Thus, before starting Spring, I check the System properties, and if my properties are not set, then I give them the required value...

However, I am a little disappointed that Eclipse can't do that for me automatically...

From stackoverflow
  • My solution is to create an abstract test base class for all tests in a project which extends TestCase. It has to be abstract to the automatic unit test finder will not consider it.

    In static code block of this class, I set all properties I need. This ensures that the code runs once and only once and that it runs before any test in my project.

    [EDIT] You say that Spring is initialized before the tests run. This is a bug in your project: It must be the tests who initialize Spring. Otherwise, you will always run into the problem that you have to test something outside of your control.

    Therefore, I suggest to move the Spring init code into a place where you can call it at the point in time when the environment is ready.

    Alternatively, check that the environment is correctly set up in setUp() and throw an error if a property is missing. This way, you will at least know why the tests would fail later. But I still prefer to have total control when which subsystem comes to life. Anything else just begs for disaster.

    romaintaz : I can't use your idea, as explained in my Edit (I don't downvote it as it is not a bad idea, however)...
  • When i want to set some properties entries for my junit test i implement the following

    protected void setUp() throws Exception {
            super.setUp();
    
            System.setProperty("Property1", "value1");
            System.setProperty("Property2", "value2");
    }
    

    The properties are set before the test methode is called

    EDIT: You also can read the properties from a file and at thes to the System properties

    romaintaz : Same remark as for Aaron Digulla answer. It will not work if the properties are used by Spring...
    Markus Lausberg : You should initialize all values and objects inside the setup method. Otherwise update the testcases.
  • I never understood why the launch configurations have a way to define environment variables but the only way of adding a system property seems to be to add vm arguments.

    The way I've worked around this is to have tests (or an abstract tests base class) test for the presence of required properties, if they aren't there then I load them from a .properties file on the classpath.

    This works as I can still override them or specify them from ANT or Maven but can also 'right click' -> Run As -> Junit Test the individual test files.

    edit: here is an example of getting Spring to optionally load a properties file in the same manner as described above:

    <bean id="placeholderConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
           <property name="location" value="database.properties"/>
           <property name="ignoreResourceNotFound" value="true" />
           <property name="systemPropertiesMode">
            <util:constant static-field="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer.SYSTEM_PROPERTIES_MODE_OVERRIDE" />
           </property>
    </bean>
    
  • You could try this - go to

     Window->Preferences->Java->Installed JREs
    

    ans select the JVM in use, than put a "Default VM" prameter like

      -DrunningInEclipse
    

    Than you can check from within your TestCase:

       System.getProperty("runningInEclipse") != null
    

Converting HTML Files to PDF

I need to automatically generate a PDF file from an exisiting (X)HTML-document. The input files (reports) use a rather simple, table-based layout, so support for really fancy javascript/css stuff is probably not needed.

As I am used to working in Java, a solution that can easily be used in a java-project is preferable. It only needs to work on windows systems, though.

One way to do it that is feasable, but does not produce good quality output (at least out of the box) is using CSS2XSLFO(http://re.be/css2xslfo/index.xhtml), and Apache FOP to create the PDF files. The problem I encountered was that while CSS-attributes are converted nicely, the table-layout is pretty messed up, with text flowing out of the table cell.

I also took a quick look at Jrex, a Java-API for using the Gecko rendering engine.

Is there maybe a way to grab the rendered page from the internet explorer rendering engine and send it to a PDF-Printer tool automatically? I have no experience in OLE programming in windows, so I have no clue what's possible and what is not.

Do you have an idea?

edit: The flying saucer/iText thing looks very promising. I will try to go with that.

Thanks for all the answers

From stackoverflow
  • If you have the funding, nothing beats Prince XML as this video shows

  • You can use a headless firefox with an extension. It's pretty annoying to get running but it does produce good results.

    Check out this answer for more info.

  • The Flying Saucer XHTML renderer project has support for outputting XHTML to PDF. Have a look at an example here.

  • Check out iText; it is a pure Java PDF toolkit which has support for reading data from HTML. I used it recently in a project when I needed to pull content from our CMS and export as PDF files, and it was all rather straightforward. The support for CSS and style tags is pretty limited, but it does render tables without any problems (I never managed to set column width though).

    Creating a PDF from HTML goes something like this:

    Document doc = new Document(PageSize.A4);
    PdfWriter.getInstance(doc, out);
    doc.open();
    HTMLWorker hw = new HTMLWorker(doc);
    hw.parse(new StringReader(html));
    doc.close();
    
  • If you look at the side bar of your question, you will see many related questions...

    In your context, the simpler method might be to install a PDF print driver like PDFCreator and just print the page to this output.

  • There is a PHP class which can perform such an operation.

    The web site is at http://www.rustyparts.com/pdf.php

  • Is there maybe a way to grab the rendered page from the internet explorer rendering engine and send it to a PDF-Printer tool automatically?

    This is how ActivePDF works, which is good means that you know what you'll get, and it actually has reasonable styling support.

    It is also one of the few packages I found (when looking a few years back) that actually supports the various page-break CSS commands.


    Unfortunately, the ActivePDF software is very frustrating - since it has to launch the IE browser in the background for conversions it can be quite slow, and it is not particularly stable either.

    There is a new version currently in Beta which is supposed to be much better, but I've not actually had a chance to try it out, so don't know how much of an improvement it is.

    panschk : Thanks for the helpful answer. I don't think ActivePDF is really suitable because of the price, but it's good to know something like that exists.
  • If you have php installed, try fpdf. It's at http://fpdf.org

    panschk : I already used FPDF for a web project. It is not useful for what I want to do, because you have to build your PDF document step by step. You can't just feed it an HTML document and get a PDF doc back.
  • Did you try WKHTMLTOPDF ?

    It's an open source implementation of webkit. Both are free.

    We've set a small tutorial here

    MGOwen : For a straight html-page-to-pdf conversion, this is better than anything else I've seen, free or commercial.
  • I believe dompdf hasn't been mentioned yet.

setting maxlength using javascript

I'm trying to set the maxlength on input fields dynamically using JavaScript. Apparently that is a problem in IE, and I found part of the solution.

$("input#title").get(0).setAttribute("max_length", 25);
$("input#title").get(0).setAttribute(
                        "onkeypress", 
                        "return limitMe(event, this)");

function limitMe(evt, txt) {
    if (evt.which && evt.which == 8) return true;
    else return (txt.value.length < txt.getAttribute("max_length");
}

It works in Firefox, but not in IE for some reason. However, it works on input fields set like this:

<input type="text" max_length="25" onkeypress="return limitMe(event, this);"/>

But since the input fields are created dynamically, I can't do this... Any ideas?

From stackoverflow
  • The attribute you're looking for is maxlength, not max_length. See here.

    peirix : Sorry, I should have included the fact that you can't set "maxlength" dynamically in IE.
  • If you're using jQuery then why not make full use of its abstractions?

    E.g.

    Instead of:

    $("input#title").get(0).setAttribute("max_length", 25);
    $("input#title").get(0).setAttribute(
                            "onkeypress", 
                            "return limitMe(event, this)");
    function limitMe(evt, txt) {
        if (evt.which && evt.which == 8) return true;
        else return (txt.value.length < txt.getAttribute("max_length");
    }
    

    Do this:

    $('input#title').attr('maxLength','25').keypress(limitMe);
    
    function limitMe(e) {
        if (e.keyCode == 8) { return true; }
        return this.value.length < $(this).attr("maxLength");
    }
    


    Edit: The reason it's not working in IE is probably because of how you attached the 'onKeyPress' handler, via setAttribute. - This isn't the proper way to register event handlers.

    peirix : and I found that jQuery's attr() actually manage to set maxlength the proper way, so I don't have to use my own function. Excellent! Thanks, man (:
  • Don't forget though that if you are setting the maxlength via JavaScript, someone else could just as easily change the maxlength to whatever they like. You will still need to validate the submitted data on the server.

How to specify table name in Fluent NHibernate ClassMap class?

Hi I am newbie to NHibernate and trying to use Fluent for mapping. My entity class name is different from the database table name it has to be mapped to. I am using mapping class derived from ClassMap<>, but I can't specify the table name: the property TableName from ClassMap is read-only.

Thanks for your help.

From stackoverflow
  • Use WithTable("table_name") instead.

    Chin : This is now. As of Sept 2009 Table("table_name");

MSDTC Service on SQL server 2005

How do I Start the MSDTC service on SQL Server 2005?

From stackoverflow
  • Microsoft Distributed Transaction Coordinator is not "on SQL Server" per se - it is a normal Windows Service. To start it, go to the command prompt and enter:

    net start msdtc
    
  • If you want to get access to MSDTC administration UI, go to Administration=>Component Services=>Local Computer. There you'll be able to manage the MSDTC via GUI.

Deleting duplicate records using a temporary table

Take the tsql query below:

DECLARE @table TABLE(data VARCHAR(20))
INSERT INTO @table VALUES ('not duplicate row')
INSERT INTO @table VALUES ('duplicate row')    
INSERT INTO @table VALUES ('duplicate row')    
INSERT INTO @table VALUES ('second duplicate row')    
INSERT INTO @table VALUES ('second duplicate row')

SELECT   data    
INTO     #duplicates    
FROM     @table    
GROUP BY data    
HAVING   COUNT(*) > 1    

-- delete all rows that are duplicated   
DELETE   FROM @table    
FROM     @table o INNER JOIN #duplicates d
         ON d.data = o.data         

-- insert one row for every duplicate set    
INSERT   INTO @table(data)    
         SELECT   data    
         FROM     #duplicates

I understand what it is doing, but the last part of logic (after --insert one row for every duplicate set), doesn't make sense. Where we have the set of code for --delete all rows that are duplicated, that gets rid of the duplicates so what's the part of the last section?

This query was found here

Thanks

From stackoverflow
  • Where we have the set of code for --delete all rows that are duplicated, that gets rid of the duplicates so what's the part of the last section?

    First, it deletes all rows that ever had duplicates. That is, all rows, and original also. In the case above, only one row ('not duplicate row') will remain in the table after DELETE. All four other rows will be deleted.

    Then is populates the table with the deleted rows again, but now the duplicates are removed.

    This is not the best way to delete duplicates.

    The best way is:

    WITH q AS (
              SELECT data, ROW_NUMBER() OVER (PARTITION BY data ORDER BY data) AS rn
              FROM @table
              )
    DELETE
    FROM      q
    WHERE     rn > 1
    
    Quassnoi : You mean, select all instances of rows that have duplicate values?
  • The delete call deletes all matching records.

    Because all duplicated rows have been deleted the last piece reinserts a single row.

  • Create table Test (Test1 int not null , Test2 varchar(10) null )
    
    
    Insert Into Test 
    
    Select 12, 'abc'
    
    UNion All 
    
    Select 13 , 'def'
    
    
    
    Insert Into Test 
    
    Select 12, 'abc'
    
    UNion All 
    
    Select 13 , 'def'
    
    
    
    Select * From Test 
    
    WITH t1 AS 
    
    (SELECT ROW_NUMBER ( ) OVER ( PARTITION BY test1, test2 ORDER BY test1) 
    
    AS RNUM FROM Test )
    
    DELETE FROM t1 WHERE RNUM > 1
    

How to avoid double backslash in MySQL's SELECT INTO OUTFILE

In MySQL, the following:

SELECT '\\' INTO OUTFILE 'c:/temp/backslash.dump';

writes two backslashes to the file, which makes sense.

Trying to dump a single backslash, I changed SQL_MODE, like that:

SET SESSION SQL_MODE='NO_BACKSLASH_ESCAPES';
SELECT '\' INTO OUTFILE 'c:/temp/backslash.dump';

but got two backslashes again.

Is there a way to dump a single backslash?

From stackoverflow
  • Do this:

    SELECT '\\' INTO OUTFILE 'c:/temp/backslash.dump' FIELDS ESCAPED BY '|';
    

TKProf Output: SQL*Net message from client

Hi all,

I am currently in the process of debugging a database performance issue. I have run extended trace on the suffering oracle box to obtain a trace file which I have analyzed using tkprof.

One thing that caught my eye straight away was the following output;

  Elapsed times include waiting on following events:
  Event waited on                             Times   Max. Wait  Total Waited
  ----------------------------------------   Waited  ----------  ------------
  SQL*Net message to client                       4        0.00          0.00
  SQL*Net message from client                     4      109.06        141.31

I have run the relate query manually via a SQL client an it executes in a timely fashion. So I don't think its cause directly by the query.

Can some one clarify what exactly "SQL*Net message from client" means ?

Does anyone have any idea what could be causing such large wait times ?

Thanks in advance

Karl

From stackoverflow

Automatic Entry Exit trace in C

Do i have to add entry and exit logs in all the C functions?

If, so are there any possible ways to write the entry and exit of a function automatically (Similar to Automatic Entry/Exit using Aspect oriented Programming in java).

The application that I'm writing is time critical and adding entry/exit statements for each function might delay the performance and also makes the code non-readable.

From stackoverflow
  • First of all. If you want to log something it will take time, no matter how you accomplish it. That being by aspect programming or something else. If your application is time critical you should have some switch to turn on/off debugging.

    Update: Checkout http://perfinsp.sourceforge.net/hookit_linux.html

    dmckee : Subtwo has the google-foo. Nice catch.
    Vibin Vijay : Thanks for the link. Let me have a look.
  • Do you want this for a debugging environment (where ptrace or similar tools (dtrace, ...) might do) or for on-going use?

    Vibin Vijay : Currently I require this for debugging (I do not prefer using ptrace or similar tools for the same).
  • C does not support any form of introspection or doing stuff automatically through magic in the runtime or on the virtual machine; there is no virtual machine, and the runtime support is basically just libraries of "dead" code that provide standard functionality.

    And as Subtwo pointed out, if you want to do something (like log entry/exit), it will have to be done and thus take time. You can't just "hide" that penalty, there is very little overhead to put it in.

    A standard profiler might give you some insight, by sampling your program statistically to see which functions execute, but that will not give you the call order, just random locations where your program was executing code at the time it was sampled.

    You could perhaps turn to some preprocessor trickery, this is a common way to do "boilerplate" stuff like logging, by for instance defining some macros that you then put at the entry/exit points of each function. Still, you'd have to remember including the macros, and any performance penalty from doing the logging will of course be present.

  • Check out AspectC, a variant of C extended with aspect-oriented features (just like AspectJ is a variant of Java with aspect-oriented features).

What exactly does display:block; do to an element?

What are the exact specs of display:block? I know quite a few of the specific things applying this to an element will do but I would like to hear them all.

Thanks.

From stackoverflow
  • Quote from W3C

    In a block formatting context, boxes are laid out one after the other, vertically, beginning at the top of a containing block. The vertical distance between two sibling boxes is determined by the 'margin' properties. Vertical margins between adjacent block boxes in a block formatting context collapse.

    In a block formatting context, each box's left outer edge touches the left edge of the containing block (for right-to-left formatting, right edges touch). This is true even in the presence of floats (although a box's content area may shrink due to the floats).

  • From the CSS2 spec:

    This value causes an element to generate a block box.

    More info can be found on Quirksmode

  • Autistic Cuckoo's article about display properties and their differences (part 1, part 2, part 3) is also a recommended read.

WPF: Returning a method AFTER an animation has completed

With reference to this programming game I am currently building.

I have a Class Library (dll) that will have a method Run which will be composed of something like such:

public class MyRobot : Robot 
{
    public void Run(} 
    {
        while (true) 
        {
           Ahead(200); //moves the bot 200pixels
           TurnLeft(90); //turns the bot by 90deg 
        }
    }
}

In those methods (inherited from Robot), the system will animate the robot using WPF (using BeginAnimation or the DispatcherTimer).

Now, the problem is that I don't a method to return (ie, move on to the next method) before completing the current one, because that will result in the animations taking place together, and when in an infinite loop (like the one above), that's especially not good.


My question is, what is the best way to prevent a method from returning before completing the animation ?

I currently have a bool in the Robot class (isActionRunning) that be flagged to true when an action starts running and then changes to false in an animation callback (using the Completed event if using BeginAnimation).

At the end of each method (after invoking BeginAnimation) I placed the following loop :

while (isActionRunning) 
{
    Thread.Sleep(200); //so that the thread sleeps for 200ms and then checks again if the animation is still running 
}

This is so that the method won't return before the animation finishes.

But I feel that this is not the right way to do this.

Can anyone guide me to what's best to achieve this ?

From stackoverflow
  • I would do something similar to what you described. I recently worked on something where I called a bunch of asynchronous operations, and I wanted to wait for them all to complete before calling another operation. I created a collection to represent all of the operations currently executing and instead of adding items to the collection directly, I created methods for adding and removing. The remove method had logic that said "lock the collection, remove the key provided, and if empty call the next operation". You could create a similar mechanism like this where a collection scoped at the application or window keeps track of operations being executed. You add a key to the collection and pass this key to your async operation. When the async operation completes, lock the collection and remove the key. Then you can have a loop that blocks your method from returning while the collection contains the key (with optional logic for adding a timeout or any other additional ways where you might want the method to be able to return and not be blocked forever).

    This might be overkill, but I have limited experience with this issue myself. For all I know, .Net might even have a canned solution to this problem that works with one or two lines of code.

  • Here's one option, it will only work if the Robot.Run code is running in a different thread than the UI thread doing the animations.

    In the Robot.Ahead method (for example), use Dispatcher.Invoke (not BeginInvoke) to call the method that starts the animation, than add a lock on the robot with an empty block( lock(this) { } ).

    In the method that starts the animation call Monitor.Enter(robot) before starting the animation

    In the animation complete handler call Monitor.Leave(robot)

    The result will be

    time      robot thread          UI thread  
      |       ---------------       --------------  
      |       call Invoke    --->  
      |                             lock robot (Monitor.Enter)  
      |                             begin animation  
      |       Invoke returns <---   return  
      |       lock(this)            (animation running)  
      |       (wait for lock  
      |       to become available)  
      |  
      |                             Animation complete  
      |                             release lock (Monitor.Exit)  
      |       (lock available,  
      |       continue running)  
      |       Release lock (exit lock block)  
      |       Return and start next  
      |       movement  
      \/
    
    Andreas Grech : Excellent, this is great. I have now changed my logic to implement what you suggested, instead of the while(isActionRunning) loop.
    Eric Lippert : This is *crazy*. If you want to wait for one thread to signal another that its current work is done, don't build a signal out of locks, **just use a signal**. There already is an object that does this in the framework; just use it. http://msdn.microsoft.com/en-us/library/system.threading.autoresetevent.aspx
    Nir : @Eric I don't remember why I used locks (I wrote that a year ago after all), It's possible I had a good reason - but I can't think of any so signals are probably the right solution here. However, in my defense, from my experience, mutex-style locks are very robust and predictable while signals turn every future code change into an hard to reproduce race condition (I had to maintain a C++ multi-threading server that used signals for synchronization - signals has so many pitfalls it's just not funny)
  • Building a signalling device out of locks is craziness; just use the signalling device that already exists in the framework.

    http://msdn.microsoft.com/en-us/library/system.threading.autoresetevent.aspx

    That is: thread one says "hey thread two, start this animation and signal me on this wait handle when you're done." Thread one then waits on the waithandle. Thread two starts the animation, and in its completion event, signals the waithandle. Thread one then wakes up again and says "hey thread two, start this other animation..."

    stefan.at.wpf : Hello Eric, I tried like you adviced, however it's not working for me. Could you please have a look at this thread: http://stackoverflow.com/questions/3420901/synchronous-blocking-animations-in-wpf Thank you very much! Anyone else maybe found a solution for the problem of this thread?

C# - Win32: Getting a handle to the topmost window, after it has lost focus?

Hi

Trying to dig into the win32 api from my WPF application (which just runs through the systray).

When clicking on the systray icon, I present the user with a contextmenu, which gains focus over whatever window was topmost.

I want to get a handle to that window (the one, that just lost focus) and have tried with different approaches using

GetForeGroundWindow()
GetTopWindow()
GetDesktopWindow()

To no end however. I'm currently considering iterating through all processes, to get the MainWindowHandles and checking the z-order of each and every window.

But I reckoned that there's an easier/smarter way; simply just one I cannot google or recall from my old Petzold tome.

Another way would be for my systray menu not to gain focus when activated?

Thanks!

From stackoverflow
  • I don't think there is anything simpler than your described z-index iteration. Your systray menu has to get focus, because otherwise people won't be able to use it (for example, with keyboard). And if it gets focus, then it becomes the foreground window, so the old foreground window is left without any distinction from any other inacitve window in the system. Truly, the z-index check IMHO is the only way.

  • You could get the topmost window before opening the menu, regardless of the menu item the user will eventually choose.

    Then, if you need the topmost window, you could just use the value you got before opening the menu.

    Chrysaor : Of course! Trying to find the focus event to override, but currently just making the check with a DispatcherTimer.