Thursday, May 5, 2011

Can I make a TTreeNode invisible?

TTreeNode does not have a Visible property, so the obvious option does not exist. Is there any other way to make a TTreeNode and all its child nodes invisible? Of course I want to be able to make it visible again later.

This is with Delphi 2007.

Note#1: I am aware of the alternative TVirtualTreeView, and I will check it out if there is no easy way to accomplish this with TTreeView.

Note#2: I need the option only for top level nodes. The ones I want to hide usually don't even have children.

From stackoverflow
  • TTreeView is a wrapper for the standard Windows tree view, which (judging from the documentation on MSDN) doesn't allow to hide tree nodes. It does make sense too, as the tree view is known to not scale to a large number of nodes, so hiding tree nodes instead of removing everything that isn't necessary would be a bad idea.

    You can make your life a little easier if you remove and insert only the top level node (the one you wish to hide), and create all child nodes in the OnExpanding event of the re-added node. For that you just need to set the HasChildren property of the node to true.

  • if you want to use a better tree component, why not use Virtualtreeview. It is one of the best components ever developed for Delphi and it's free to use with source! But there is maybe a logical problem with hiding a ttreenode! Should the tree show a + sign when no nodes are visible?

    http://wiki.lazarus.freepascal.org/VirtualTreeview

  • It's a good idea to separate data from the user interface, and this issue with tree views is a good example - don't store data in a tree view. I often have a non-visual unit that contains a structured class that stores data. A user interface unit can have a treeview that can displays (a configurable subset of) data from that class. There are a variety of ways to move data between the two. This type of isolation requires a bit of planning, but provides much greater flexibility and stability.

    dummzeuch : While that is not the answer I wanted to hear, I guess it is the only possible solution so I'll accept it.
  • The only way to "hide" a node in TTreeView is to actually remove it. Then, to "show" the node, you simply re-insert it again.

Flex and Cairngorm Error: C0001E: Only one ServiceLocator instance can be instantiated.

Hey guys,

I’m new to Flex and Cairngorm.While I’m using ServiceLocator,I do run into the problem: Error: C0001E: Only one ServiceLocator instance can be instantiated.

My Code is like this:

In Serives.mxml:

<cairngorm:ServiceLocator xmlns:mx="http://www.adobe.com/2006/mxml"
xmlns:cairngorm="com.adobe.cairngorm.business.*">
<mx:HTTPService id="statistServ"
    url="rooms.xml"
    showBusyCursor="true"
    method="POST"
    resultFormat="array"/>

In Delegate.as,I have snippets:

this.service = ServiceLocator.getInstance().getHTTPService(”statistServ”);

In Main.xml,snippets like:

<business:Service id="service" />

this wonderful little Error message pops up the minute I load a second instance of some module which requires httpservice.

Is there any way to resolve this problem without switching to another Framework?

Best Wishes,

Shuo from China

From stackoverflow
  • The error you're seeing is from Cairngorm's implementation of the Singleton pattern. It's preventing you from creating a second instance of ServiceLocator because the framework requires that there be only one. When loading the second instance of your module, your code is also trying to create a second instance of ServiceLocator when it should be using getInstance() (or not getting an instance at all).

    By declaring your Services tag in Main.mxml, you've created your lone instance of ServiceLocator and it cannot be declared or newed anywhere else. If Main.mxml is part of the module that you're trying to instantiate more than once, that's your problem right there. If not, I can't tell where in your code the problem is based on the limited sample above, but it should be somewhere in the module.

    In reply to comment:

    No problem. You can easily solve your problem by declaring your Service in ActionScript instead of MXML. By declaring a tag in MXML, you're always creating an instance of the corresponding AS class, whereas you instead want to retrieve the lone instance of the singleton. To do this, include the following AS code inside of your module MXML:

    var service:Service = Service(ServiceLocator.getInstance());
    

    That is essentially equivalent of what you're trying to do with the MXML tag, with the exception of not creating a new Service instance.

    However, you still need to instantiate the Service somewhere. To do that, put the Service MXML tag inside of the main MXML of the application which is loading the modules.

    Shuo : Thanks,Stiggler! You're right!In my module,I have in Main.mxml. Each time I open the module,I'm actually instantiating a serviceLocator.As we know,ServiceLocator validates a static variable to see if an instance has already been created in its constructor.But I think the constructor ServiceLocator should be private but current AS3.0 does not allow it. So,is there any way to solve this?As the module is used quite ofen. Much Thanks! Regards,Shuo
    Shuo : Thanks again,Stiggler! I've solved my problems by placing inside of the main MXML of the application instead of the module MXML. You're very helpful! Good luck! Shuo from China
    Stiggler : I'm glad I could help. If you feel this question has been fully answered, please go ahead and mark the answer as accepted.
    Shuo : Hey Stiggler!I'm not sure how to mark the answer as accepted.I'll be glad to mark it if I know the way.
    Stiggler : Just click the check mark icon that appears to the left hand side of this answer :)

xsd attribute and element validation

I am trying to create an XSD schema which will validate the following xml.

<Item ItemGUID="3F2504E0-4F89-11D3-9A0C-0305E82C3301">The name of the item</Item>

I want to validate the max length of the attribute "ItemGUID" to 36 characters and "The name of the item" to a max 25 characters.

How can it be validated to satisfy the above condition using the xsd schema?

From stackoverflow
  • With XML Schema, you can do something like this:

    <xs:element name="Item">
      <xs:complexType>
        <xs:simpleContent>
          <xs:extension base="string25">
            <xs:attribute name="ItemGUID" type="string36" />
          </xs:extension>
        </xs:simpleContent>
      </xs:complexType>
    </xs:element> 
    
    <xs:simpleType name="string25">
      <xs:restriction base="xs:string">
        <xs:minLength value="1"/>
        <xs:maxLength value="25"/>
      </xs:restriction>
    </xs:simpleType>
    
    
    <xs:simpleType name="string36">
      <xs:restriction base="xs:string">
        <xs:minLength value="1"/>
        <xs:maxLength value="36"/>
      </xs:restriction>
    </xs:simpleType>
    

    I haven't tried it, but if this doesn't work it should be very close to what you need.

MSBuild with Visual studio 2005

Hi

Can anyone tell me how to write and run msbuild by using VS 2005?

Thanks

From stackoverflow
  • msbuild file is just a plan text file. you can even write it in notepad and run it from command line. If you would like to run it as part of the build just just

    1. right click on the project
    2. choose Property
    3. goto Build Events tab
    4. create a build event to run msbuild

    For example, create a text file called test.proj:

    <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
       <PropertyGroup>
          <TextToShow>Hello World!!</TextToShow>
       </PropertyGroup>
    
       <Target Name="HelloWorld"> 
          <Message Text="$(TextToShow)" />
       </Target>
    </Project>
    

    and you can run it from command line this way

    msbuild /target:HelloWorld test.proj
    
  • If you want to use MSBuild as the build system for your Visual Studio 2005 projects, you don't have to do anything. .csproj and .vbproj files are MSBuild files. Visual Studio solution files (.sln) can also be passed to MSBuild.exe. Building your project with Visual Studio invokes MSBuild.

    If you need to write code that creates, modifies, and runs msbuild files, the Microsoft.Build.*.dll assemblies have classes for that.

What are the benifits of learning F#?

I hear so much hype about F#. What makes functional programming so great? Is it really worth leaning?

From stackoverflow
  • Makes you think about programming differently than the other languages so.

    1. Able to scale to multiple cpu because of being functional.
    2. Easy to prove a function is correct, because of no side effects.
    3. F# is backed by a rich corporation.

    You should also look into OCaml, Haskell.

  • This question has already been asked:
    why-should-a-net-developer-learn-F#
    learning-functional-programming

  • Remember F# is not a purely functional language, naturally this trade-off is necessary to have it work with the .Net framework.

    Dave Berk : I'd consider it a point in its favor. There's no reason to lock yourself into one specific paradigm.
  • While not used in industry as much, functional languages will, in essence, "expand your mind" with regard to programming. They tend to rely heavily on recursion and make you focus on scope and functions themselves differently.

    It's kind of like comparing Buddhism with Taoism. At the end of the day they both give you a similar outlook on life, but the unique insights of both will help you realize more about the world.

  • F# was created, as well as erlang and haskell, to solve a specific problem. No, if you are not interested in the problem it solves you don't need to learn it. I remember first getting into computers, it was easy to know everything. Now days, it's impossible to know everything well so if you aren't curious and are not faced with a problem that can be solved with F#, focus on your skillset and improve it so you can better the community in your area of expertise. That's the goal everyone should attain.

Unknown problem/question with: if($numrows==0)

The following code continues to be displayed even if there are entries in my database and I don't understand why. Am I missing something? I'm not sure if this makes sense, but help would be great. :)

if($numrows==0)
{
echo"<h3>Results</h3>";
echo"<p>Sorry, your search: &quot;".$escaped."&quot; returned zero results</p>";
}
From stackoverflow
  • how do you get $numrows? It can be the mistake.

    What I usually do is:

    if($numrows > 0 ){
    
      // Code
    
    }else{
      echo"<h3>Results</h3>";
      echo"<p>Sorry, your search: "".$escaped."" returned zero results</p>";
    }
    
    Holly : Oh. Thank you. I would just put my query where you have //Code right? Because when I do that it just displays the else statement. :/
    fesja : can you paste your query and how you get the $numrows value?
    barfoon : No //code is what you want to do when you have some rows. You have to query the DB first, in order to get numrows.
  • Try:

    echo "'$numrows'";
    

    Directly above the if statement. If output is not '0', then the problem is how you're assigning 0 to $numrows.

    John Rasch : The if block actually would currently get executed if $numrows were null (because the == operator doesn't compare types), but it would not if she changed it to if($numrows === 0)
    Babiker : Thaks John. You're right.
  • If the code you're having a problem with is the same as quoted in your previous question... then the problem is here:

    $numresults=mysql_query($query);
    $numrows=mysql_num_rows(numresults);
    

    You're missing a $ before numresults on the second line.

    John Rasch : +1 - nice find!

HTML Editing in WinForms or WPF apps

I am looking for a way to edit a piece of HTML (such as an email text) in a Windows app (either WinForms or WPF). So this should work not unlike the little editor I have available to myself right here on the stackoverflow site (well, except more wysiwyg, I guess), except I want to do the same thing in WPF/WinForms.

Anyway: You get the idea: HTML editing in windows apps like it used to be possible with the old DHTML edit control.

Any suggestions would be highly appreciated.

From stackoverflow
  • WinForms has a rich text control you can use to an extent, but any RTF to HTML would be third-party (Here is just one example). I can't answer WPF, but it seems like the FlowDocument and RichTextBox would be the idea there. I think you'd have a similar issue, converting the RTF to HTML.

    Velika : I believe RTF does support tables, to some extent at least.
  • I used this HTML editor, based on the IE Web Browser control, in my WinForms app. It worked well, though there is a large 10MB COM Interop dependency file.

    http://www.codeproject.com/KB/edit/editor_in_windows_forms.aspx

    Peter Gfader : I have used that control in conjunction with TinyMCE... Works good, but as just already mentioned: browser dependency and interop is not nice
  • Hi,

    take a look at the HTMLTextbox library on codeplex (http://winformhtmltextbox.codeplex.com/). I know, it's also using a browser control but it's working great. I use it in my own applications (here an example: http://www.code4ward.net/main/Flash/Gallery/large/5C9816C8-7C8F-4A47-8607.png)

  • I have found this editor that does not requires Microsoft.mshtml. However, it requires some additional works to get a nice formatting buttons bar around.

  • You could try the ModelText HTML Control (disclosure: I wrote it).

    It is what you are asking for, and the only thing of its kind as far as I know: i.e. it's to edit HTML in Winforms, without depending on a browser and interop.

.Net Application Exits Abruptly

My .Net appliaction exits abruptly on certain machines ( this is a desktop application). I tried to catch the exception but the catch statement I put on simply can't catch the exception that was happening.

Any ideas how to solve, or diagnose this problem?

Note: This exception only occurs at client's machine, release mode, on which we have no debugger tool to use.

Note 2: The application event log does not contain any errors at all.

From stackoverflow
  • You may want to try adding an event handler to System.Windows.Forms.Application.ThreadException and System.AppDomain.CurrentDomain.UnhandledException to see if you can figure out what exception (if any) is causing your application to terminate.

  • In the debug drop down menu in Visual Studio choose exceptions and check all the checkboxes under thrown. This should halt the app at any unhandled exceptions. Examine it and give us the results.

    Ngu Soon Hui : Not sure this is applicable. Because it only occurs on release mode, in client's machine. We can't reproduce it here, though
  • Can you check the Application Event Logs on the client's pc incase the .NET runtime is logging something?

    Ngu Soon Hui : I checked the event logs.. unfortunately no error was recorded.
  • This is almost always caused by a COM/PInvoke issue where the native code you've used raises a Win32 exception. Under certain circumstances Windows will elect to simply abort the process rather than tear it down normally when their is major state corruption such as an invalid stack pointer.

    If you can determine what specific behaviors precede the shutdown you can narrow your search for the controls/PInvokes that might be causing the problem.

    Austin : If your application is PInvoke-ing, is compiled as AnyCPU, and your development machines are running 32-bit windows, you can experience crashes when you run your application on 64-bit Windows. A simple fix for this is to compile your application as x86. Scott Hanselman posted about this: http://www.hanselman.com/blog/BackToBasics32bitAnd64bitConfusionAroundX86AndX64AndTheNETFrameworkAndCLR.aspx

SSL Error with WCF Service using Transport Security & Cert. Authentication

I don't know if this is a question more suited for Serverfault.com, really depends on the answer, but I have followed this tutorial in .NET C# to setup a WCF service under 'wsHttpBinding' (Transport Security & Certificate Authentication), I have created a test development certificate using the methods described here and I have also configured my HTTPS 443 port in Bindings for IIS.

Everything has been working pretty good each step, however I am receiving an error in the the Example "Hello World" service I created (again, all followed via the MSDN tutorial link I first stated) when hitting https://vd1/WcfWsHttpBindingTest/Service.svc (VD1 being my local computer name):

HTTP Error 403.7 - Forbidden
The page you are attempting to access requires your browser to have a Secure Sockets Layer (SSL) client certificate that the Web server recognizes.

I have followed both tutorials as stated to install my server certificate and the client certificate and it has been configured in IIS; Also if I negate the 'https' and just use 'http' I receive a 403.4 Forbidden stating I am trying to access a page which has been secured with SSL, so I'm pretty sure that side of it is working.

Any ideas folks?
I haven't deviated from the tutorials, I am running IIS 7.0 and Vista Business.

It would even help if somebody could start me from a clean slate by giving me better tutorial links for configuring a service with wsHttpBinding.

** If anyone had seen my initial post, you will notice I closed my answer as it has evolved to the problem above **

From stackoverflow
  • Sounds like the client credentials aren't getting set or there is a problem with the config files. Can you post the config files so we can see the ClientCredentials configuration, which configures in a tag like: < clientCertificate > .

    Alternately, a cert can be configured in code, so if you have the source code that configures the cert on the proxy, post that.

    A final check would be Vista Specific. You should run VS (and possibly related processes for certificate generation) as admininstrator: Some Info on Vista Admin

    If none of that helps, try CodePlex for some guidance, I found that the checklists for security configuration helped me no end.

  • Thanks for your help Tanner.

    After two hours of scratching my head and tinkering, with help from a colleague we narrowed it down to one step which was not done correctly. The Certificate was being added to "Local User" not "Local Computer".

    Thanks again.

XSLT character encoding problem

Hey guys,

I'm using XSLT and having great success, just got a couple of problems.

Warning: DOMDocument::loadXML() [domdocument.loadxml]: Entity 'Aring' not defined in Entity

Basically for some non-standard characters I am getting the above type of error. I really want to fix this once and for all. I know about character mapping but I cannot possibly write down every possible combination of special characters.

Thanks!

From stackoverflow
  • Include a DTD that defines the entities, like this one

    Here's a post at PHP.net that hints at how to succesfully include it.

    The DTD above should probably cover you; &Aring; is an HTML entity, and the DTD above covers all HTML 4.01 entities.

    James : How do I include those? And do you have a list of DTDs that may be relevant?
    James : That is the code at the top of my .xsl page, but the problem still persists. Sorry for being slow if I am making a basic mistake.
    Ciaran McNulty : James you need the DOCTYPE on the XML file with the entities in.
  • When used without a DTD, XML only supports a very limited number of named entities. (&lt;, &gt;, &amp;, and &quot;, as I recall.) To include other out-of-charset characters without using a DTD, simply refer to them with a numeric entity instead.

    For example, &Aring; corresponds to Unicode character U+00C5, "Latin Capital Letter A With Ring Above". You can therefore use &#xC5; (leading zeroes can be omitted) to include it in your document. If you're on Windows, the Character Map tool (on XP: Start > Programs > Accessories > System Tools) is a big help.

  • &Aring; is not a standard XML entity. In order to support it in your XML document, your XML parser needs to be DTD-aware and the document must have a DOCTYPE declaration which either defines that entity or refers to a DTD that defines that entity. An XHTML DTD, for example, defines &Aring; to mean &#xC5;.

    It is correct for your DOM XML parser to throw an error when it sees a named entity that it is not already aware of, and the parser is either not DTD-aware or there is no DOCTYPE declaration for what that entity means. XML itself defines the entities &lt;, &gt;, &amp;, and &quot;. These are the named entities that can be safely used in any XML application.

    If you are writing the document yourself, then just don't use &Aring; - use a numeric equivalent instead or, assuming you're using Unicode, just use the character literal.

    If you need to be able to parse XML documents from other people containing any other named entity, and the documents don't have a DOCTYPE, then as Frank mentioned you will need to fix the document yourself by inserting a correct DOCTYPE after the XML declaration.

Auto formatting a web.config in Visual Studio 2008

I am currently in the process of creating API documentation using Microsoft Word 2007 and I need the user to cut and paste a section from the document into their web.config.

I formatted the section in the Microsoft Word document for easy readability and when I paste the formatted section into the web.config it maintains the style from the Microsoft Word document.

Is there a way for the user to auto format the section to their preferred web.config layout?

Edit

The documentation is formatted like so in Microsoft Word:

<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="basicEndPoint">
</binding>
</basicHttpBinding>
</bindings>
</system.serviceModel>

When the user adds the section from the word document to their web.config, I want it to match their preferred formatting style. No line breaks, different indentation, etc.

Edit 1:

I removed all the page breaks from the configuration section and used Ctrl+K, Ctrl+D to format the entire document. I updated the code sample to reflect what is looks like in the Word document.

From stackoverflow
  • I don't really understand your question, but copying and pasting from Microsoft Word 2007, Notepad and Visual Studio, you can copy from any of them to the other and you can still maintain the formatting (Notepad will lose the coloring though).

    A suggestion, why don't you provide them with a web.config file that is beefed up with all the necessary configurations possible, comment them and describe them in your documentation. In other words, section X defines doing so-and-so by uncommenting the lines 10-12 and editing the value of K to the number or path they need to, etc.

  • You could always recommend that your user just hits Ctrl+K, Ctrl+D which will reformat their web.config after pasting. (From the menu, Edit/Advanced/Format Document)

    Visual Studio does a pretty good job at keeping XML files formatted nicely.

    Michael Kniskern : Also under Tools->Options->XML->Formatting->Auto Reformat the user can check the "On paste from clipboard" checkbox
    Arnis L. : Sometimes i paste xml in studio just because of this...
  • You may want to be careful with this - Word isn't designed to handle code, and the problems don't stop with whitespace formatting. Have you ever tried to debug an issue caused by a parameter containing a dash instead of a hyphen?

    The formatting itself depends on the tool used to edit web.config. Assuming visual studio, pasted code is expected to be ugly, but is easily fixed with ctrl-k-d

How to replace a variable within a string with PHP?

So I have some PHP code that looks like:

$message = 'Here is the result: %s';

I just used %s as an example. It's basically a placeholder for whatever will go there. Then I pass the string to a function and I want that function to replace the %s with the value.

What do I need to do to achieve this? Do I need to do some regex, and use preg_replace(), or something? or is there a simpler way to do it?

From stackoverflow
  • try dynamic variables:

    $placeholder = 's';
    str_replace("%".$placeholder,$$placeholder,$message);
    

    then %s will be replaced with $s, the variable

  • You can use str_replace

    http://es.php.net/manual/en/function.str-replace.php

    that is for sure lighter than regex.

    Also sprintf can be an even more versatile option

    http://es.php.net/manual/en/function.sprintf.php

  • You can use sprintf, which works in a very similar way to C's printf and sprintf functions.

  • You can actually use sprintf function which will return a formatted string and will put your variables on the place of the placeholders.
    It also gives you great powers over how you want your string to be formated and displayed

    $output = sprintf("Here is the result: %s for this date %s", $result, $date);
    
  • If you use %s, I think that is the same placeholder that printf uses for a string. So you could do:

    $text = sprintf($message, "replacement text");
    

    Think that should work at least...

  • 
    $find = array(
         '#name#',
         '#date#'
    );
    $find = array(
         'someone\'s name',
         date("m-d-Y")
    );
    $text_result = str_replace($find, $search, $text);
    

    I'm usually using this for my code, fetching the $text from some text/html files then make the $text_result as the output

How do you write to the Log tab and Console.Error tab of the NUnit gui runner

In the NUnit Gui Runner, there are 6 tabs. I can write to the Console.Out by writing something like:

Console.WriteLine("This will end up in the Console.Out");

I can write to the Trace tab by writing something like:

System.Diagnostics.Trace.WriteLine("This will end up on the Trace tab");

But how do I write to the two other tabs, "Log" and "Console.Error"?

From stackoverflow
  • I believe to write to Console.Error, you do this:

    Console.Error.WriteLine("blah");

    To write to the Log, you need to configure log4net in your test project, then setup a log4net appender in the .exe.config file for your project. NUnit is actually a little tricky to setup with log4net, here's a little guide to get started:

    http://www.softwarefrontier.com/2007/09/using-log4net-with-nunit.html

Regular Expression to find the start end of a list in HTML

I have a TextBox in a webpage that i'm using javascript to parse and modify to format for HTML. 90% of it works really well, the last main thing i'm trying to be able to support is copying and pasting from a word document. I got it mostly completely, i just am kinda stuck on finding list and wrapping them in a UL tag..

So, using regular expressions, i'd like to find the list in this text:

<p>paragraph goes here

<li>goes here<br/>
<li>list item 2<br/>
<li>list item 3<br/>

<p>another paragraph

and wrap the <li> section with a <ul> tag. my regexp foo isn't that good, can someone help?

----- update -----

While I appreciate all the feedback basically indicating that I need to start from scratch with this issue, I do not have the time to do that. I completely understand that regex is not the ideal way to handle HTML formatting, but how I am using it now, it will handle most of what my users are looking to do. I only need a subset of HTML tags, not a full HTML editor.

The source of my content will be a user copying and pasting from a word document (about 99.9% ) of the time. i use regex to insert HTML tags into plain text. for the lists, i find the bullet character MS word inserts into it's copied text and replace that with the <LI> tag. I just want to make it more user friendly to wrap the <LI> tags with a <UL> tag.

I'll look into being able to end my tags properly, so.. assuming they're properly ended, what would be the regex to wrap my list items with a <ul> tag?

thanks!

From stackoverflow
  • Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems. -- Jamie Zawinski

    1. Regular expressions and HTML are a particularly bad fit.

    2. This is 2009, use closing tags in your HTML. (That alone will help you, if you really want to regex your html.

    3. If you've already got this page inside a browser, use the DOM! Let the browser parse the HTML for you (shove it into a hidden div if you must) and navigate the resulting DOM tree.

  • Don't parse HTML with regexes. Instead, use a real HTML parser.

    Sorry if my answer feels insubstantial, but this question is asked almost every day, and your requirements are (in my opinion) far too complicated for regular expressions.

    Also, none of your tags are closed. You should probably write that like this:

    <p>paragraph goes here</p>
    
    <li>goes here</li>
    <li>list item 2</li>
    <li>list item 3</li>
    
    <p>another paragraph</p>
    

    My HTML may be off, but you should really close all your tags.

  • I agree with James and Chris, in general it's really a lot better to use a proper parser, I've seen people fail badly doing it any other way (I'm assuming you don't have full control over the HTML input here, in which case a shortcut like regex might work fine).

    Let's assume you're using Java for the moment. If you know that your input is valid XHTML instead of HTML, you can use the Java API for XML Processing (JAXP), which comes with the Sun Java JDK. Then in a few lines you can parse your XHTML into a DOM tree and reach down to pick out the list's node and do whatever you like with it. There's a learning curve to JAXP, but it's well worth it.

    If you are using Groovy, there's XMLSlurper. Ruby has several good XML libraries. PHP has the XMLParser extension. Python has Beautiful Soup. Pretty much any modern language has good alternatives to choose from.

    Now based on your example, you don't have properly XML-ized XHTML, but wild-and-wooly HTML with unclosed tags and other nasties. If that's the case, you'll need to grab an HTML parser library, something on the order of HTMLParser. Good luck!

  • Assuming all elements have end tags, and nobody got clever by adding spaces inside start or end tags, and that some elements precede the list items, all you have to do it something like (in Perl syntax, probably compatible with a PCRE library, minus the m// operator):

    m/(?<!li)>[^<]*<li/i
    

    to identify the first list item in a group. Exploded (with the x flag, for readability):

    m/
        (?<!li)> # the end of a start or end tag that isn't part of an li element
        [^<]*    # some non-angle-bracket characters -- in-between tag content
        <li      # the beginning of an li element
    /xi          # space insensitive, case insensitive (respectively)
    

    And then you could go through the next block more confident that nothing will likely be between list items until you read its end, save that position, and use this pattern again.


    Figuring out where it ends is trickier without a parser. You could use something like (this is abridged)

    m/(?<=<li).*?<(div|form|p)/i
    

    where you list all the non-inline elements, which will trigger the li and ul to be closed and end the overall list. But the other way for the list to close implicity is for the container to close.


    If the list-item elements themselves are well-formed (have closing tags), then this might be sufficient for placing the lists's closing tag:

    m{</li>.*?<(?!li)}i
    

PHP Form code mangled

I am generating a simple form with php. The following code has been reduced to showcase the problem.

<?php
$blah = "<h1>Well</h1>"; $test = "<h2>Done</h2>";
echo '<script type="text/javascript" src="fetchlayers.js"></script>';
$formcode = "<form action=\"process.php\" method=\"post\" enctype=\"multipart/form-data \">"
          . "<label for=\"file\">Filename:</label>"
          . "<input type=\"file\" name=\"file\" id=\"file\"/> <br />"
          . "<input type=\"submit\" name=\"submit\" value=\"Submit\" "
          .    "onclick=\"setTimeout(function() { sendInfo(\"$blah\", \"$test\"); },1250);\" />"
          . "</form>";

echo "<h1>hello</h1>
<div id='form'>
$formcode
</div>";

This results in this html code

<h1>hello</h1>
<div id="form">
<form action="process.php" method="post" enctype="multipart/form-data ">
<label for="file">Filename:</label><input name="file" id="file" type="file">
<br><input name="submit" value="Submit" onclick="setTimeout(function() { sendInfo(" type="submit"><h1>Well</h1>", "<h2>Done</h2>"); },1250);" /&gt;
</form>

Somehow the form code for type=submit is ending up after my call to sendinfo(). Why?

From stackoverflow
  • It's because of your quotes in the onclick. Use single quotes instead:

    "onclick=\"setTimeout(function() { sendInfo('$blah', '$test'); }, 1250);\" "
    

    The way it is now, your onclick attribute actually reads like this:

    onclick="setTimeout(function() { sendInfo("
    
  • It appears to be an escaping issues:

    <?php
    $blah = "<h1>Well</h1>"; $test = "<h2>Done</h2>";
    echo '<script type="text/javascript" src="fetchlayers.js"></script>';
    $formcode = "<form action=\"process.php\" method=\"post\" enctype=\"multipart/form-data \"><label for=\"file\">Filename:</label><input type=\"file\" name=\"file\" id=\"file\"/> <br /><input type=\"submit\" name=\"submit\" value=\"Submit\" onclick=\"setTimeout(function() { sendInfo('$blah', '$test'); },1250);\" /></form>";
    
    echo "<h1>hello</h1>
    <div id='form'>
    ". $formcode . "
    </div>";
    

    The javascript in onclick needs single quotes or it has to use &quot;.

    fiXedd : There's a typo where the first single-quote is supposed to be: sendInfo(;$blah', '$test');

How to calculate load bearing in Box2D?

I'm using Box2D (the AS3/Flash version, if it matters) and I'm trying to calculate how much weight each body is carrying.

I know how to iterate through all the bodies, and I know how to poll the Collion Detection routines, but it seems the collision forces die off to zero once weight is applied. Is there some sort of "total static force" property I'm overlooking?

From stackoverflow
  • I think all you need to do is loop through your b2Body instances and use the GetMass() method.

    I'm not sure what you mean by "total static force".

    As for weight/mass I think you apply it before any collisions, when you create the body, either set it yourself using setMass(); or have box2d estimate a mass based on the shape, using the SetMassFromShapes() method.

    hth

    Andy Moore : I'm not looking for the weight/mass of a particular body - but the total weight the body is carrying. ie: 10 boxes stacked on top of each other, how much "load" is on the bottom box?
    George Profenza : shouldn't that be the sum of the masses of all the boxes above that bottom 1 ? var totalMass:Number = 0; for(var i:int = 0 ; i < stackedBodiesNum ; i++){ totalMass += stackedBodies[i].GetMass(); } trace(totalMass); I think it's something simple, but I'm not getting it, am I ?
    Andy Moore : Ah well the rub is that there's no way of knowing which box is stacked where - indeed, the screen is just going to be a random jumble of boxes. There's no convenient stackedBodies array :)
  • It has been awhile since I have played with Box2D but have you tried polling GetReactionForce() on the things of interest?

    I know that when I made a bridge simulation and I wanted the bridge to break based off the weight on it, I polled GetReactionForce() and if it was above a certain threshold then I deleted the joint connecting the two bodies.

    Andy Moore : GetReactionForce would probably do the trick if I was using joints; unfortunately I am just using individual shapes. :(
  • Using the contactResult type in the optional contactListener object, you can poll the normalForce of each item to find out what forces (which intrinsically includes weight) are being applied to objects.

    Note that sleeping bodies (a resting stack for example) will not trigger contactResults, but it should work fine if you turn off sleeping or if you want to measure forces only while motion is happening.

    For info on how to implement the contactListener class check up on the documentation.

synchronizing objects ID in app & web database?

Hi,

We have an Android app and a Web Service. We want to download part of the places objects to the mobile. The user will be able to download more of a certain city. Because of that we need to save the city_id of the web in the mobile database. We've thought on two options:

  • Each database will have it own primary IDs, but we will save the Web Primary ID in the mobile too (so we can ask to the webservice for more info). That's the easiest option.
  • The mobile table will not autoincrement and the objects will have the same IDs as in the web.

Which one (or another) do you think is the best approach?

thanks!

From stackoverflow
  • Use the IDs from the server - they are valid unique identifiers, and there's nothing particularly special about autoincrementing.

    fesja : thanks, i will do it that way; it's more consistant

tagging photos in facebook-connect within iphone app

hello stacks!

Im adding a fbConnect feature in my iphone app. Was wondering if there is a way to tag photos (names, i.e. John Smith) in the fbConnect api?

all the best!

From stackoverflow

Question about joining two mysql tables.

I am trying to join two tables; the purpose being able to search and display event information for an artist that is entered by the user.

The tables are as follows:

artist table: [id],[name]

events table: [id],[artist_id],[venue_name],[city],[state],[date],[time]

I created a search engine, but what I want to do is when an artist name is entered into the text box, the code will go out to my database and will look through the artist table to see what name was entered and then grab the id that matches the entered name and then go to the events table to find that distinct artist_id and display all of the event information for the certain artist that was entered.

I would really like help with how to do this and I'm not the greatest at this, but I am trying! Thanks:)

From stackoverflow
  • select e.venue_name, e.city, e.state, e.date, e.time
    from artist_table a
      join events_table e
        on a.id = e.artist_id
    where a.name = @userInput
    

    or something like that... Or am I missing something? Is this a homework question?

    duffymo : +1 from me - the point goes to the swift. 8)
    Holly : yes, it's a homework project due tomorrow :/
  • SELECT *
    FROM artist
        LEFT JOIN events
            ON artist.id = events.artist_id
    WHERE artist.name = 'your search text'
    
    Adrien : Not to stump for my own answer ... But presuming a fairly normalized database, this is going to return more data than is strictly necessary. Still, +1 for being structurally sound. Also, watch for input validation on the 'your search text' bit. SQL Injection waiting to happen there.
    LukeH : @Adrien, You're probably right, but I assumed that they'd also want the artist details for display in the UI or whatever, hence the "SELECT *" and the "LEFT JOIN".
    Adrien : @Luke: Agreed, hence the upvote from me. I've been accused of "overanalyzing" the problem (especially homework problems) from time to time. :)
  • select a.name, e.* 
    from artist as a
        left join events on(a.id - e.artist_id)
            where a.name like '%$someinput%'

    just in case you dont want to find name exact match.

    Just trying to help. and its sure i'm not great at this ,but want to help since at first it's complicated for me too

Is prevention of XSS a valid reason to prefer POST over GET for web apps?

The current trend in web applications seems to be towards using GET requests for everything. Specifically, using RESTful URLs that describe a service, a command, and its parameters. A few months ago, Jeff Atwood posted about the dangers of XSS. He demonstrated how even allowing users to post on your site something as seemingly innocuous as an "img" tag could result in an XSS vulnerability. The reason is that the browser will just go blindly request the url in the "src" attribute, which could do something merely annoying, such as logging the user out, or something much more ominous.

When I first started doing web development ten years ago, the conventional wisdom was to always favor POST over GET for forms, and to have the application on the server side require POST for form submission, for precisely this reason. Browsers send GET requests all the time (like in the aforementioned "img" tag example), but they only send POST requests in certain circumstances (specifically, forms with the "method" attribute set to POST). By requiring POST, is seems you can eliminate a large segment of XSS attacks. Is this a valid reason for preferring them?

From stackoverflow
  • You're confusing vanilla Ajax calls with REST calls.

    Vanilla Ajax calls use GET or POST and it is completely up to you how to handle them.

    REST uses the verbs GET, HEAD, POST, PUT, DELETE

    HTTP VERB   REST/CRUD
    POST         Create
    GET          Read
    PUT          Update, Create
    DELETE     Delete
    

    You want to use POST over GET when you are worried about CSRF, not XSS.

    A good rule of thumb is always use POST and only use GET if you are absolutely sure you want to share that data with other sites or the data is not sensitive.

    But just using POST alone won't protect you 100%.

    Both XSS and CSRF are very important and you should review your app for both, but they are two very different beasts.

    CSRF :

    Wikipedia

    OWASP

    XSS:

    OWASP

  • I think you're misunderstanding REST. The point isn't to prefer GET over POST, the point is to use GET where the request doesn't affect the data on the server, and POST where data is modified. REST is all about properly using the HTTP verbs available.

    For example, a search form will often use GET, while a Create X form will usually use POST.

    Chad Grant : You're totally missing the security aspect in your answer :(
  • Since when did REST imply using GET for everything? Last I checked, it meant the exact opposite. Use GET requests for getting a resource, and POST for posting one to the server.

    One of the key points of REST is to use the HTTP requests that best maps to the operation you're trying to do. GET should be used for what it is intended for: Getting data from the server, without changing state on the server. It should not be used to update resources on the server. POST or PUT are designed for that.

    Using HTTP the way it was intended to be used both helps avoid some (but far from all) XSS attacks, it also makes browsers behave a lot nicer when communicating with your site. The browser expects that GET requests can be safely repeated, without requiring confirmation from the user. That's what it does if you refresh the page, for example, or use the back/forward buttons. POST is expected to change state on the server, so the browser typically asks for confirmation before repeating a POST request.

    Chad Grant : Restricting POST will have absolutely NO effect on XSS. XSS is caused by not validating the data you receive from the client regardless if that data comes from GET or POST. This particular question is more about CSRF
  • Anyone can set up a simple html form and 'POST' data to your webservice via their browser and the local html file.

    Restricting to POST will stop simple xss but if they can get a javascript running it won't really change much.

    From my experience GET is mainly used for 'getting' stuff from the server, post is used for 'posting stuff' to the server.

    GET's Have the ability to be bookmarked simply and clearly.

    POST's can hold much more data due to not being restricted by the max url length which you should be trying to keep small.

    Chad Grant : Restricting POST will have absolutely NO effect on XSS. XSS is caused by not validating the data you receive from the client regardless if that data comes from GET or POST
  • There are situations when you should use POST rather than GET, but avoiding XSS isn't one of them. Perhaps you're thinking of XSRF, but even then, requiring POST doesn't really protect you. And in fact, REST advocates would actually say that you shouldn't just use GET but that you should use POST, PUT and DELETE for the corresponding "CRUD" operations.

    To avoid XSS, escape and/or scrub content from users appropriately.

    To avoid XSRF, require secret tokens on any side-effect causing operation that is potentially dangerous. (BTW: it's a good idea to avoid using GET requests when passing secret tokens as this could result in them leaking in referrers.)

    Use GET for read-only requests whenever possible. (pretty much whenever the query can fit in a URL)

    Use POST (or PUT or DELETE, if feasible and appropriate) for write requests.

  • XSS won't be stopped; XSS is when a user gets you to somehow output their script to other users. That requires filtering.

    XSRF won't be stopped either; it requires adding one-time-tokens of some sort, to ensure that someone can only hit your site if they're actually on it (rather than posting from an embedded iframe or the like).

    However, POST vs GET does prevent web accelerators and scrapers (eg Google Bot) from modifying your site. They only go to GET links, and thus if you don't want to have your site deleted (a la Daily WTF posts on this), make sure that 'delete this item' isn't a GET. ;-)

    More usually, it's a matter of semantics and form size. GET does not post a form, thus is limited to whatever you can put in a URL, which is not much. POST allows arbitrary amounts of data. PUT and DELETE are more there for semantics; they can both be done via POST too.

  • The already-given answers really do answer your question - no, prevention of XSS is not a valid reason to prefer POST over GET. However, if you want a demonstration of this, check out tools like WebScarab or Tamper Data, which are very useful for testing your own site's vulnerabilities. It's just as easy to inject code into a POST request as into a GET. Even without these tools, though, note that unless you're checking for POST vs. GET server-side, it's easy to simply send parms using a GET. Simply add, e.g., ?parm1=value1&parm2=value2&etc to the URL.

itextsharp extract images

I have been using this code with great success to pull out the first image found in each page of a PDF. However, it is now not working with some new PDFs for an uknown reason. I have used other tools (Datalogics, etc) that do pull out the images fine with these new PDFs. However, I do not want to buy Datalogics or any tool if I can use iTextSharp. Can anybody tell me why this code is not finding the images in the PDF?

Knowns: my PDFs only have 1 image per page and nothing else.

using iTextSharp.text;
using iTextSharp.text.pdf;
...
            public static void ExtractImagesFromPDF(string sourcePdf, string outputPath)
        {
            // NOTE:  This will only get the first image it finds per page.
            PdfReader pdf = new PdfReader(sourcePdf);
            RandomAccessFileOrArray raf = new iTextSharp.text.pdf.RandomAccessFileOrArray(sourcePdf);

            try
            {
                for (int pageNumber = 1; pageNumber <= pdf.NumberOfPages; pageNumber++)
                {
                    PdfDictionary pg = pdf.GetPageN(pageNumber);
                    PdfDictionary res =
                      (PdfDictionary)PdfReader.GetPdfObject(pg.Get(PdfName.RESOURCES));


                    PdfDictionary xobj =
                      (PdfDictionary)PdfReader.GetPdfObject(res.Get(PdfName.XOBJECT));
                    if (xobj != null)
                    {
                        foreach (PdfName name in xobj.Keys)
                        {

                            PdfObject obj = xobj.Get(name);
                            if (obj.IsIndirect())
                            {
                                PdfDictionary tg = (PdfDictionary)PdfReader.GetPdfObject(obj);

                                PdfName type =
                                  (PdfName)PdfReader.GetPdfObject(tg.Get(PdfName.SUBTYPE));

                                if (PdfName.IMAGE.Equals(type))
                                {

                                    int XrefIndex = Convert.ToInt32(((PRIndirectReference)obj).Number.ToString(System.Globalization.CultureInfo.InvariantCulture));
                                    PdfObject pdfObj = pdf.GetPdfObject(XrefIndex);
                                    PdfStream pdfStrem = (PdfStream)pdfObj;
                                    byte[] bytes = PdfReader.GetStreamBytesRaw((PRStream)pdfStrem);
                                    if ((bytes != null))
                                    {
                                        using (System.IO.MemoryStream memStream = new System.IO.MemoryStream(bytes))
                                        {
                                            memStream.Position = 0;
                                            System.Drawing.Image img = System.Drawing.Image.FromStream(memStream);
                                            // must save the file while stream is open.
                                            if (!Directory.Exists(outputPath))
                                                Directory.CreateDirectory(outputPath);

                                            string path = Path.Combine(outputPath, String.Format(@"{0}.jpg", pageNumber));
                                            System.Drawing.Imaging.EncoderParameters parms = new System.Drawing.Imaging.EncoderParameters(1);
                                            parms.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Compression, 0);
                                            System.Drawing.Imaging.ImageCodecInfo jpegEncoder = Utilities.GetImageEncoder("JPEG");
                                            img.Save(path, jpegEncoder, parms);
                                            break;

                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            catch
            {
                throw;
            }
            finally
            {
                pdf.Close();
                raf.Close();
            }


        }
From stackoverflow
  • The above will only work with JPEGs. Excluding inline images and embedded files, you need to go through the objects of subtype IMAGE, then look at the filter and take the appropriate action. Here's an example, assuming we have a PdfObject of subtype IMAGE:

          PdfReader pdf = new PdfReader("c:\\temp\\exp0.pdf");
      int xo=pdf.XrefSize;
      for (int i=0;i<xo;i++)
      {
       PdfObject obj=pdf.GetPdfObject(i);
       if (obj!=null && obj.IsStream())
       {
        PdfDictionary pd=(PdfDictionary)obj;
        if (pd.Contains(PdfName.SUBTYPE) && pd.Get(PdfName.SUBTYPE).ToString()=="/Image")
        {
         string filter=pd.Get(PdfName.FILTER).ToString();
         string width=pd.Get(PdfName.WIDTH).ToString();
         string height=pd.Get(PdfName.HEIGHT).ToString();
         string bpp=pd.Get(PdfName.BITSPERCOMPONENT).ToString();
         string extent=".";
         byte [] img=null;
         switch (filter)
         {
          case "/FlateDecode":
           byte[] arr=PdfReader.FlateDecode(PdfReader.GetStreamBytesRaw((PRStream)obj),true);
           Bitmap bmp=new Bitmap(Int32.Parse(width),Int32.Parse(height),PixelFormat.Format24bppRgb);
           BitmapData bmd=bmp.LockBits(new Rectangle(0,0,Int32.Parse(width),Int32.Parse(height)),ImageLockMode.WriteOnly,
            PixelFormat.Format24bppRgb);
           Marshal.Copy(arr,0,bmd.Scan0,arr.Length);
           bmp.UnlockBits(bmd);
           bmp.Save("c:\\temp\\bmp1.png",ImageFormat.Png);
           break;
          default:
           break;
         }
        }
       }
      }
    

    This will mess the color up because of the Microsoft BGR, of course, but I wanted to keep it short. Do something similar for "/CCITTFaxDecode", etc.

    Dave : I appreciate the code. But I am not finding any IMAGE subtypes in my PDF. Everything is Indirect of type XObject. Any ideas on how I can find the images?
    R Ubben : Well, they are indirect xobjects; every stream must be indirect, according to the standard. What I did was go through the objects and look for streams. I should have included that in the code. I will edit it to add that part.
    R Ubben : So, you look through the objects for streams, then fetch its dictionary. The type will be stream, and for images, the subtype will be "/Image".
  • I found that my problem was that I was not recursively searching inside of forms and groups for images. Basically, the original code would only find images that were embedded at the root of the pdf document. Here is the revised method plus a new method (FindImageInPDFDictionary) that recursively searches for images in the page. NOTE: the flaws of only supporting JPEG and non-compressed images still applies. See R Ubben's code for options to fix those flaws. HTH someone.

        public static void ExtractImagesFromPDF(string sourcePdf, string outputPath)
        {
            // NOTE:  This will only get the first image it finds per page.
            PdfReader pdf = new PdfReader(sourcePdf);
            RandomAccessFileOrArray raf = new iTextSharp.text.pdf.RandomAccessFileOrArray(sourcePdf);
    
            try
            {
                for (int pageNumber = 1; pageNumber <= pdf.NumberOfPages; pageNumber++)
                {
                    PdfDictionary pg = pdf.GetPageN(pageNumber);
    
                    // recursively search pages, forms and groups for images.
                    PdfObject obj = FindImageInPDFDictionary(pg);
                    if (obj != null)
                    {
    
                        int XrefIndex = Convert.ToInt32(((PRIndirectReference)obj).Number.ToString(System.Globalization.CultureInfo.InvariantCulture));
                        PdfObject pdfObj = pdf.GetPdfObject(XrefIndex);
                        PdfStream pdfStrem = (PdfStream)pdfObj;
                        byte[] bytes = PdfReader.GetStreamBytesRaw((PRStream)pdfStrem);
                        if ((bytes != null))
                        {
                            using (System.IO.MemoryStream memStream = new System.IO.MemoryStream(bytes))
                            {
                                memStream.Position = 0;
                                System.Drawing.Image img = System.Drawing.Image.FromStream(memStream);
                                // must save the file while stream is open.
                                if (!Directory.Exists(outputPath))
                                    Directory.CreateDirectory(outputPath);
    
                                string path = Path.Combine(outputPath, String.Format(@"{0}.jpg", pageNumber));
                                System.Drawing.Imaging.EncoderParameters parms = new System.Drawing.Imaging.EncoderParameters(1);
                                parms.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Compression, 0);
                                System.Drawing.Imaging.ImageCodecInfo jpegEncoder = Utilities.GetImageEncoder("JPEG");
                                img.Save(path, jpegEncoder, parms);
                            }
                        }
                    }
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                pdf.Close();
                raf.Close();
            }
    
    
        }
    
         private static PdfObject FindImageInPDFDictionary(PdfDictionary pg)
        {
            PdfDictionary res =
                (PdfDictionary)PdfReader.GetPdfObject(pg.Get(PdfName.RESOURCES));
    
    
            PdfDictionary xobj =
              (PdfDictionary)PdfReader.GetPdfObject(res.Get(PdfName.XOBJECT));
            if (xobj != null)
            {
                foreach (PdfName name in xobj.Keys)
                {
    
                    PdfObject obj = xobj.Get(name);
                    if (obj.IsIndirect())
                    {
                        PdfDictionary tg = (PdfDictionary)PdfReader.GetPdfObject(obj);
    
                        PdfName type =
                          (PdfName)PdfReader.GetPdfObject(tg.Get(PdfName.SUBTYPE));
    
                        //image at the root of the pdf
                        if (PdfName.IMAGE.Equals(type))
                        {
                            return obj;
                        }// image inside a form
                        else if (PdfName.FORM.Equals(type))
                        {
                            return FindImageInPDFDictionary(tg);
                        } //image inside a group
                        else if (PdfName.GROUP.Equals(type))
                        {
                            return FindImageInPDFDictionary(tg);
                        }
    
                    }
                }
            }
    
            return null;
    
        }
    
  • The following code incorporates all of Dave and R Ubben's ideas above, plus it returns a full list of all the images and also deals with multiple bit depths. I had to convert it to VB for the project I'm working on though, sorry about that...

    Private Sub getAllImages(ByVal dict As pdf.PdfDictionary, ByVal images As List(Of Byte()), ByVal doc As pdf.PdfReader)
        Dim res As pdf.PdfDictionary = CType(pdf.PdfReader.GetPdfObject(dict.Get(pdf.PdfName.RESOURCES)), pdf.PdfDictionary)
        Dim xobj As pdf.PdfDictionary = CType(pdf.PdfReader.GetPdfObject(res.Get(pdf.PdfName.XOBJECT)), pdf.PdfDictionary)
    
        If xobj IsNot Nothing Then
            For Each name As pdf.PdfName In xobj.Keys
                Dim obj As pdf.PdfObject = xobj.Get(name)
                If (obj.IsIndirect) Then
                    Dim tg As pdf.PdfDictionary = CType(pdf.PdfReader.GetPdfObject(obj), pdf.PdfDictionary)
                    Dim subtype As pdf.PdfName = CType(pdf.PdfReader.GetPdfObject(tg.Get(pdf.PdfName.SUBTYPE)), pdf.PdfName)
                    If pdf.PdfName.IMAGE.Equals(subtype) Then
                        Dim xrefIdx As Integer = CType(obj, pdf.PRIndirectReference).Number
                        Dim pdfObj As pdf.PdfObject = doc.GetPdfObject(xrefIdx)
                        Dim str As pdf.PdfStream = CType(pdfObj, pdf.PdfStream)
                        Dim bytes As Byte() = pdf.PdfReader.GetStreamBytesRaw(CType(str, pdf.PRStream))
    
                        Dim filter As String = tg.Get(pdf.PdfName.FILTER).ToString
                        Dim width As String = tg.Get(pdf.PdfName.WIDTH).ToString
                        Dim height As String = tg.Get(pdf.PdfName.HEIGHT).ToString
                        Dim bpp As String = tg.Get(pdf.PdfName.BITSPERCOMPONENT).ToString
    
                        If filter = "/FlateDecode" Then
                            bytes = pdf.PdfReader.FlateDecode(bytes, True)
                            Dim pixelFormat As System.Drawing.Imaging.PixelFormat
                            Select Case Integer.Parse(bpp)
                                Case 1
                                    pixelFormat = Drawing.Imaging.PixelFormat.Format1bppIndexed
                                Case 24
                                    pixelFormat = Drawing.Imaging.PixelFormat.Format24bppRgb
                                Case Else
                                    Throw New Exception("Unknown pixel format " + bpp)
                            End Select
                            Dim bmp As New System.Drawing.Bitmap(Int32.Parse(width), Int32.Parse(height), pixelFormat)
                            Dim bmd As System.Drawing.Imaging.BitmapData = bmp.LockBits(New System.Drawing.Rectangle(0, 0, Int32.Parse(width), Int32.Parse(height)), System.Drawing.Imaging.ImageLockMode.WriteOnly, pixelFormat)
                            Marshal.Copy(bytes, 0, bmd.Scan0, bytes.Length)
                            bmp.UnlockBits(bmd)
                            Using ms As New MemoryStream
                                bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png)
                                bytes = ms.GetBuffer
                            End Using
                        End If
                        images.Add(bytes)
                    ElseIf pdf.PdfName.FORM.Equals(subtype) Or pdf.PdfName.GROUP.Equals(subtype) Then
                        getAllImages(tg, images, doc)
                    End If
                End If
            Next
        End If
    End Sub
    
  • I dint get to know to which name space this itext sharp belonging to..:( Which dll refrence i need to add ? Awaiting reply..