Thursday, March 31, 2011

Searching good book on Microsoft Business Intelligence Development Studio 2005

Hi,

I'm looking for a good book that about Microsoft Business Intelligence Development Studio 2005. Most interest goes to SSIS, but SSAS and SSRS are also important.

The book explains in a fair, simple and as much hands on way how the Development Studio for BI works (solution, projects, do's and dont's) and all the transformations in SSIS one can use thoroughly explained (like for example how a Derived Columns works). I'm a BI consultant (10 years experience), but not in Microsoft solutions.

Who can suggest me a good book?

From stackoverflow

How to tell if I'm on the last iteration of a for X in Y loop in Objective-C

I have a loop using the for (NSObject *obj in someArray) { } syntax. Is there an easy way to tell if I'm on the last iteration of the loop (ie. without having to use [someArray count])

From stackoverflow
  • Maybe this will work?

    if ( obj == [ someArray lastObject ] ) {
        // ...
    }
    
  • You could use NSArray#lastObject to determine if obj is equal to [NSArray lastObject].

    for (NSObject *obj in someArray) {
        if ([someArray lastObject] == obj) {
            NSLog(@"Last iteration");
        }
    }
    
  • Rather than call into the array at every iteration, it might be better to cache the last object in the array:

    NSObject *lastObject = [someArray lastObject];
    for (NSObject *obj in someArray) {
    
        // Loop code
    
        if (obj == lastObject) {
            // do what you want for the last array item
        }
    }
    
    gclj5 : You're still calling the method in the loop. I think you meant to swap the first two lines. Another tiny typo: uppercase 'F' in "For"
    Abizern : Thanks for pointing that out - I'll edit it.

Using a base class for unit test setup and teardown

Assuming Visual Studio.NET 2008 and MsTest are used to run unit tests. When a system is based on a service container and dependency injection unit testing would naturally require the setting up of services.

Should these services rather be setup in a base class that all unit tests derive from or in each unit test class. If they should be in a base class, is there a way to have the TestInitialize and ClassInitialize methods be executed without requiring them to be called from the derived class, e.g base.Initialise?

From stackoverflow
  • I prefer the Test* and Class* marked methods to be on the actual unit test class. If you define them on a base class, you cannot add test specific activities to them. Instead, use the static and instance constructors and finalizer on your base class.

  • The MSTest framework will search the entire object (all base classes) for the methods marked Test*. Like when you declare them on the unit test class, you do not have to call them explicitly.

    sduplooy : Class* methods will always be marked as static and hence will not be called from derived classes. The Test* methods will be called since they are instance methods.
    Anthony Mastrean : You're right, fixed the answer.
  • With 2008, you should be able to have [TestInitialize] on a base class, and as long as you don't add another [TestInitialize] somewhere down the hierarchy, it should be called. You could also do things with virtual methods.

MSTest.exe not finding app.config

I'm currently trying to run MSTest.exe from NCover, but I believe the question could apply generally to running MSTest.exe from the command line.

If I have the "/noisolation" argument, then MSTest.exe appears to find and use the app.config as expected. Without it, NCover doesn't capture any coverage information. From my research so far, it seems NCover needs /noisolation. So the question is how to get my *.config files to work when that argument is passed.

My NCover settings are:

Application to Profile
C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\IDE\MSTest.exe

Working Folder
C:\Documents and Settings\MyProfile\My Documents\Visual Studio 2008\Projects\XYZ\XYZ.CoreTest\bin\Debug

Application arguments
/noisolation /testcontainer:"C:\Documents and Settings\MyProfile\My Documents\Visual Studio 2008\Projects\XYZ\XYZ.CoreTest\bin\Debug\XYZ.CoreTest.dll"



Update: I added a trace showing that my config is (not surprisingly) trying to read from "C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\IDE\MSTest.exe.Config".

Update 2: If at all possible, I don't want to edit MSTest.exe.Config. That just isn't terribly portable.

From stackoverflow
  • In visual studio, mark the App.config file to property to CopyAlways. (right click on file, choose properties to get to the property panel)

    Larsenal : Having done so, the (renamed) app.config is in my output folder right next to the assembly... which is what it has been doing. My app is still trying to read the MSTest.exe.config rather than MyAssembly.dll.config. If I omit the /noisolation switch, it reads teh correct file.
  • I've never before used NoIsolation, but if I am understanding it correctly, it literally runs all of your test code in the MSTest class. That being so, it does and should read the App config for MSTest. If you insist on using noisolation, I'm thinking you would have to merge your App.config into MSTest.exe.config. Of course, that is a hack.

    It would probably be better to avoid the noisolation altogether. If it is due to an error, fix the error if possible. Work around the error if reorganizing (major refactoring) your app is not possible. I'm not sure there is an elegant alternative.

    I found "I think we need to find the root cause of this issue in order to avoid the noisolation switch. You might need to modify your applicaton. Is it possible to create a simple solution that repro the same issue?" at this URL.

    Larsenal : If this is the case, then perhaps my real question has to do with how to get NCover to correctly work with MSTest.exe without /noisolation.
    Greg Ogle : Just some ideas; sorry that they sound critical. Not intentional. If you are using team system, maybe you could use code coverage from taht? http://blogs.vertigosoftware.com/teamsystem/archive/2006/02/06/nUnit_and_Team_System_Code_Coverage.aspx
  • There's a technique where you can combine the contents of config files it's detailed here. You could add a fixed file inlcude line to MSTest.exe.Config, and then copy your app's app.config to that fixed file location. It's ugly, but more portable than hacking MSTest.exe.Config for every different eventuality.

  • At http://docs.ncover.com/ref/2-0/whats-new-in-ncover-2-0/release-notes-for-ncover-2-1-0/ under NCover Fixes:

    Running coverage on MSTest no longer requires the "/noisolation" flag. NCover correctly gathers coverage

    If this is indeed fixed, then upgrade NCover to 2.1.0. Perhaps that will work.

    Larsenal : I'll have to look into this.
    Regent : @Greg Ogle: Looks like the link is changed to http://docs.ncover.com/ref/2-0/whats-new-in-ncover-2-0/release-notes-for-ncover-2-1-0/
  • Ok, I'm running the risk that my post will devolve into a unit testing flamewar, but I think the problem is your tests and possibly even your code. You should refactor.

    Unit tests should be atomic. A single test should have no external dependencies and a config file is such a dependency. No test should rely on the config file.

    If you are testing a method that uses information from a config file, refactor your code so that the configured information is read outside of the method and either passed to the method or set as a property before the method is called. That way your test can either pass the value to the method, or set the property during test setup.

    If you need your app.config for a database connection string, you're on your own. DALs are notoriously difficult to unit test. If it's for a web service connection string, don't use it -- mock the interface.

    Larsenal : What I'm doing is probably better characterized as integration testing, not unit testing. In this particular case, I'm having to retroactively add some tests to an existing code base.
    Randolpho : Oh, I hate doing that! Ah, well, I stand by my statement... if you have the opportunity to refactor your code to make it more testable, do it. If your hands are tied, your hands are tied. Also, if you can, look into mocking your integrations, it'll do wonders for you later on.
  • To clear up the confusion: not using /noisolation = if it finds a SameNameAsYourDll.dll.config file, it'll be deployed with the test dll automatically, and will be used for the app config for the app domain that runs the tests in that assembly

    using /noisolation = All the isolation we do between tests, you, the host process, and everything else is out the window. We may still do some isolation, but you don't get the added benefit of the app domain being unique to your test dll. Thus, you dll's config won't help.

  • From Craig Stuntz in a comment at link text

    How to do this with MSTest.

    1. In Solution Explorer, right-click the Solution (not the Project).

    2. Click Add, New Item

    3. In Categories, select Test Run Configuration

    4. Now choose the Test Run Configuration item and add it to your project

    5. In Solution Explorer, double-click the Test Run Configuration you just created

    6. Click the Deployment item

    7. Add your config file as a deployed file (or deploy the entire folder which contains it, if appropriate)

    This took me a little while to figure out, but I'm in a similar situation and it does work for me.

    daub815 : This also only works for Visual Studio 2008 :(

Why does Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Equals() exist?

Description for Assert.Equals() from the MSDN Documentation: Do not use this method.

That's it, the full explanation. Uh.. ok, but then ... why is it there? Is it a deprecated method from an earlier version of the framework? Something that's supposed to be used only by other Microsoft Assemblies?

It just makes me want to use it all the more knowing I'm not supposed to. ;-)

Does anyone know?

From stackoverflow
  • .Equals is inherited from object. It's listed as "Do not use this method" so users won't confuse it with the AreEqual method.

  • All objects in .NET derive from Object.

    Object has a .Equals() method.

    Apparently the .Equals() method for this particular object doesn't do anything useful, so the docs are warning you that it doesn't do anything useful.

  • It was changed in 2008 (Maybe SP1) to fail a test when called, so that people who were using it by accident were told they really shouldn't be using it.

wpf complete reference

Hey

I am looking for a complete wpf tags documentation to use it with wpf controls. Anybody seen something like this?

10x

From stackoverflow
  • The MSDN reference feels a little mechanical, but it's complete.

    Josh G : XAML tags are used for assigning properties on WPF controls. Lookup the WPF control the XAML refers to and read about the properties on the control in MSDN.
  • There is no "Tags" complete documentation for WPF. The markup - XAML - is infinite by it's very nature. If I create a new control, boom, I can use it in XAML. Or, I can use XAML to create my own arbitrary object graph using custom types that are nothing related to UI.

    There is a XAML language spec, but that is not what you looking for. The answer from BC for the MSDN is a start, but vastly incomplete. Look at everything under System.Windows.Controls* for a better idea.

VBScript Compressor / Packer

I'm looking for a VbScript compressor / packer. Basically I want to shorten the VBScript code.

Could you recommend a tool for this?

From stackoverflow
  • I could swear Microsoft had their own tool for VBScript compression/obfuscation a few years back. But now I can't seem to find it.

    Where are you going to use the VBScript? Embedded in a web page or somewhere else?

    dr. evil : It's "script encoder" - http://www.microsoft.com/downloads/details.aspx?familyid=E7877F67-C447-4873-B1B0-21F0626A6329&displaylang=en but it only obfuscates does not shorten the code.
    tyndall : Thanks. I knew I wasn't imagining it. To bad it doesn't compress the code. I also just searched around for VBScript refactoring tools. Couldn't find any. My thought was you could rename the functions (a,b,c,etc...) with this functionality at least.
  • We use http://www.w3compiler.com/ on ASP code - not sure about straight VBScript though, but I'm guessing it is similar so would work.

    dr. evil : I tried with w3compiler but even when I changed the syntax to ASP alike, it can't optimise it for some unknown reasons.

RTD - making the sample COM DLL into a COM exe

I'm planning on making my existing application into an RTD server.

The application is currently written in C++ and while I will eventually port it to C#/Mono I want to be able to add the RTD functionality with C++.

I have found a few sample pieces of code (the MSVCRTDServer) and this site: http://weblogs.asp.net/kennykerr/archive/2008/10/29/excel-rtd-server-in-c.aspx

Unfortunately these are DLLs and I have forgotten all I knew of COM (good riddance) a long time ago.

How do i go about incorporating the DLL examples into the EXE? This is apparently about packaging the COM server in an EXE rather than a DLL.

EDIT:

Note, the existing app has an MFC GUI.

EDIT:

The intended use is taht the existing GUI app will be running - no need for clients of the COM/RTD interface to launch the app. (Although I won't deny that would be nice)

Basically i want to implement the IRTDServer interface with my own data - so that Excel (or other apps) can access the dynamic data that the application provides. (It is a program that talks to a serial port device - that device has status/state that changes and i want to be able to update clients on the changes asynchronously)

So, I need to create a COM object and register it so that clients can "see" it.

I am not sure how to add a COM object to an exe and have that COM object implement an existing/pre-definfed interface.

EDIT I started a bounty on this so I could get code samples. Apparently I am too lazy and stupid (or maybe it is just the hyper aversion to COM) to get started with existing answer by Franci Penov. (which is very useful and a great start)

So basically what I am looking for is:

code to take my existing dialog based MFC application that has a bunch of threads running and turn it into an RTD server (that has the same UI)

All that cocreate and CoThisandthat, etc. Where do I put that code in my exe? How do I extend/implement the IRTD stuff?

A before and after of a sample MFC hello world app (dialog based) is going to get the accepted answer.

  1. Before app with all the source code for mfc dialog app.
  2. "after" app that is based on the MFC app in step #1 that implements the RTD srver interface and all of its source. (all project files, source, etc)
  3. steps taken in the GUI/visual studio and otherwise to create step 2 from step 1. ( IDL, etc other files created. )

Ideally this is provided for VS2008, but any version would work.

Thanks.

From stackoverflow
  • EDIT: Dude, I have not touched MFC since year 2000. I was hoping to stay that way for the rest of my life. :-) Anyway...

    Aparently, the wizards have evolved since last century. The following steps for adding ATL COM support to and MFC app are for VS 2008.

    1. Generate a simple MFC dialog based app called MFCTest. Do NOT check the Automation checkbox in the wizard.
    2. Right click on the project and select Add / Class... In the dialog, choose ATL Simple Object. You will get a warning that ATL support will be added to the project.
    3. A new wizard will open with options for the new ATL object.

    You should be done.

    Frankly, I don't see any reason to post here a wizard-generated code. But if you have further questions on particular pieces of that code, post them on SO and I'll help you.


    EDIT: This is slowly turning into an article. If we go on like this, I might even publish a book. :-)

    Once you have the simple ATL object integrated in the MFC project, you can add the RTD interface to it. You will need to both inherit from the interface and add it to the COM_INTERFACE_MAP. Since the RTD interface is an IDispatch interface, you will have to inherit your class from IDispatchImpl<> and to add IDispatch to the COM_INTERFACE_MAP using COM_INTERFACE_ENTRY2 (in order to specify that it's implemented through the IRtdServer.

    I am not really familiar with how RTD works. You might also have to add support for COM connection points to your class, if Excel needs to supscribe to your updates. Here's also a link to refresh your connection points in ATL knowledge.

    Btw, I stumbled upon this blog post that has the C++ definitions of the two RTD interfaces. You probably already have them, but I thought I'd add it for completeness sake.


    The easiest way would be to create new ATL EXE project through the VS wizard and let it take of the registration and the process management part. The rest is not that different.

    If you need a particular sample to jumpstart your journey back to the land of COM out-of-proc, you can look at LABRADOR.

    Couple of links that might be of further interest to you:

    EDIT: If you just need to know how to register an object in your EXE with COM, so client apps can CocreateInstance it, check out CoRegisterClassObject. However:

    • the object needs to be a COM object
    • you need to implement a class factory for it
    • if you want process management (ie, COM starts your app on demand), the ClassID nees to be registered in the registry
    • if the client is going to create it through ProgID, the ProgID needs to be registered in the registry
    • you might need a custom proxy/stub dll, if you are doing custom marshalling
    • if your app has UI, you will have to modify the shutdown logic, so that when the user closes the UI, the app does not exit untili the last COM reference to your objects has been released as well

    EDIT 2: I'd still suggest you look at the ATL out-of-proc sample and at the skeleton the ATL wizard would generate to understand the sequence of operations. However, you might need to delve a bit in the ATL code to see what exactly is going on.

    Here's the short version of the process:

    On a startup, the application nees to check for a particular command line argument - /embedded. If that argument is present, it means the app is being launched by COm in response to a CoCO call. The app might choose to not show its UI at this point.

    Whether the app shows the UI or not, it has to register the class factories for any COM objects it provides through the CoRegisterClassObject API I mentioned above.

    If the app is started through COM, it can choose to shutdown itself on the last COM reference release. (This is usually detected through an additional global ref counter that is increased on any object AddRef and decreased on any object Release). However, the app should not shutdown itself, if it detected that the user interacted with its UI. in such case, the shutdown is deferred until the user explicitly closes the last UI (To make that detection easier, the app usually does not show its UI until the user attempts to start it explicitly)

    If the app was started by the user and the las UI is closed, the app should check if there are outstanding COM references to any object in it. If there are none, it can shutdown itself. If however, there are COM references, the app should hide the UI, but continue running until the last reference is released.

    If the app has reached a point at which it will shutdown, it should revoke all class factory registrations.

    Tim : Yes, starting from scratch is probably easier, but the whole point is I have an existing application that is what will be the source of the data and I want to shoe-horn the RTD code into it... I'll have a look at the links. Thanks
    Tim : thanks for the additional information. That might be enough to get me going.
    Tim : OK, thanks again. My head hurts with all the stuff the wizards create. Now I am starting to remember why I never missed leaving COM behind...
    Tim : I'll try the atl wizard. I'm just not sure how to implement/provide/extendthe RTD interface with my own. Not sure how that works.
  • You marshal your code in an ATL Server project. See samples at ATL Server Samples .

    Franci Penov : ATL Server is used for creating ISAPI extensions with ATL. It will require IIS hosting. It'll work, but it'll be harder to deploy and configure the solution.

Problem restricting anonymous access to an ASP.Net MVC Site.

Whenever I restrict anonymous access in my MVC site I get a 404 error:

Server Error in '/' Application. The resource cannot be found. Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make > sure that it is spelled correctly.

Requested URL: /Account/Login

I've just been playing with MVC (RC1 Refresh) for the first time and after getting my exiting membership provider working I wanted to lock down the site to prevent anonymous access. I tried the traditional way using web.config with:

<configuration>
 <system.web> 
  <authorization> 
   <deny users="?"/> 
  </authorization> 
 </system.web> 
</configuration>

but got the above error even though I explicitly allowed anonymous access to the logon page.

I also tried the technique mentioned in Scott Gu's blog and secured the About page by adding the [Authorize] attribute in the HomeController

[Authorize]
public ActionResult About()
{
 return View();
}

but got the same error when I tried to access that page.

I've even tried a clean install on a separate machine.

So how do you enable Authorization in ASP.Net MVC RC1 Refresh?

From stackoverflow
  • The default Web.Config contains an error. It has:

    <authentication mode="Forms">
     <forms loginUrl="~/Account/Login"/>
    </authentication>
    

    This should be:

    <authentication mode="Forms">
     <forms loginUrl="~/Account/LogOn"/>
    </authentication>
    

    (Excuse me asking and answering my own question but it took me ages to spot this and couldn't find any clues via Google or SO. if this has been posted before feel free to close).

    Chad Moran : Make sure you mark your answer an the accepted answer. :)
    Matthew : Thanks, this could have been a several hour goose chase.
    Martin Doms : Wow, thanks so much. That one had me scratching my head!

What would be the best suggestions for a developer aspiring to become architect?

My career goal is to become architect. I would like to know from people who made such transition what are the best suggestions/hints/recommendation that would be critical in making the change.

Thanks

From stackoverflow
  • Ultimately, to be an architect requires a skillset that is built on experience, not hard knowledge.

    Start communicating with the business stakeholders in your current system. Position yourself to get involved, or at least start being aware of, the "how and why" of the business side of things. An architect's responsibility is to be able to make that leap between business and technical without friction. That requires communication skills and understanding. When you do this for an extended period of time, you start to become familiar with the "patterns and practices" of what business drivers expect of software solutions.

    Also take an interest in any hardware/infrastructure/logistical stuff that you don't deal with today. Being able to coordinate a solution from many aspects can only be done if you have prior experience under your belt, be able to foresee practical roadblocks by applying what you've learned in the past.

    When you are working on a project, think about it from these perspectives:

    • What will be required to make changes a year from now? (Maintenance and enhancements)
    • How difficult is the solution to deploy?
    • Does the solution fit into a broader IT scheme? e.g. will it be the red-headed stepchild in a solution portfolio?
    • What impact(s) does the solution have on the surrounding systems as far as network access, security, load, etc.?

    These books have been very helpful to me:

  • Yup - as Rex M says, there's no substitute for experience. There are a couple of other useful skills you can develop while you're gaining that experience, though...

    Blog. Blog about that neat technique you applied in your code the other day. Blog about the new API you're using. Blog about your cat, but only from time to time :-)

    Writing about a subject, especially for public consumption, forces you to think more deeply about it, to really get an understanding. Blogging will also sharpen your written communication skills - crucial for an architect.

    For verbal skills, get on a presentation skills course. As an architect you will be presenting your architectural thoughts to developers. Your audience will thank you for not being one of those presenters that simply stands there and reads the slides out, word for word!

    If you can stand in front of a room full of expectant faces and lucidly convey an idea, you'll be ahead of 90% of most aspiring architects.

    Maxim : That's neat to know. I'm already on the blog/presentations path. Cool :)
  • There's nothing magical about being an architect. Most of the ones I know are just really good developers. With that in mind, just work on being the best dev around. Take every opportunity to learn. You might focus on the broader sorts of learning. It's better to know how two pieces fit together than to understand every detail of a tiny piece. Look for opportunities to work on the seams between pieces. That's where architects do most of their work so the experience will be most valuable from there.

  • I found that my ability to translate between developers and non-developers made me invaluable - I could understand the problems, and create analogies or examples to explain them to the business folk. And, in the opposite direction, I could understand the issues and constraints that the business folk were experience, and translate those into requirements and suggestions for the developers.

    Also, it helps to be a very good developer, it helps to regularly learn new things, it helps to be somewhat humble. Lastly, it helps to volunteer for work, especially the work that other developers don't want to do. Bosses (good ones, anyway) usually remember that you were a team player, and when you tell them you want more responsibility, are more likely to give it to you.

  • I found this 97-things-every-software-architect-should-know very useful.

  • There are different types of software architects. The common ingredient between different types of architects is the right balance of technical knowlege, leadership skills, soft skills and domain knowledge. The most difficult aspect of being a software architect is to persuade different stakeholder on various decisions. That is where sound communication and persuasion skills help. To summarize:

    • Technical Knowledge
    • Domain Understanding
    • Communication Skills
    • Persuasion Skills
    • Qualities of a leader

    I am also an aspiring architect. I have found http://www.bredemeyer.com/ a goot resource for aspiring as well as veteran architects.

Can I use ASP.NET AJAX History without having .NET 3.5 SP1 installed?

Is it possible to use this feature on a server that only have .NET 2.0 installed? After an initial look into how AJAX history is implemented, I'm not sure it would be easy. I am just curious if anyone knows of a way to do it.

From stackoverflow

Which book would you recommend to learn SVG?

I am a complete beginner with SVG and I am looking for books that would help me get started. I am interesting in scripting, and animations.

From stackoverflow

What's the best way to add colored-sytax code snippets to a web page?

Is there a web gadget or service or some open source solution for doing this?

Or do people just hand-code this in the HTML?

I need to add some Ruby and Python code to a web page.

From stackoverflow
  • I think Stack Overflow uses this or something very much like it: http://code.google.com/p/syntaxhighlighter/

  • If you're using the Vim editor, its pretty simple. Just open the code in a GVIM window and save it as an HTML file (Save As.., etc).. it will do all the work for you creating an HTML file that preserves syntax highlighting.

    EDIT: Its actually "Convert to HTML" on the Syntax menu. (http://vim.wikia.com/wiki/Pasting_code_with_syntax_coloring_in_emails)

  • SyntaxHighlighter 2.0 was recently released here is a basic snippit to get you started:

    <head>
        <script type="text/javascript" src="path/to/scripts/shCore.js"></script>
        <script type="text/javascript" src="path/to/scripts/shBrushPython.js"></script>
        <script type="text/javascript" src="path/to/scripts/shBrushRuby.js"></script>
        <link type="text/css" rel="stylesheet" href="path/to/css/shCore.css"/>
        <link type="text/css" rel="stylesheet" href="path/to/css/shThemeDefault.css"/>
        <script type="text/javascript">
         SyntaxHighlighter.config.clipboardSwf = 'path/to/scripts/clipboard.swf';
         SyntaxHighlighter.all();
        </script>
    </head>
    
    
    <pre class="brush: python;">
        ... code ...
    </pre>
    
    <pre class="brush: ruby;">
        ... code ...
    </pre>
    
  • I think this site uses prettify.

  • I think you're looking for something like GeSHi - The generic syntax highlighter. I've had a lot of success with this in the past, GeSHi supports a TON of languages. Not only is this useful for your own syntax highlighting on your web site, but I use the source files because they contain all of the language keywords (I need them for a text-editor I'm working on with syntax highlighting). It's been a godsend.

    If you specifically need just Ruby and Python highlighting, you may want to check out NetBeans. It has a feature to output your source code to an HTML page while keeping all of the coloured syntax.

    Bryan Locke : Cool. Didn't know NetBeans had that. That's perfect. Thanks.

jQuery and Auto-populat selects

Hey,

I have a simple page where I can select a client, then once I chose that autopopulate to the projects that belong to the client. I am using PHP/MySQL to pull the results.

I took at a look at this: http://remysharp.com/2007/01/20/auto-populating-select-boxes-using-jquery-ajax/ but I think that starts with both fields on the page. I tried to rework the code but didn't come out that well.

Any ideas on any type of reference?

Thanks,

Ryan

UPDATE 2: Here is my jQuery is this all I need or do I need the other sections, this code doesnt work as is.

Thanks for your help!

Ryan

 var client_id = $('#c_id').val();
    $.getJSON("../inc/get-projects.php", {id: client_id}, function(data){
     projects = $('#p_id');
     projects.empty();
     $.each(data, function() {
      var option = $('<option/>').attr('value', this.id).text(this.name);
      projects.append(option);
     });
    });

PHP:

<?php
    include "config.inc.php";
    $sth = mysql_query(
     sprintf(
     "SELECT c_id,p_id,p_title FROM projects WHERE c_id = %s",
     mysql_real_escape_string($_GET['id'])
     )
    );
    $projects = array();
    while($r = mysql_fetch_assoc($sth)) {
     $projects[] = array('id' => $r['p_id'], 'name' => $r['p_title']);
    }
    print json_encode($projects);
    exit;


?>
From stackoverflow
  • The answers to this question might prove helpful: http://stackoverflow.com/questions/180451/using-javascript-and-jquery-to-populate-related-select-boxes-with-array-structu

  • If you have HTML like this:

    <select id='clients'>...</select>
    <select id='projects'>...</select>
    

    You can have jQuery code like this:

    $(document).ready(function() {
        var $clients = $('#clients');
        $clients.change(function() {
            var client_id = $clients.val();
            $.getJSON("getProjects.php", {id: client_id}, function(projects) {
                $projects = $('#projects');
                $projects.empty();
                $.each(projects, function() {
                    var option = $('<option/>').attr('value', this.id).text(this.name);
                    $projects.append(option);
                });
            });
        });
    });
    

    And then have getProjects.php return something like:

    $sth = mysql_query(
        sprintf(
        "SELECT * FROM projects WHERE client_id = %s",
        mysql_real_escape_string($_GET['id'])
        )
    );
    $projects = array();
    while($r = mysql_fetch_assoc($sth)) {
        $projects[] = array('id' => $r['id'], 'name' => $r['name']);
    }
    print json_encode($projects);
    exit;
    

    I haven't tested all of this, but it is more or less what you want, I think.

    edit - Tested and works, obviously it might not be exactly what you need but it gives you an idea of how to go about it. Hope it helps.

    edit 2 - The problem with your code is here:

    $.getJSON("../inc/get-projects.php", {id: client_id}, function(projects){
        projects = $('#p_id');
        projects.empty();
        $.each(projects, function() {
            var option = $('<option/>').attr('value', this.id).text(this.name);
            projects.append(option);
        });
    });
    

    You are overwriting the projects passed into the function with the projects in the 2nd line. I used a $ in my code to differentiate the two, which was admittedly perhaps not the best of ways. To fix, change the code to this:

    $.getJSON("../inc/get-projects.php", {id: client_id}, function(data){
        projects = $('#p_id');
        projects.empty();
        $.each(data, function() {
            var option = $('<option/>').attr('value', this.id).text(this.name);
            projects.append(option);
        });
    });
    
    Jarrod Dixon : Nice - way to go that extra mile!
    Coughlin : Wow! Thank you, let me work with this and give it a shot. Thank you so much, Ryan
    Coughlin : Its working PERFECT so far, but it is displaying p_id where it should be displaying the JSON content, the PHP loads the data correctly, but the jQuery is reading it wrong I think. p_id = ID that you gave in the example.
    Coughlin : So when my code prints it looks like: And not loading my data. Thoughts?
    Paolo Bergantino : Can you edit your question with the code you are using? I tested the above and it works, so I need to see what you changed around. Are you assigning the id to 'id' and the project name to 'name' in PHP's json_encode?
    Paolo Bergantino : Essentially whatever variables you assign in the $projects[] = line in the PHP code need to match up with the this.id and this.name on the var option = line in the javascript code.
    Coughlin : I updated my code above! Thanks, Ryan
    Coughlin : Hey, check on my first question, I updated my code, it didn't seem to work. Do I need the other section in it? Ryan

Making cut/replace methods with JTextArea

I am to make a cut and a replace method on JTextArea. I have the code for copy and paste, and I reckon I could just use that, in addition to just deleting the marked text in the JTA.

How would the code for a code for cut and replace methods look like?

The code for copy looks like this:

public void copy(){
    int start=ta.getSelectionStart();
    int end=ta.getSelectionEnd();
    String s=ta.getText();
    aString=s.substring(start,end);
    System.out.println(aString);
}

And the paste code looks like the following:

public void paste(){
    int start=ta.getSelectionStart();
    String startText=ta.getText().substring(0, start);
    String endText=ta.getText().substring(start);
    String res=startText+clipBoard+endText;
    ta.setText(res);
}

So basically: How do I delete marked text in a JTextArea? Or is there possibly a better way to do this?

From stackoverflow
  • It would mixture of both methods, without clipBoard concatenation, I suppose.

    public void cut(){
      int start=ta.getSelectionStart();
      int end=ta.getSelectionEnd();
      String startText=ta.getText().substring(0, start);
      String endText=ta.getText().substring(end, ta.getText.length());
      ta.setText(startText+endText);
    }
    

    However, why not use cut, copy, and paste method of JTextComponent, which are already inherited and available.

  • JTextArea supports cut/copy/paste by default using keyword combination (Ctrl+C etc). If you want to have custom invocations (like menu action), JTextComponent itself provides cut/copy/paste methods which you can re-use.

  • In addition to amit.dev's answer, you should also be able to set custom key mappings to use whatever keys you would like... but if you do, you'll loose some platform independence, since different platforms have different keys for these operations.

Converting SVG to PNG using C#

I've been trying to convert SVG images to PNG using C#, without having to write too much code. Can anyone recommend a library or example code for doing this?

From stackoverflow
  • You can call the command-line version of incscape to do this:

    http://harriyott.com/2008/05/converting-svg-images-to-png-in-c.aspx

    Also there is a C# SVG rendering engine, primarily designed to allow SVG files to be used on the web on codeplex that might suit your needs if that is your problem:

    http://www.codeplex.com/svg

    harriyott : Thanks Espo. I actually wrote that inkscape blog post! Although it "works", it's not a particularly robust solution. I like the codeplex project though - I'll give it a look. Thanks.
    Espo : How embarrassing :) Good thing maybe the SVG rendering engine could help you out though.
    harriyott : I take it as a compliment. I've not been quoted to myself before!
    Jeff Atwood : that's hilarious! :)
  • Couldnt help noticing:

    @harriyott Isnt it your site www.harriyott.com??

    Espo : Haha, didn't notice that. Maybe he allready know about the incscape-trick then :) But the SVG-rendering might help him if he needs to display svg-images on the web.
    Prakash : yes, thats a nice link! +1 2 u..
  • I'm using Batik for this. The complete Delphi code:

    procedure ExecNewProcess(ProgramName : String; Wait: Boolean);
    var
      StartInfo : TStartupInfo;
      ProcInfo : TProcessInformation;
      CreateOK : Boolean;
    begin
      FillChar(StartInfo, SizeOf(TStartupInfo), #0);
      FillChar(ProcInfo, SizeOf(TProcessInformation), #0);
      StartInfo.cb := SizeOf(TStartupInfo);
      CreateOK := CreateProcess(nil, PChar(ProgramName), nil, nil, False,
                  CREATE_NEW_PROCESS_GROUP + NORMAL_PRIORITY_CLASS,
                  nil, nil, StartInfo, ProcInfo);
      if CreateOK then begin
        //may or may not be needed. Usually wait for child processes
        if Wait then
          WaitForSingleObject(ProcInfo.hProcess, INFINITE);
      end else
        ShowMessage('Unable to run ' + ProgramName);
    
      CloseHandle(ProcInfo.hProcess);
      CloseHandle(ProcInfo.hThread);
    end;
    
    procedure ConvertSVGtoPNG(aFilename: String);
    const
      ExecLine = 'c:\windows\system32\java.exe -jar C:\Apps\batik-1.7\batik-rasterizer.jar ';
    begin
      ExecNewProcess(ExecLine + aFilename, True);
    end;
    
  • you can use altsoft xml2pdf lib for this

Wicket PropertyModel strangeness?

I'm new to Wicket and was trying the following configuration:

class User {
   private String password;

   ...

   public void setPassword(String password) {
     this.password = MD5.encode(password);
   }
   ...
}

After trying to use the following to bind to the password and finding out that the default implementation of PropertyModel is by default to bound to the field, not the property (weird name eh?)

add(new PasswordTextField("password", new PropertyModel(user, "password"));

Why in the world would they have implemented it this way? And is there a PropertyModel alternative that uses getter and setters by default?

Thank you?

From stackoverflow
  • PropertyModel will do what you want already. When a PropertyModel is queried for its value, it looks in two places:

    • If a "getter" method exists for the given property, the PropertyModel calls the getter to retrieve the property's value. Specifically, the PropertyModel looks for a method named get<Property>, where <Property> is the property expression passed to the PropertyModel constructor, and calls the method using reflection if it exists.

    • If no "getter" method exists, the PropertyModel returns the value of the property field directly. Specifically, the PropertyModel uses reflection find a field that matches the property expression passed to the PropertyModel constructor. If a matching field is found, the PropertyModel returns the field's value. Note that the PropertyModel will check private and protected fields in addition to public fields for a match.

    In your case, the property expression used in the PropertyModel constructor is "password", so the PropertyModel will first look for a method on the user object called getPassword. If no such method exists, the PropertyModel will return the value of the private password field instead.

    Since in your case the PropertyModel is returning the private field's value instead of calling the "getter", you most likely mistyped the name of the getter in your User class. For example, f you accidentally typed getPasssword (with 3 s's), the PropertyModel won't find it, and will fallback to returning the private field.


    EDIT

    If you don't like PropertyModel's default behavior, you can create a subclass of PropertyModel that will prevent Wicket from trying to read/write to private fields. This way, you can force all property accesses to occur through getters and setters.

    I wrote an example BeanPropertyModel class to demonstrate this:

    import org.apache.wicket.WicketRuntimeException;
    import org.apache.wicket.model.PropertyModel;
    
    /**
     * A custom implementation of {@link org.apache.wicket.model.PropertyModel}
     * that can only be bound to properties that have a public getter or setter method.
     * 
     * @author mspross
     *
     */
    public class BeanPropertyModel extends PropertyModel {
    
        public BeanPropertyModel(Object modelObject, String expression) {
            super(modelObject, expression);
        }
    
        @Override
        public Object getObject() {
            if(getPropertyGetter() == null)
                fail("Missing getter");
            return super.getObject();               
        }
    
        @Override
        public void setObject(Object modelObject) {
            if(getPropertySetter() == null)
                fail("Missing setter");
            super.setObject(modelObject);
        }
    
        private void fail(String message) {
    
            throw new WicketRuntimeException(
                    String.format("%s. Property expression: '%s', class: '%s'.",
                            message,
                            getPropertyExpression(),
                            getTarget().getClass().getCanonicalName()));
        }
    }
    
    Allain Lalonde : Great answer! Thanks a bunch for clarifying it for me.
    Allain Lalonde : What I'd been doing was not providing a getter and hoping that is would call the setter. Reason being I didn't want the user object to have a getPassword() method.
    Mike Spross : It will still call the setter, since you defined one, but when Wicket renders the password field, it will try to "get" the model value, and will end up retrieving the private field. If you want to prevent this, you can override getObject() to return null or a string of "*" characters, or whatever.
  • great answer by mike spross! one small addition though:

    i'd not use property model in this case. just write

     new Model<String>(){ getObject(){...} setObject(){...}}
    

    and implement the correct bahavior, which does exactly what you want.

    Mike Spross : +1 - If this is a "one-time" thing, this is the easiest way to get the needed functionality.

Linq to SQL Inheritance Question

I guess I'm not quite sure how the Linq inheritance is supposed to work.

I have a "User" entity and I want to have two additional entities called "Creator" and "Assigned" that inherit from the "User" entity (basically they should just have the same exact properties as the User entity) I don't need any additional properties. I can do this just fine in the designer.

The problem is that when I try to associate the inherited entities with another entity - I don't have access to any of the properties from the base entity. Am I not supposed to have access to those to tie to other entities? Seems to me like I should.

From stackoverflow
  • This sounds more like a relationship rather than inheritance to me. That is all of the entities are users, but some users have a creator relationship to others and some have an assigned relationship. Probably the easiest way to model this is to have a join table for creators and another for assignees. Create foreign key relationships back to the user table from both columns in the join table. When you drag all of these tables onto the designer surface, each user will get createdBy/created and assignee/assigned to entity sets. Your db constraints, I presume, will limit it so that each user only has one creator and a user isn't assigned to more than one other use (or maybe not, depending on your rules).

    user table
    user_id  int identity not null primary key
    user_name varchar
    ....
    
    created_by
    created_by_id int identity not null primary key
    creator int not null, FK to user.user_id
    createe int not null, FK to user.user_id
    (with a unique index on creator/createe -- or both could be the PK)
    (constraint creator <> createe)
    
    assigned_to
    assigned_to_id int identity not null primary key
    owner_id int not null, FK to user.user_id
    assignee_id  int not null, FK to user.user_id
    (with a unique index on assignee_id -- or not)
    (constraint owner_id <> assignee_id -- or not)
    

MOSS 2007 BDC Filter

I'm new to MOSS. How do you set up/apply a filter using the MS BDC editor? I have run across a few samples but they don't go into any detail.

From stackoverflow
  • Refer to the following link. This should give you a much better understanding of how BDC works within SharePoint.

What does "Is Identity" column property mean in SQL Server?

I am using SQL Server for the first time and I see that a column property is called Is Identity.

What doeds this mean?

What are the advantages of marking a column property as Is Identity = Yes ?

Thanks in advance.

From stackoverflow
  • It simply means the column uses the Identity(increment, seed) function to provide values for a primary key (usually). It is also known as "Autonumber". The second line below is an example:

    CREATE TABLE Table (
    TableID bigint IDENTITY(1,1) NOT NULL,
    DateTimeStamp datetime NOT NULL DEFAULT (getdate()),
    Data nvarchar(100) NOT NULL,
    CONSTRAINT PK_Table PRIMARY KEY CLUSTERED 
    (
        TableID ASC
    )
    

    It acts as a default value for the column that increments for each record. Note that you can also get the value inserted from SCOPE_IDENTITY(). Do not use @@IDENTITY as it is depreciated and can return the wrong result in the case of triggers or nested contexts.

  • Flag indicating an Identity Column - can be used as an auto-increment column (recommended for any table)

    it has many implications like being able to get the id of the last inserted row in a table using @@IDENTITY or SCOPE_IDENTITY() etc.

    Try: Understanding Identity Columns

    Niyaz : Yes. This does. Thanks a lot!!!!
    NTulip : i updated comment with some more information. don't forget to vote up the answer. Thanks
    mrdenny : Don't use @@IDENTITY. It's unreliable, if there is a trigger on the table which puts data into another table which has an identity column on it @@IDENTITY will return the wrong value.
  • http://sqlskills.com/BLOGS/KIMBERLY/post/Ever-increasing-clustering-key-the-Clustered-Index-Debateagain!.aspx

  • It's equivalent to MySQL's AUTO_INCREMENT property. Usually used on a primary key column