Sunday, March 6, 2011

Is the Sql Server Unique Key also an Index?

Hi folks,

I've got a column in a table (eg. UserName) which I want to make sure is unique. So I create a unique key for that column and call it IX_Users_UserName.

Now, if I do lots of searching for users based on their username I want to make sure there is an index for that field.

Do I need to create a separate index, or is the unique key also considered an index, just like the primary key is a clustered unique key?

Thanks :)

From stackoverflow
  • A unique key is an index in I suspect almost every database product. It has to be, otherwise the database would have a hard time enforcing it: when you insert a value, the database has to answer, "does that value already exist?" The sane way to do that is consult an index.

    I don't have a SQL Server in front of me to test, but I'd be shocked if it didn't.

  • Unique Key: Unique Key enforces uniqueness of the column on which they are defined. Unique Key creates a non-clustered index on the column. Unique Key allows only one NULL Value.

    Alter table to add unique constraint to column:

    ALTER TABLE Authors ADD CONSTRAINT IX_Authors_Name UNIQUE(Name) GO

    Source

    More information from MSDN.

    FWIW -- if your constraint doesn't create an index, I would avoid naming it IX_ as that would typically be assumed to be associated with one (IX = Index).

    Pure.Krome : Cheers :) perfect answer. I'll also reanme all my unique keys to IX and drop the single index i had on those fields (why double up ... that's bad!). Cheers!
  • Basically, in SQL Server, a unique constraint is indeed realized by means of a unique index.

    The differences between a UNIQUE constraint and a UNIQUE INDEX are quite subtle, really. If you create a UNIQUE INDEX, you can reference that in a foreign key constraints from another table (doesn't work if you create a UNIQUE constraint....).

    So what's the difference? Well - a unique constraint really is more of a logical thing on a table - you want to express the intent that the contents of a given column (or group of columns) is unique.

    A unique index (like most indices) is more of a "behind-the-scenes" implementation detail.

    From my point of view, unless you really have a problem with it, I'd always use a UNIQUE INDEX - the benefit of being part of a referential integrity constraint is quite valid and can be very useful in certain cases. Funtionally, in practice, there's no difference between using a Unique Constraint vs. Unique Index, really.

Are there any free tools to create SWF / Flash animations?

Are there any competitor tools like Flash for creating SWF animations? My 8 year old son wants to learn 2D animation but I doubt his anticipated attention span warrants buying Flash.

From stackoverflow
  • The following URL contains a rather comprehensive list of open source flash projects. Take a look, you might find what you need.

    http://osflash.org/open_source_flash_projects

  • There's a short video tutorial on using InkScape and SWFTools to make an animation here:

    http://screencasters.heathenx.org/episode-031/

    Alternately, you could look into the (now discontinued) PowerBullet which has a PowerPoint-like interface.

  • It's not "free" as such, but there's a 30 day trial for Flash CS4 up on adobes site.

  • For kids there's a software called ANIMATIONISH. It's not free, however. This was made by the guys who created ToonBoom studio (a pro software for 2d animation).

Unit/Integration Tests, how granular should they be?

I am testing the UI of my ASP.Net Web Forms app using NUnit/Watin. I understand the high level concepts around TDD, Unit Testing, integration testing etc, but have not had much of a chance to put them to use until now.

So, when I am testing the validation logic on a data entry form, should I be writing one test that triggers each of my validation errors (i.e. Field x is required), or a separate test for each of the validation errors that should be thrown by the form. Is this simply a style issue, or are there valid reasons for writing several tests instead of one that hits on all possible combos of my validation logic?

Psuedo code:

    [Test]
    public void Validation()
    {
       //Do some stuff to test that username is required.
       Assert.AreEqual(true, ie.ContainsText("Username is required.");

       //Do some stuff to test that passwword is required.
       Assert.AreEqual(true, ie.ContainsText("Password is required.");
    }

vs.

[Test]
public void ValidateUserName()
{
   //Do some stuff to test that username is required.
   Assert.AreEqual(true, ie.ContainsText("Username is required.");
}

[Test]
public void ValidatePassword()
{
   //Do some stuff to test that passwword is required.
   Assert.AreEqual(true, ie.ContainsText("Password is required.");
}
From stackoverflow
  • I would lean towards one test per validation:

    • If you completely break validation, two tests fail, so you know immediately about everything you've broken. If they're in the same test then the first failure will mask the second until the first is fixed.

    • As soon as you break anything you'll get a description of exactly what's broken in the names of the failed methods. Many unit testing GUIs will give you a little red traffic light next to each failing test, and these will naturally highlight and describe all your errors.

    Having said that, the important thing is that you test at all - where particular tests appear in a class is a minor detail...

How Load a PHP page in Same Window in JQuery

Dear All,

I have Test.php and it has two functions:

   <?php

     echo displayInfo();
     echo displayDetails();

    ?>

Javascript:

<html>
 ...
<script type="text/javascript">

    $.ajax({
      type:'POST',
      url: 'display.php',
      data:'id='+id  ,
      success: function(data){
       $("#response").html(data);
      }
          });     

</script>
...

<div id="response">
</div>
</html>

It returns the response from jQuery.

The response shows as <a href=Another.php?>Link</a>

When I click the Another.php link in [test.php], it loads in another window. But I need it should load same <div> </div> area without changing the content of [test.php], since it has displayInfo(), displayDetails().

Or is it possible to load a PHP page inside <div> </div> elements?

How can I tackle this problem?

Any suggestions?

From stackoverflow
  • If I understand correctly, you'd like for the a link to cancel navigation, but fire the AJAX function?

    In that case:

    $("#mylink").click(function() {
     $.ajax({ type: "POST", url: "another.php", data: {id: "somedata"}, function(data) {
      $("#response").html(data);
     });
     return false;
    });
    
  • You could just use MooTools and http://mootools.net/docs/Request/Request.HTML

  • Krof is correct,

    One possible unwanted behavior of this however is that it will query the data every time the link is clicked. You can set the event to only call the ajax query once by using one.

    $("#mylink").one('click', function() {
      // ajax call
      return false;
    });
    

    Don't forget to set href="javascript:{}" in your link so after the event is fired once the link wont do anything;

    Krof Drakula : Actually the `href=""` part isn't needed if you cancel event bubbling by returning `false`. Although I think it does help if you want to avoid having the outline drawn around `a` elements (if I remember correctly).
  • I am calling one php file for graph. The returned content contains one alert mess. but It isnt executing. How to load that html string from the responce string

    strager : Is this another question? If so, create a new question ("Add Question" at top). Or is this in addition to the question? If so, edit your original question with your original account.

How do you keep your metadata under version control?

We have a database that persist our metadata and data.

Our metadata is produced buy a dedicated team, using a Web application on the development server, and is a critical part of our application.

Then the customer generates data according to this metadata.

We already version the database schema, and all schema change. The next step is to put our metadata under version control.

Naive solution

A naive solution would be to dump all the metadata, and commit it under version control before generating the corresponding packages. Since it's a dump, it can easily be restored. But there is probably a better way, like an incremental solution (only version diffs).

Text dumps

Another solution is to export all metadata tables in text format (like XML), and then version those text files. But then you have to find a way to reimport them.

So, is your metadata under version control? Why? How?

From stackoverflow
  • Non Niave solution:-

    Version control your mata data build scripts.

    I.E. the database schema drop/create and the SQL "INSERTS" should both be placed under version control.

    The advantage of this approach is thet the Schema and Insert scripts really are source code. Version controls systems are designed for source code so they play well with this method. In addition its pretty much self contained and can be easily ported to other systems.

    If your meta data is devleoped interactivley there are several utilities that will allow you to export your database as an insert script.

    Nelson Reis : Can you name one of those utilities that allow us to export the database as an insert script? Thanks.
    Bill Karwin : Each brand of database provides its own tool. E.g. for MySQL, it's `mysqldump`.
    James Anderson : TOAD for Oracle, or Squirrel SQL for anything that supports a JDBC connection.
    WW : This is what we do, only we write the insert statements first, put them in version control and then include them (sadly not automatically) into the upgrade database script. Bonus points for using merge/upsert to make subsequent updates easy.
  • K. Scott Allen has a series of excellent blog posts about this subject:

  • Something to consider would be the tools available by Embarcadero. ErStudio for example provides the ability to version control against your entire database model.

ASP.NET MVC route question

I have two routes I want mapped in my ASP.NET MVC application

  1. /User/Login
  2. /User/{userid}/{username}/{action} (e.g. /User/1/blah/profile)

Here are the routes I've defined:

    routes.MapRoute(
        "Profile",
        "Users/{userID}/{username}/{action}",
        new { controller = "Users", action = "Profile" }
    );

    routes.MapRoute(
        "Default",
        "{controller}/{action}/{id}",
        new { controller = "Home", action = "Index", id = "" }
    );

This works great so far in most instances. The following URLs work from my home page:

<%= Html.ActionLink((UsersController x) => x.Login(), "Login") %>
<%= Html.ActionLink((UsersController x) => x.Profile(1, "blah") %>

These map to (respectfully):

/Users/Login /Users/1/blah

However, once I've navigated to /Users/1/blah, the login url immediately turns to /Users/1/blah/login. Any idea how to fix this?

From stackoverflow
  • Sorry but i just have to say.. Bad design?

    Why do you need both username and userid in the url? why not have /Users/Profile/fekberg instead? The username should, imo be unique.

    Kevin Pang : You realize that this site does the same thing right? The username isn't used for indexing, but for SEO.
    Filip Ekberg : Well i'd still leave the user-id out of the question, but sure, it can be used :)
  • is your route hitting an Authorize filter? Is there a requirement to be logged in to view the /Users/1/blah page? (ie. is there an [Authorize] attribute on the UsersController class, or on the Profile Action?)

    well then, if it is not an Authorize filter, I highly suggest you implement this Routing Debugger Tool into your project.

    Kevin Pang : No, anyone can view this page. I'm not sure what this has to do with the routing though. Or are you just curious?
    E Rolnicki : it sounded as if you were being redirected to a login page when trying to hit a page which would typically be protected by an authorization filter.
  • You want to use <%=Html.RouteLink%>

    This is very similar to the problem I had which you can view here

Does anyone know of any good tutorials for the Slick 2D lib?

There is a 2D java graphics library called Slick 2D (http://slick.cokeandcode.com/) that seems to be used by a bunch of indie games (mostly applets), but the documentation is a little lacking. Does anyone know of any good tutorials for this lib?

From stackoverflow
  • Your best bets are the Slick Wiki and the Slick Forums.

  • Most definitely check out their forums, and ask questions. They've been very helpful to me in the past.

Have log4net use application config file for configuration data.

I would like to stored log4net config data in my application.config file. Based on my understanding of the documentation, I did the following: 1. Add a reference to log4net.dll 2. Add the following line in AssemblyInfo.cs:

[assembly: log4net.Config.XmlConfigurator(Watch = true)]
  1. Initialize the logger as follows:

    private static readonly ILog log = LogManager.GetLogger(typeof(frmWizard));

  2. I have the following code in my app.config:

However, when I run the application, I get the following error on the console: No appender named [Consoleappender] could be found. How can I get log4net to read settings from the config file?

Thanks!

From stackoverflow
  • have you tried adding a configsection handler to your app.config? e.g.

    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
    
  • Add a line to your app.config in the configSections element

     <configSections>
       <section name="log4net" 
              type="log4net.Config.Log4NetConfigurationSectionHandler, log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821" />
      </configSections>
    

    Then later add the log4Net section, but delegate to the actual log4Net config file elsewhere...

      <log4net configSource="Config\Log4Net.config" />
    

    In your application code, when you create the log, write

        private static ILog GetLog(string logName)
        {
            ILog log = LogManager.GetLogger(logName);
            log4net.Config.XmlConfigurator.Configure();
            return log;
        }
    
    Peter Lillevold : LogManager.GetLogger will automatically configure the appdomain when the XmlConfigurator attribute is present in the assembly. Thus, you should not call XmlConfigurator.Configure() since that will cause you to initialize log4net for each logger you're getting.
    Jay : Thanks just what I needed
  • Charles,

    Thank you for your suggestion. The problem was actually "operator headspace" rather than anything wrong on the config part. I copied the log4net example, but I didn't change appender. I am able to use the log4net config section embedded in my config file without any problems.

Need RTF/doc to html converter, preferably free

I have a problem with low end users needed to convert word documents to html.

Their formatting sucks and so does the standard word html conversion. I don't particularly feel like teaching marketing people html, so I was wondering what might be a good (cheap/free) solution.

They are happy to copy paste text from word into RTF (as complex as formatting goes) then click a process button. I'd love a good rtf that showed them exactly what their code would look like when compiled, so they could edit, the double spaces / bad alignments and such out and compile it into nice looking html.

Can anyone help out

Regards, Nonick

From stackoverflow
  • I've been looking for a (free) RTF2HTML converter for a while and recently stumbled upon this: http://www.codeproject.com/KB/recipes/RtfConverter.aspx.

    I've not evaluated it yet but it looks promising.

    Joe : It won't create RTF, only parse it. Also, it doesn't handle a bunch of elements -- including tables.
  • OpenOffice.org Writer

  • Word 2007 allows you to save in html. It offers a few different option; single file web page, web page, and filter web page. The filter web page turns out fairly nice. Im sure OpenOffice offers similar tools.

Can VS2008 Testrunner run MbUnit tests or not?

Ok, so I keep seeing how VS2008 has this nice unit test display and I can see people running NUnit tests within it on Dimecasts.net and this article seems to imply that MbUnit v3 should have support for using visual studio's test runner. And yet I can't get it to recognize my tests.

Has anyone else been able to get Visual Studio to run their MbUnit tests and if so did you have to do anything special to get it configured?

From stackoverflow

C++ Instance Initialization Syntax

Given a class like this:

class Foo {
public:
    Foo(int);

    Foo(const Foo&);

    Foo& operator=(int);

private:
    // ...
};

Are these two lines exactly equivalent, or is there a subtle difference between them?

Foo f(42);

Foo f = 42;


Edit: I confused matters by making the Foo constructor "explicit" in the original question. I've removed that, but appreciate the answers.

I've also added declaration of a copy constructor, to make it clear that copying may not be a trivial operation.

What I really want to know is, according to the C++ standard, will "Foo f = 42" directly call the Foo(int) constructor, or is the copy constructor going to be called?

It looks like fasih.ahmed has the answer I was looking for (unless he's wrong).

From stackoverflow
  • Foo f = 42;
    

    This statement will make a temporary object for the value '42'.

    Foo f(42);
    

    This statement will directly assign the value so one less function call.

    Marcin : That's not true. All modern compilers will create identical code from both of these examples.
    fasih.ahmed : Just today I was playing with this and modern compilers failed to create identical code. I'm talking latest version of gcc on Linux Enterprise Server 5. Try running that code and you'll find out.
    Kristopher Johnson : FWIW, I'm less concerned with "create identical code" than the formal equivalence or non-equivalence of the statements.
    Johannes Schaub - litb : Marcin, but it will still check semantics of the call.
    Johannes Schaub - litb : even though it optimizes temporaries
    Gorpik : Foo f = 42 is equivalent to Foo f (Foo(42)) in any conforming compiler. If the copy constructor implementation is not available when compiling the call, it cannot be optimised, since the constructor might have side effects.
    Gorpik : Ups, sorry for the previous comment. According to the standard, the compiler is allowed to do the optimisation even if the copy constructor implementation is not available. So, if the constructor does indeed have side effects, the call is somewhat undefined.
    Johannes Schaub - litb : Gorphik, it aren't the side effects. even tho there are side effects, the copy can still be elided. the point is the visibility of the copy constructor, and no the compiler is *not* allowed to elide the copy if the copy constructor is not visible.
  • class Foo {
    public:
        Foo(explicit int);
    
        Foo& operator=(int);
    };
    

    That's invalid. The syntax is

    class Foo {
    public:
        explicit Foo(int);
    
        Foo& operator=(int);
    };
    

    The difference is that the conversion constructor cannot be used for implicit conversions when you put explicit before it:

    Foo f(10); // works
    Foo f = 10; // doesn't work
    

    The above doesn't have anything to do with an assignment operator you declared there. It is not used since that is an initialization (only constructors are used). The following will use the assignment operator:

    Foo f;
    f = 10;
    

    And will use the default constructor of Foo (the one taking no arguments).


    Edit: The questioner changed his question to the specific ways of whether

    Foo f = 1; // called "copy initialization" 
    Foo f(1);  // called "direct initialization"
    

    Are the same. The answer is that they are equivalent to the following:

    Foo f(Foo(1));
    Foo f(1);
    

    If and only if the conversion constructor taking the int is not declared with keyword explicit, otherwise the first is a compiler error (see above). The compiler is allowed to elide (optimize out) the temporary passed to the copy constructor of Foo in the first case if all semantic restrictions are still safisfied, and even if the copy constructor has side effects. That especially includes a visible copy constructor.

    fasih.ahmed : Thats what i tried to explain. I guess I failed.
    Kristopher Johnson : Sorry, I didn't mean to have the "explicit" in the question. I've updated it.
    Johannes Schaub - litb : still i don't think i will delete that part of my answer. the bottom part answers what your assignment op is for
    j_random_hacker : Thanks for the detailed explanation. It's rules like "The compiler is allowed to elide... even if the copy ctor has side effects" that make me hate C++ sometimes. I mean, how could they make it any more confusing and potentially damaging???
    Johannes Schaub - litb : j_random_hacker. i think it's because the copy constructor is used to copy instances. if there is no copy necassary, why should it copy? the cctor should not change any global state anyway (it should just initialize *this). i think it's reasonable to allow the compiler to not make the copy then.

Submit with JQuery in firefox 3 & opera in a modal dialog box from SimpleModal

I'm trying to submit a form who is rendered in a SimpleModal dialog, but my submit is never called when I'm using FF3 & Opera (Chrome, Safari and IE works). I use the following code:

function ShowModal(rendercontainerid, modalcontainerid, url) {
    if (url == '')
        return;
    $.get(url, function(data) {
        $(rendercontainerid).html(data);
        $(rendercontainerid).modal({ 
            close: false,
            containerId: modalcontainerid,
            onOpen: function(dialog) {
                dialog.overlay.fadeIn('slow', function() {
                    dialog.container.slideDown('slow', function() {
                        dialog.data.fadeIn('slow');
                    });
                });
            },
            onClose: function(dialog) {
                dialog.data.fadeOut('slow', function() {
                    dialog.container.slideUp('slow', function() {
                        dialog.overlay.fadeOut('slow', function() {
                            $.modal.close(); // must call this!
                        });
                    });
                });
            }
        });
    });
}

function CloseDialog() {
    $.modal.close();
}

function SubmitAndClose(rendercontainerid) {
    $(rendercontainerid).find('form').submit();
    CloseDialog();
    window.location = window.location;
}

function AjaxSubmitAndClose(rendercontainerid) {
    var form = $(rendercontainerid).find('form');
    var url = $(form).attr('action');
    var postData = $(form).serializeArray();

    var options = {
        dataType: 'json',
        success: AjaxSubmitSucces
    };

    $(form).ajaxSubmit(options);
}

function AjaxSubmitSucces(data) {
    if (data.ErrorMessage != '') {
        alert(data.ErrorMessage);
    }
    else if (data.RedirectUrl != '') {
        CloseDialog();
        window.location = data.RedirectUrl;
    }
}

I also tried to the jquery.form plugin for ajax posting but then you will see the formdata(An fckeditor) is in the initial values(it looks like it is cached).

From stackoverflow
  • Try using the onShow callback:

    onShow: function (dialog) {
      // bind form submit in dialog
      dialog.data.find('form').submit(function (e) {
        e.preventDefault();
        // do stuff here
      });
    }
    

Two 'self-updating' properties in WPF MVVM

Considering you have an MVVM Architecture in WPF like Josh Smith's examples

How would you implement two properties 'synced' that update eachother? I have a Price property, and a PriceVatInclusive property in my model.

-When the Price changes, I want to see the Vat inclusive price to automatically be 'Price * 1.21'.

-Vice versa, when the PriceVatInclusive changes, I want the Price to be 'PriceVatInclusive / 1.21'

Any ideas on that?

And what if your model is a Entity framework entiry? You can't use the approach above then... no? Should you put calculating code in the ViewMOdel or ... ?

From stackoverflow
  • One way:

        public class Sample : INotifyPropertyChanged
        {
            private const double Multiplier = 1.21;
            #region Fields
            private double price;
            private double vat;
            #endregion
    
            #region Properties
            public double Price
            {
                get { return price; }
                set
                {
                    if (price == value) return;
                    price = value;
                    OnPropertyChanged(new PropertyChangedEventArgs("Price"));
                    Vat = Price * Multiplier;
                }
            }
    
            public double Vat
            {
                get { return vat; }
                set
                {
                    if (vat == value) return;
                    vat = value;
                    OnPropertyChanged(new PropertyChangedEventArgs("Vat"));
                    Price = Vat / Multiplier;
                }
            }
            #endregion
    
            #region INotifyPropertyChanged Members
            protected void OnPropertyChanged(PropertyChangedEventArgs e)
            {
                PropertyChangedEventHandler ev = PropertyChanged;
                if (ev != null)
                {
                    ev(this, e);
                }
            }
            public event PropertyChangedEventHandler PropertyChanged;
    
            #endregion
        }
    

    If you can derive from DependencyObject, you can use Dependency Properties.

    public class Sample : DependencyObject
    {
        private const double Multiplier = 1.21;
    
        public static readonly DependencyProperty VatProperty =
            DependencyProperty.Register("Vat", typeof(double), typeof(Sample), 
            new PropertyMetadata(VatPropertyChanged));
    
        public static readonly DependencyProperty PriceProperty =
            DependencyProperty.Register("Price", typeof(double), typeof(Sample), 
            new PropertyMetadata(PricePropertyChanged));
    
        private static void VatPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
        {
            Sample sample = obj as Sample;
            sample.Price = sample.Vat / Multiplier;
        }
    
        private static void PricePropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
        {
            Sample sample = obj as Sample;
            sample.Vat = sample.Price * Multiplier;
        }
    
        #region Properties
        public double Price
        {
            get { return (double)GetValue(PriceProperty); }
            set { SetValue(PriceProperty, value); }
        }
    
        public double Vat
        {
            get { return (double)GetValue(VatProperty); }
            set { SetValue(VatProperty, value); }
        }
        #endregion
    }
    
    Tom Deleu : Yes ok, But what if your model is a Entity framework entiry? You can't use the approach above then... no? Should you put calculating code in the ViewMOdel or ... ?

Create modified HFONT from HFONT

I using the Win32 API and C/C++. I have a HFONT and want to use it to create a new HFONT. The new font should use the exact same font metrics except that it should be bold. Something like:

HFONT CreateBoldFont(HFONT hFont) {
    LOGFONT lf;
    GetLogicalFont(hFont, &lf);
    lf.lfWeight = FW_BOLD;
    return CreateFontIndirect(&lf);
}

The "GetLogicalFont" is the missing API (as far as I can tell anyway). Is there some other way to do it? Preferrably something that works on Windows Mobile 5+.

From stackoverflow
  • You want to use the GetObject function.

    GetObject ( hFont, sizeof(LOGFONT), &lf );
    
  • Something like this - note that error checking is left as an exercise for the reader. :-)

    static HFONT CreateBoldWindowFont(HWND window)
    {
        const HFONT font = (HFONT)::SendMessage(window, WM_GETFONT, 0, 0);
        LOGFONT fontAttributes = { 0 };
        ::GetObject(font, sizeof(fontAttributes), &fontAttributes);
        fontAttributes.lfWeight = FW_BOLD;
    
        return ::CreateFontIndirect(&fontAttributes);
    }
    
    static void PlayWithBoldFont()
    {
        const HFONT boldFont = CreateBoldWindowFont(someWindow);
        .
        . // Play with it!
        .
        ::DeleteObject(boldFont);
    }
    

Using two css files in the same html file

Is it possible to use 2 CSS classes that have the same name for the selectors, etc. in the same HTML file? If so, how do you differentiate between the two when styling elements?

From stackoverflow
  • Yes it is possible. The definitions in second file will overwrite the definitions of the first file. There is no way to differentiate between the two but to prepend the class names according to the file.

  • do you mean 2 definitions for the same class? or 2 class names on an element?

    The first case, no.

    <style>
      .foo{
        border:1px solid blue;
        color:red;
      }
      .foo{
        border:4px solid orange;
      }
    </style>
    <div class="foo">this will have an orange border and red text (no blue border)</div>
    

    The second case, yes

    <div class="class1 class2">this is valid</div>
    
    Xaisoft : 2 similar class names in 2 separate files.
    Jonathan Lonowski : Well, true. But, misleading. Each new definition expands/overrides the last. The "foo" div will still have red text.
    scunliffe : Ah my bad, my code sample didn't match my thought. Xaisoft: if the names are different, then you are totally fine, you can do whatever you want. The only issue is if the names are the exact same.
  • ...that have similar names for the selectors

    If the names really are similar and not identical then there shouldn't be a problem.

    Xaisoft : Assume they are identical.
    John Topley : I've edited the question to reflect this.
    EBGreen : Well, then the overwrite answers that you already have are the right answer.
  • Yes this is possible, simply include two css files in the HEAD section of the document. Any styles set in the first will be overwritten in the second, so say you have this:
    First file:

     #something{
      background-color: #F00;
      color: #FFF;
     }
    

    And then in the second file:

     #something{
      background-color: #000;
     }
    

    Then the background color for #something will be overwritten in the second file to black but the color will stay the same since the second file doesn't say anything about it.

How to implement paging using a HTML table?

I have an html table which i bind data dynamically on the server side in C#.. The problem is that I have a search button that calls a search on the DB(in a search method on the server side) based on the information from the client page. this search method loads the info from the DB and updates the html table(this is where the information is binded dynamically)

for (int i = 0; i < data.Count; i++)
{   
  FirstCell.Controls.Add(lbl1);

  SecondCell.Controls.Add(lbl2);

  ThirdCell.Controls.Add(lbl3);      
  row.Cells.Add(FirstCell);

  row.Cells.Add(SecondCell);

  row.Cells.Add(ThirdCell);

  Table.Rows.Add(row);
}

... and after this is done I store the loaded objects from the DB in a session variable like: Session{"data"]=data;

my question is how do I display the html table with a certain number of records per page with the page's indexes at the bottom of the view page below the table? And as I iterate through the pages keep the data viewable and not lost? I am not trying to use ASP.net data controls!!!

From stackoverflow
  • I know this doesn't exactly answer your question, but doesn't the standard ASP.NET DataGrid support paging out of the box? Or do you not want to use ASP.NET controls. Just curious....

    TStamper : I do not want to use asp data controls...
  • Have you seen this post about how to implement client-side paging in a Gridview control using JQuery? There is an example of it in action here - Datagrid paging using JQuery example

    This could be modified to work with a html table.

    TStamper : @Russ What would I do without you..

Including a MP3 Encoder with your application

Part of a web application I'm working on turns text into speech and then turns the wav stream into a mp3 using LAME encoder.

How would one go about licensing the mp3 encoder with the company that owns the patent so we can redistribute the web application and still be legal and what could be cost be involved with that or would it be better to just drop the mp3 encoding and go to a different audio format?

MP3's work great but the patent problems with it are a REAL pain!

From stackoverflow
  • Maybe go with a less troublesome format? Aiff?

    http://en.wikipedia.org/wiki/Audio_Interchange_File_Format

  • This may be wrong, but this is what I've gathered. From Wikipedia: MP3#Licensing and patent issues:

    A large number of different organizations have claimed ownership of patents necessary to implement MP3 [...] have many different expiration dates, ranging from 2007 to 2017 in the U.S [...]
    See this big list and this informative article.

    It seems the main patent-enforcing organization are Thomson Consumer Electronics and the Fraunhofer institute, whose website at mp3licensing.com lists some "royalty rates": US $5.00 per unit for encoding -- presumably that means that for every copy of your software you sell, they get $5. It's not clear what the notion of "unit" is for web applications. If you're simply using LAME encoder, are you infringing the patent directly? I don't know; I'm not a lawyer. Now you know why people want to stop/end/oppose software patents.

    In my opinion, it is best to just avoid all this hassle and use an unencumbered format, such as Ogg Vorbis, or Speex (by the same Xiph.org) which is specifically tailored for speech, or others. You could also just use a lossless format like WAV or FLAC and leave the encoding to the users, but this would require huge downloads.

How can I convert messages in an mbox file to UTF-8?

Hello,

I am trying to modify the below program to ensure each msg is converted to utf-8 using Encode::decode(), but I am unsure of how and where to place this to make it work.

#!/usr/bin/perl
use warnings;
use strict;
use Mail::Box::Manager;

open (MYFILE, '>>data.txt');
binmode(MYFILE, ':encoding(UTF-8)');


my $file = shift || $ENV{MAIL};
my $mgr = Mail::Box::Manager->new(
    access          => 'r',
);

my $folder = $mgr->open( folder => $file )
or die "$file: Unable to open: $!\n";

for my $msg ( sort { $a->timestamp <=> $b->timestamp } $folder->messages)
{
    my $to          = join( ', ', map { $_->format } $msg->to );
    my $from        = join( ', ', map { $_->format } $msg->from );
    my $date        = localtime( $msg->timestamp );
    my $subject     = $msg->subject;
    my $body        = $msg->decoded->string;

    # Strip all quoted text
    $body =~ s/^>.*$//msg;

    print MYFILE <<"";
From: $from
To: $to
Date: $date
Subject: $subject
\n
$body

}
From stackoverflow
  • Nothing in the script seems to be specifying what encoding you expect the input to be in... normally that's important since auto-detection of character encodings in hard (and not usually supported by encoding libraries).

  • From the documentation I suspect you want to replace

    my $body        = $msg->decoded->string;
    

    with

    my $body        = $msg->decoded('UTF-8')->string;
    

    Though I'm not completely sure and it may not matter at all.

How to set a breakpoint in Eclipse in a third party library?

I'm getting a NullPointerException in a Class from a 3rd party library. Now I'd like to debug the whole thing and I would need to know from which object the class is held. But it seems to me that I cannot set a breakpoint in a Class from a 3rd party.

Does anyone know a way out of my trouble? Of course I'm using Eclipse as my IDE.

Update: the library is open-source.

From stackoverflow
  • You can easily set method breakpoints in 3rd party libraries without having the source. Just open the class (you'll get the "i-have-no-source" view). Open the outline, right-click on the method you want and create the method breakpoint (I don't know of the exact words in the menu right now, you'll find it).

  • Normally, you should be able to set a break point. Especially if the 3rd party library is open source. But if your 3rd party lib is from a commercial vendor, they may have compiled the source with the debug flag turned off. This will make it impossible for you to debug into it. Your vendor might have done this as part of an obfuscation process to make it impossible to reverse engineer the library, or just simply because the final compiled classes will be smaller.

    boutta : I will ask a colleague if the debug flag was turned off.
  • You can also set breakpoints on specific exceptions. From the Debug perspective, there's a button "Add Java Exception Breakpoint", and there you can add "NullPointerException". Your debugger will then suspend execution as soon as such an exception is raised.

    boutta : This doesn't catch the Exceptions flung in the library. Maybe there is something about what Bent said with the debug flags not set.
    Robin : I've never seen that happen. The JVM still has the stack trace, just no source or line numbers, so it should still break on the exception.
  • The most sure-fire way to do this (and end up with something that's actually useful) is to download the source (you say that it is open-source), and set up another "Java Project" pointing at that source.

    To do that, get the source downloaded and unzipped somewhere on your system. Click "File"->"New"->"Java Project". In the next dialog, give it a project name and select "Create Project from Existing Source". Browse to the root location of the open source library.

    Supposing that all the additional libraries that are required by the project and such are included in the project you downloaded, Eclipse will figure everything out and set the build path up for you.

    You'll need to remove the open source jar from your project's build path, and add this new project to the build path of your project.

    Now, you can just treat this as your code, and debug at will.

    This gets around at least a couple of problems with other approaches:

    1. You could "attach source" to the jar file, but if the jar file was compiled without debug information, this still won't work. If the jar file was compiled with debug information (lines,source,vars...see http://java.sun.com/j2se/1.3/docs/tooldocs/win32/javac.html, and the -g option).

    2. You could add an "exception breakpoint" to see when the NullPointerException is raised, but that's a common exception, and may well get raised and dealt with many (hundreds of?) times prior to the one you're looking for. Plus, without the original source, you won't be able to really see much of anything about the code that is throwing the NullPointerException - the likelihood you'll be able to figure out what's wrong is pretty low.

Rhinomocks 3.5 for dummies...ie me

I'm trying to use Rhinomocks 3.5 and the new lambda notation to mock some tests. I've read this, but have so many more questions. Are there any complete examples out there, especially for a MVC type of architecture?

For example what is the best way to mock this.

 public void OnAuthenticateUnitAccount()
 {
  if(AuthenticateUnitAccount != null)
  {
   int accountID = int.Parse(_view.GetAccountID());
   int securityCode = int.Parse(_view.GetSecurityCode());
   AuthenticateUnitAccount(accountID, securityCode);
  }
 }

There is a view interface and a presenter interface. It's calling an event on the controller.

What I came up with is this.

[TestMethod()]
 public void OnAuthenticateUnitAccountTest()
 {
  IAuthenticationView view = MockRepository.GenerateStub<IAuthenticationView>();
  IAuthenticationPresenter target = MockRepository.GenerateMock<IAuthenticationPresenter>();

  target.Raise(x => x.AuthenticateUnitAccount += null, view.GetPlayerID(), view.GetSecurityCode());
  target.VerifyAllExpectations();
 }

It passes but I don't know if it is correct.

And yes we are doing the tests after we developed...it needed to be done quickly.

From stackoverflow
  • I'm making the assumption that this is in one of your controllers. Further, I'm assuming that you have a way to pass the view data in via a constructor or setter, and that you have a way to register the AuthenticateUnitAccount handler. Given that, I'd do something like the following:

    [TestMethod]
    public void OnAuthenticateUnitAccountSuccessTest()
    {
        IAuthenticationView view = MockRepository.GenerateStub<IAuthenticationView>();
        view.Stub( v => GetPlayerID() ).Returns( 1 );
        view.Stub( v => GetSecurityCode() ).Returns( 2 );
    
        FakeAuthenticator authenticator = MockRepository.GenerateMock<FakeAuthenticator>();
        authenticator.Expect( a => a.Authenticate( 1, 2 ) );
    
        Controller controller = new Controller( view );
        controller.AuthenticateUnitAccount += authenticator.Authenticate;
    
        controller.OnAuthenicateAccount()
    
        authenticator.VerifyAllExpectations();
    }
    

    The FakeAuthenticator class contains an Authenticate method that matches the signature of your handler. Because you need to know if this method is called, you need to mock it rather than stub it to make sure it is called with the proper arguments, etc. You'll notice that I'm directly invoking the method rather than raising an event. Since you only need to test your code here, there's no need to test what happens when the event is raised. You may want to test that elsewhere. Here we just want to know that the proper methods get called with the right arguments.

    For failure you could do something like:

    [TestMethod]
    [ExpectedException(typeof(UnauthorizedException))]
    public void OnAuthenticateUnitAccountFailureTest()
    {
        IAuthenticationView view = MockRepository.GenerateStub<IAuthenticationView>();
        view.Stub( v => GetPlayerID() ).Returns( 1 );
        view.Stub( v => GetSecurityCode() ).Returns( 2 );
    
        FakeAuthenticator authenticator = MockRepository.GenerateMock<FakeAuthenticator>();
        authenticator.Expect( a => a.Authenticate( 1, 2 ) )
                     .Throw( new UnauthorizedException() );
    
        Controller controller = new Controller( view );
        controller.AuthenticateUnitAccount += authenticator.Authenticate;
    
        controller.OnAuthenicateAccount()
    
        authenticator.VerifyAllExpectations();
    }
    
    nportelli : No, it isn't in the controller. It's in the presenter actually. You are correct that the presenter gets the view assigned in the constructor. All that method is doing is calling an event that the controller is listening to. But your example definitely helps.

Can entire page be developed out of ajax in asp.net 3.5?

My requirement is to develop a page with 4 sections, which cannot have a postback. Section 1. Content which can be changed on user click Section 2. List of users viewing the page online (Auto update when user leaves or visits the page ) Section 3. Chat for the users online Section 4. Rating the content and other functionality for Section 1

Please advise me how to go about it ? Also let me know if there are other easy options in this scenario. One of the options considered was GWT, dropped due to the fact that entire application is being developed in .nET

Any help regarding this will be highly appreciated. Freelancers willing to work on this will be highly rewarded.

From stackoverflow
  • Yes, this is entirely possible using MS Ajax.

    Check out this book, which describes how to write entire web applications without using any postbacks:

    http://www.amazon.com/Developing-Service-Oriented-Applications-Microsoft%C2%AE-PRO-Developer/dp/0735625913/ref=sr_1_9?ie=UTF8&s=books&qid=1229457728&sr=8-9

  • It depends how you define the term "postback". Of course, you could design a whole application without a single postback, I'm not sure exactly how useful it would be unless it was for word processing or something.

    Some people have commented that using the UpdatePanel is okay - well...that's not really without postbacks. An UpdatePanel posts the whole page back in the background, the ASP.NET webserver processes the entire page using the full page lifecycle, so it's not strictly no-postback.

    I've got an application that I wrote that has no postbacks (if by no postbacks you mean, no visible full page refreshes) that communicates with the server using a number of UpdatePanels for each section of the page. You can also use the JavaScript XmlHttpObject to write your own AJAX calls to the server - once again, strictly speaking, this is still a postback it just doesn't visibly update the entire page in the user's browser. If you're using the JavaScript XmlHttpObject, it's fairly simple to make webservice calls.

    Some good reading for this is:

Combining two PDF files in C++

In C++ I'm generating a PDF report with libHaru. I'm looking for someway to append two pages from an existing PDF file to the end of my report. Is there any free way to do that?

Thanks.

From stackoverflow
  • You can use the Ghostscript utility pdf2ps to convert the PDF files to PostScript, append the PostScript files, and then convert them back to a PDF using ps2pdf.

    Troy Howard : As much as I love Ghostscript, this solution is really a kludge for anything other than a one-off. That's a really big hammer for such a simple task.
  • Try PoDoFo

    http://podofo.sourceforge.net/

    You should be able to open both of the PDFs as PDFMemDocuments using PDFMemDocument.Load( filename ). Then, aquire references to the two pages you want to copy and add to the end of the document using InsertPages, or optionally, remove all but the last two pages of the source document, then call PDFDocument.Append and pass the culled document. Hard to say which would be faster or more stable.

    Hope that helps, Troy

    Imbue : I ended up using the PoDoFo with the InsertPages method. It seems to actually delete all but the needed pages internally. It also crashes on some PDF files, but it works on simple tests and should be OK for my purposes. Thanks.