Friday, February 11, 2011

ASP.NET MVC 2 strongly typed htmlhelper, indexes

public class Foo { public bool Checked {get;set;}}

View:

<viewdata model="Foo[] fooList" />
<for each="var f in fooList">
    ${Html.CheckBoxFor(x=>x[fIndex].Checked)}
</for>

Will output:

<input id="Checked" name="Checked" type="checkbox" value="true" />
<input name="Checked" type="hidden" value="false" />

<input id="Checked" name="Checked" type="checkbox" value="true" />
<input name="Checked" type="hidden" value="false" />

<input id="Checked" name="Checked" type="checkbox" value="true" />
<input name="Checked" type="hidden" value="false" />

Problem is that System.Web.Mvc.ExpressionHelper.GetExpressionText does not include index in id/name.

That leads to problems in case I want to add a label for every checkbox (because all id`s are the same).

Any ideas how to handle this properly?


From the MVC source=>

 while (part != null) {
            if (part.NodeType == System.Linq.Expressions.ExpressionType.MemberAccess) {
                MemberExpression memberExpressionPart = (MemberExpression)part;
                nameParts.Push(memberExpressionPart.Member.Name);
                part = memberExpressionPart.Expression;
            }
            else {
                //arghhhh... [index] != MemberAccess :(
                break;
            }
        }
  • Use the CheckBoxFor overload that allows you to specify html attributes:

    CheckBoxFor(TModel)(HtmlHelper(TModel), Expression(Func(TModel, Boolean)), IDictionary(String, Object))
    

    For example,

    ${Html.CheckBoxFor(x => x[fIndex].Checked, new { id = "foo" + fIndex) })}
    
    Arnis L. : That's not **properly**. In this case - let me ask what's the benefit of `CheckBoxFor` 'strongly-typed' helper method if i won't be able to get that id back from view model without messing around with hard-coded strings? That's the same as to use `${Html.CheckBox("foo"+fIndex,m.AllCatalogs[i].Checked)}` which even looks better.
    Brettski : @Arnis L. Agreed
    From Ajw
  • The ability of the expression-based helpers to understand indexes isn't in the product yet. It will be in the next preview release (whatever comes after MVC 2 RC). See http://aspnet.codeplex.com/WorkItem/View.aspx?WorkItemId=4970.

    Arnis L. : Your are hero of the day. :P
    From Levi

Differences in WCF 2.0 framework vs WCF 3.5 framework

Hi, I am wondering if there are any updates / differences to WCF from 2.0 framework to the 3.5 framework?

Thanks

automatically close batch file when done

How would I make this close itself when its done?

copy h2.cfg default.cfg /y
c:
cd "c:\program\reba"
"c:\program\reba\reba.exe"

i tried adding:

cls
@exit

in the end but i didnt work

edit: i want the cmd window to close when reba has loaded

  • You'll need to run reba.exe in the background.

    The shell command START should do the trick for you. Here is some documentation on it:

    http://ss64.com/nt/start.html

    I think you can say something like

    START "" "c:\program\reba\reba.exe"
    

    in your batch file (i.e. just add the START).

    Joey : Note that you should never blindly use spaces around the first argument when dealing with `start`. This causes the argument to be interpreted as the window title for the new window and then the program to run is missing. Which means it will just spawn a new `cmd` window with the respective window title.
    Carl Smotricz : Ah, very interesting! That's why the doc I quoted makes those mysterious admonitions that you should always include a title, without giving a sensible reason why. This clears things up, thanks!

How i Can Decrease the loading time of Crystal Report File

Hi

How i can Decrease the report file Loading Time? I Use this Code to Load a Report File

reportDocumnet.Load(reortFilePath);

but the first time loading is very long.

just in first time running this code

i want use a way to run this line of my code speedly

  • Some people load a report in background thread on program startup. Then the massive crystal libraries will be loaded when user runs the first report.

    hosseinsinohe : that right i want use other ways pleaze help me
    From dotjoe
  • How much time spent in the SQL/data plan generation? Can you create a view in your database to speed up the content resolution? Can you cache previously generated reports that have the same query parameters?

    hosseinsinohe : just this line of my code runing in long time(in first time) And this not realated to load data
  • To follow on with what has been said about preloading crystal libraries have a look at this article

    http://www.google.co.uk/search?hl=en&source=hp&q=http%3A%2F%2Fwww.experts-exchange.com%2FDatabase%2FReporting_%2FCrystal_Reports%2FQ_24295843.html&btnG=Google+Search&meta=&aq=f&oq=

    dotjoe : bold move linking to expert sexchange :) why can you only see the answers if linked from google search? http://www.google.com/search?q=Slow+opening+of+Crystal+Reports+in+.NET+Run+time&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a
    David : @dotjoe Bizarre! Changed link to ensure anyone using will reach answer. Thanks.
    From David

springs authentication, does it use encrypted cookies?

Does the spring framework use (or in one of the options that it supports) encrypted cookies that store the logged in users userId in a cookie?

This is how asp.net authentication works, where it encrypts a value in a cookie, which is normally the userId or username.

Is that what spring does? (I realize spring let's you choose, but is this the most common approach generally?)

  • Storing user ID or any kind of data the server relies upon is a terrible idea. It typically means as soon as someone figures out how your encryption works (which is only a matter of time, particularly when they have a crib as user IDs tend to be public too) they can probably compromise your system.

    In case you're wondering what a "crib" is. see Cryptography FAQ (03/10: Basic Cryptology):

    Cryptanalytic methods include what is known as practical cryptanalysis'': the enemy doesn't have to just stare at your ciphertext until he figures out the plaintext. For instance, he might assumecribs''---stretches of probable plaintext. If the crib is correct then he might be able to deduce the key and then decipher the rest of the message. Or he might exploit ``isologs''---the same plaintext enciphered in several cryptosystems or several keys. Thus he might obtain solutions even when cryptanalytic theory says he doesn't have a chance.

    Java Web apps typically just store a session ID and that session on the serverside contains such information as user ID. That's much more secure.

    mrblah : Funny how MS doesn't think so :) Probably 95% of .net apps store either the user id or username in the cookie!
    matt b : do you have a source for this claim?
    cletus : If you have a system where the user just needs to figure out a) what encryption algorithm you use (usually pretty obvious) and b) what the encryption key is (for which you may have one or many cribs) in order to log in as anybody then you don't need to prove that system isn't insecure. It's basic commonsense.
    mrblah : @matt look here: http://msdn.microsoft.com/en-us/library/aa480476.aspx see: FormsAuthentication.SetAuthCookie(userName.Text, false);
    From cletus
  • I don't have the source handy to prove this, but the answer to the question is no.

    Spring Security handles everything on the server side. The only cookie on the client is the one for JSESSIONID, and the security framework merely checks for the authentication/principal object in the request's session (at least under the default setup).

    I don't understand why you would store any sort of authentication information in the client's cookie if you could simply store a sessionID and track authentication details and state on the server side.

    mrblah : sessions are bound to a specific server.
    matt b : and a load balancer with sticky sessions makes that a moot point
    mrblah : true, but who wants sticky sessions if you have other options.
    matt b : people that don't want to put user information in cookies or worry about encryption :) or apps that need to maintain state during a user's session.
    From matt b

Simple XML HELP !!!!

Hi ,

I need some help ,

All I need to do is change "HERE" to a the value of $date

$line1 = $sxe->addChild("date","HERE");

How can I add the value of $date into the area were "HERE" is ?

Please help

  • $sxe->addChild("date", $date);
    
    Oliver Bayes-Shelton : just changed it too $sxe->addChild('date', $date); and it works :) Thanks
    From Ben Marini
  • EDIT: Actually the following wont work unless the date node exists. Listen to the others... We see how often i actually modify structure with SimpleXml ;-)

    $sxe->date = $date;

How to use php value in SimpleXMLElement ?

Hi ,

I know that too add a text value into the xml page I do the following

$person = $sxe->addChild("person");
$person->addChild('first_name');

If I want to use the value of $person how could I code it ?

  • You can get it as

    $personXml = $person->asXML();
    
    From alex

ASP.NET Specify which files should be cached

I am developing a website in ASP.NET and I am using various javascript frameworks/libraries. The different files belonging to these frameworks/libraries rarely changes thus there is no reason to refresh those files once they have been sent to the client browser (atleast not everytime a page is served).

I see that the HttpContext object can be used somehow, that I can set the content expiration on the files/folders on the IIS, or maybe setup somekind of caching in the web.config file.

1. What is best practice/what approach should I take?

If the content expiration on the IIS works, then this is just great (and easy). But during development, I use the ASP.NET Development Server, which does not interact with the external IIS - thus no performance gain achieved during development :(

2. How can I use cache here (depending on question 1)?

I would like to modify this question to be used as a "this-is-how-its-done" thread for future reference for me and others.

  • The cache settings in the HttpContext only control how the aspx page is cached, not the caching of files that the browser include (javascript, css, images...).

    The browser caches the javascript files by default, and that is pretty much the same regardless if you are running the site locally or live. Normally you have to make a Ctrl+F5 or purge the cache if you make changes in a script to get the browser to load the new version.

    So, you don't have to do anything at all, the browswer already caches the files.

    Chau : I actually suspected that what you're saying is true. But when I look at the NET tab in FireBug, it claims that it is using above 10s to recieve a +1MB javascript file - and this is locally. The response header for this file says cache-control: private, and the request header says cache-control: max_age=0.
    From Guffa
  • I think if you are looking for the caching of the files then that has to be done on the IIS end. You can try YSloy (by Yahoo) extension with FireBug. This is very good and should be used as best practice. Hope that will be helpfull :)

    Chau : YSlow is now included in my developer tools. Regarding the javascript files and caching, YSlow complains about none of the having a "far-future expiration date" - which corresponds with the lack of caching I am experiencing.
    From Anil Namde

CakePHP Routing, using a language prefix with a default prefix

I'm trying to create a routing prefix that would be default.

http://localhost/heb/mycont would leave to the Hebrew page, while

http://localhost/mycont would lead to the English page.

Router::connect('/:language/mycont',array('controller'=>'contname','action'=>'index'),array('language'=>'[a-z]{0,3}'));

This code allows me to use 0-3 letters for language, but it still requires a language!

http://localhost/a/mycont would work

http://localhost/mycont doesn't work

Any ideas how to fix that? Is it even possible with the default routing?

  • Let me preface this by stating that I'm not a routing expert, but in this case, it makes sense that what you have wouldn't work because the route is expecting a language parameter; the route won't match if it's not there.

    To "fix" (quoted since it's not really broken), you might want to try setting your default locale and, in your AppController, overwrite if a :language value is present.

    Travis Leleu : This looks like a quick and solid solution to me! The only other reasonable option that I can think of would be to override the Router::connect function so that it will set the default :language value if none is present. But that might be overkill.
  • My solution was simply to setup the / to a specific language, while everything else is marked /:language/

    That way I did not make duplicated routes.

    From Yossi

Routing Problem With Symfony

So I have a module that displays articles. And I tried to make an action that displayed all article of a certain publication when that publication was clicked. I tried following the way to do this on the symfony jobeet tutorials but I ran into some new headaches. Since publications and authors can sometime be url unfriendly, I want to use slugs, and this is where I ran into the problem.

So I have an article module and I added a routing rule like this

publication_articles:
  url:  /publications/:publication_slug
  class: sfDoctrineRoute
  param: { module: article, action: publication }
  options: { model: Article, type: list }

I then added a getPublicationSlug() function to the article class that took out spaces and special characters - nothing special.

I then added this function to the action class:

  public function executePublication(sfWebRequest $request)
  {
      $this->articles = $this->getRoute()->getObjects();
  }

When I try adding a link like this:

<a href="<?php echo url_for('publications/'.$article->getPublicationSlug()) ?>"><?php echo $article->getPublication() ?></a>

The page returns all the articles without any filtering on the publication

and if i add a link like this:

<?php echo link_to($article->getPublication(), 'publication_articles', $article) ?>

I get this error:

The "/publications/:publication_slug" route has some missing mandatory parameters (:publication_slug).

Any ideas? Thanks so much!

  • The object linking referenced in the Symfony guides (url_for('my_route', $obj)) has never worked properly for me. Instead I always generate my routes using direct parameter insertion, try this instead:

    <?php echo link_to($article->getPublication(), '@publication_articles?publication_slug=' . $article->getPublicationSlug()) ?>
    
    Cryo : While the above will fix your immediate issue it looks like you'll have a deeper problem next. After looking into the custom getter routing further it looks like this is not supported by Doctrine at all, only Propel. sfDoctrineRoute will only match on columns that actually exist in the table definition while sfPropelRoute uses reflection to allow for custom getters. You'll need to add your slug columns into your table definition to get this to work.
    Daniel Hertz : Thanks for the help. That's weird bc this page says that this is supported by doctrine. http://www.symfony-project.org/jobeet/1_2/Doctrine/en/07
    Cryo : I was using the same tutorial to implement it but I couldn't get it to work as they said so I dove into the actual sfDoctrinePlugin code and confirmed it. I'm hoping I'm wrong but I wrote a test implementation and couldn't get it to work. If you find a way to make it work please let me know.
    From Cryo
  • I really avoid using sfDoctrineRoute in such cases due to some additional joins that I want to implement, not just getting an object.

    From Darmen

Choosing a test platform for .NET - MbUnit or the one by Microsoft?

I have chosen these two as primary candidates. My thinking goes like this:

  • MbUnit has had a nice start and enjoys a smart, dedicated team of developers.
  • MSFT has many resources and can compete with MbUnit easily if they choose to do so.

Which one do you believe I should bet on?

  • Microsoft unit testing framework is kind of tied to Visual Studio. This is both an advantage and disadvantage. Advantage is you can run tests easily from Visual Studio out of the box, disadvantage is forget about Mono support. It's worth noting that VS2010 will support 3rd party unit test frameworks.

    Jeff Brown : VS 2008 already supports 3rd party unit test frameworks to a degree. Gallio provides Visual Studio integration for MbUnit, NUnit, xUnit.net and others...
    From joemoe
  • I love MbUnit because it supports parametrized tests through attributes. So you can do something like this:

    [Test]
    [Row(2,1,2)]
    [Row(4,3,1)]
    [Row(ExpectedException(typeof(DivideByZeroException)))]
    void TestIntDivision(int numerator, int denominator, int result)
    {
      Assert.AreEqual(result, numerator/denominator);
    }
    
    Hamish Grubijan : I like! Whatever happened to their servers though?
    Jeff Brown : It's fixed. Just a power outage and a misbehaving VM.
    Daniel Schilling : NUnit now has the same thing with their TestCase attribute in version 2.5.
  • NUnit is more widespread, MbUnit has the most features, but MSTest has more manpower behind it. Check this question out: http://stackoverflow.com/questions/261139/nunit-vs-mbunit-vs-mstest-vs-xunit-net

Convert string to C# code

Hi,

in the current NUnit version, I can parameterized TestFixture and instantiated it multiple times. E.g.:

[TestFixture("var1")]  
[TestFixture("var2")]  
[TestFixture("var3")]  
public class MyTestFixture  
{  
    private string var;  

    public MyTestFixture(string var)  
    {  
        this.var = var;  
    }  

    ...  

}  

This will instantiate the MyTestFixture 3 times with the argument parameter. My problem is the current NUnit doesn't have datasource feature for TextFixture attribute (only TestCaseSource). I need to instantiate the TestFixture based on the data input, and each TestFixture has a different sets of test case data input. No problem with the Test case data driven, thanks to the TestCaseSource. But how can I do this for the TestFixture attribute?

My idea is to generate the TestFixture attribute on the fly then change it to code string and insert into the test code, e.g.: something like this:

ConvertToCode(GenerateTestFixture());  
public class MyTestFixture  
{  
   ...  
}  

How can I do this? Or are there a better way?

Thank you very much for your help.

Best regards,
Edward

  • Creating attributes for your method on the fly is possible but hard. You're better off finding another approach.

    Attributes (e.g. [TestFixture]) of the kind you have are read by the compiler when your code is compiled and inserted in to your code automatically.

    To generate your own attributes for classes you'll need to use something like Reflection.Emit to modify generated assemblies as a post-build step for the project. This is like writing assembly language directly (you'd be creating MSIL) which might be fun but is not easy and would make your code very hard to maintain!

    An alternative approach might be to have an enum control the test cases, and have a method that checks the enum and returns the appropriate data:

    public enum TestController
    {
        Value1,
        Value2,
        Value3
    }
    
    [TestFixture(TestController.Value1)]   
    [TestFixture(TestController.Value2)]   
    [TestFixture(TestController.Value3)]   
    public class MyTestFixture   
    {   
        public MyTestFixture(TestController testController)   
        {   
            var dataForTest = GetDataForTest(testController);
        }   
    
        ...   
    
    }   
    

    The method GetDataForTest() would then have some kind of switch statement to generate the data.

    An alternative approach might be to use a type rather than an enum, then instantiate the type in the GetDataForTest() method and call a factory method - but I think that might be a bit overcomplicated.

    Edward : Thank you very much Jeremy. The thing is TestFixture is data-driven, so I wouldn't know in advance how many value there will be. Would the other approach works for data driven TestFixture? If yes, can you please give me a short sample? Again thank you very much for your help. Best regards, Edward
    Jeremy McGee : If you don't know how many there will be then I don't think it will be possible to have seperate tests for each data item. Rather, you'll need to have one test that tests all data items.
    Edward : Actually the test already exist with one test cases test all data items, we also have custom test result to generate result for each data item. But since NUnit 2.5 support data-driven I was tasked to convert the existing test the UNit data driven. This has some benefits over the existing test, such as look better in the UI, can run one test, etc.I can just use the TestCaseSource, the problem is the test name become very long with a lot of duplicates as test cases kind of hierarchical. I think I'll give the Reflection.Emit approach a try. Thank you very much for your help. Best regards, Edward
    Jeremy McGee : Reflection.Emit here is most certainly non-trivial - you're essentially replicating tools like PostSharp that do aspect-oriented programming.

google gears discontinued, html 5 in draft

Hi all,

we've trying to develop a mobile web app that will provide offline capabilities, not just reading but also creating content.

Gears supports three important aspects: - local server so we can have cached static content such as html, css, js, etc - local database so that we can have data stored locally for offline access as well as store new content inside of it while offline - workerpool, used for a background process that syncs data back to the server

By the looks of the gears page and some other articles, gears is being abandoned in favour of html 5 which is understandable.

However, at this stage there are two problems:

  1. there's still a long way to have HTML 5 supported by major desktop browsers,let alone mobile ones
  2. HTML 5 does not support workers, there is a draft http://dev.w3.org/html5/workers/ but I assume real browser support is still far away.

Do what does one do today? (e.g. within the next year) Cheers Rok

  • I think that you have slightly misinterpreted Google's position on Gears. According to an article in the LA Times:

    The Google spokesman wrote to clarify in a follow-up e-mail, "We're continuing to support Gears so that nothing breaks for sites that use it. But we expect developers to use HTML5 for these features moving forward as it's a standards-based approach that will be available across all browsers."

    It sounds to me like it is completely safe to continue using Gears, until and after HTML 5 is ubiquitous.

    Rok : I assume, that the way to go forward is then to create some kind of wrapper/interface that we use in our app and change the underlying implementation in the future as html 5 develops. There is something similar already available (http://code.google.com/p/webstorageportabilitylayer/) but with practically no documentation and only one committed revision... What would you suggest on the worker side?
    Adam Crossland : You can only plan for the future so much. Personally, I wouldn't worry about creating some kind of abstraction layer to mask the differences between Gears and HTML5. I'd code to Gears, get the app done, and watch carefully as HTML 5 matures and becomes widely available. I try to stay away from open source projects with no documentation.
  • HTML5 support is a little better then you think.

    Android has various support for HTML5 standards, with the inclusion of Google Gears into most versions and Android 2.0+ having native support for HTML5 (at least as far as audio/video, canvas, offline storage, and geolocation go). IPhone also supports offline storage along with audio/video tags. WebOS seems to have offline database support, but I don't know much beyond that.

    http://www.whatwg.org/specs/web-workers/current-work/ is the web worker draft implemented in Firefox 3.5 and Safari 4, so they should wind up in IPhone's version of Safari eventually.

    So if you can live without worker threads and don't mind limiting yourself to Android, WebOS, and IPhone, you can use a hybrid approach of HTML5 with a fallback to Gears.

    I don't think supporting other smart-phones is going to be possible in a truly portable way, although Firefox for Mobile (which is nearing release on the Nokia N900) will support all the HTML5 as Firefox 3.6.

    Rok : I tried an Android 1.6 device and it failed to do window.openDatabase js method so offline storage seems to not be supported there. I did not test Android 2.X. Majority of our customers will be running Windows Mobile devices so that is one requirement we have.IE mobile is crap, but Opera mobile+gears run fine. Of course, the more platforms we can support, the better. What do you suggest as a sync replacement for worker threads?
    From sargas
  • Appcache, Web storage & Web workers works on Firefox and newer Android devices.

    Use this handy test http://dev.w3.org/2008/mobile-test/v2/ to profile browsers.

    From hendry
  • HTML 5 does not support workers, there is a draft http://dev.w3.org/html5/workers/ but I assume real browser support is still far away.

    I coded a working example of web workers using the WebKit engine included in Qt 4.6.2. Looking at the code history, support was incorporated sometime in 2008.

    I've been surprised by the level of HTML5 already in (desktop) browsers (excepting IE of course). Mobile lags a few years. I've found this site useful: http://caniuse.com/

Visual Studio VB pretty listing settings

Does anyone know how to stop Visual Studio VB.NET editor from changing my beautiful scientific notation numbers into hideous decimal notation?

It seems that this is part of "Pretty Listing" (single checkbox in the options). I'd like to keep the other features of pretty listing, I just don't want to have to stare at 0.0000000000000001 when I could be looking at 1e-16

  • I don't think there's a way to do it. You could rely on the implicit CDbl() conversion in this situation:

    Dim myPrettyNumber As Double = "1E-16"
    

    Or if you just want to be able to read it more easily, add a comment:

    Dim myUglyNumber As Double = 0.0000000000000001 ' 1E-16
    
    David Rutten : Well, since I always work with Option Strict On, the implicit conversion won't kick in. Sounds like I'm screwed then. The best solution is probably defining some constants somewhere...
    MarkJ : Never never ever use implicit conversion, it's regionally aware and it means your program will only work on certain locales. In this case just use `Val("1E-16")` which is not regionally aware and will always work.
    Cory Larson : ...I was just throwing out some options -- I never claimed they were _good_ options! :)

How should i randomly call class member methods ?

Hi there.

I am writing a small "quiz program". It looks similar to this:

#include <cstdlib>
#include <iostream>
#include <time.h>

using namespace std;

using std::cout;

class cQuestion
{
  private:
    static short goodAnswers[20][2];

  public:
    static void checkAnswer(int questNumber)
    { 
      /* checking input, checking if answer is bad or good */
      /* putting the answer to cQuiz::answArr */
    };

    static void question1(void) { cout << "this is question 1"; };
    static void question2(void) { cout << "this is question 2"; };
    static void question3(void) { cout << "this is question 3"; };
    static void question4(void) { cout << "this is question 4"; };
    static void question5(void) { cout << "this is question 5"; };
    /*and so on to question 20*/
};

short cQuestion::goodAnswers[20][2] = {0,0};

class cQuiz
{
  private:
    static short questArr[5];
    static short answArr[5];

  public:
    void drawRandom(void)
    {
      srand ( time(NULL) );

      for (int i = 0; i < 5; i++ )
        questArr[i] = rand() % 20 + 1;
    };

    void askQuestions(void)
    {
      for (int i = 0; i < 5; i++ )
      {
        /* call questions by question number from questArr */
        /* HOW SHOULD I CALL CERTAIN cQuestion CLASS MEMBER ?? */
        cQuestion::checkAnswer(questArr[i]);
      }
    };
};

short cQuiz::questArr[5] = {0};
short cQuiz::answArr[5] = {0};

int main(int argc, char *argv[])
{
  cQuiz quiz;
  quiz.drawRandom();
  quiz.askQuestions();

  system("PAUSE");
  return EXIT_SUCCESS;
}

I am wondering, how can (or should) I call class cQuestion member methods ? I was thinking about using an array of pointers to these members (cQuestion::question1, cQuestion::question2, and so on) or overloading subscript operator[].

I am not sure if either way is good or bad. Should i consider different solution or somehow use both together? Or am I completely missing the point?

  • Why is each question in its own method? Why not make an array of strings to store the questions?

    From eduffy
  • This is not good design. Having to add a new method for each question means that you have to recompile each time you add aquestion to the quiz. And as you have found out, it is hard to call those functions randomly. A re-design is in order here.

    dygi : Mhm.. I've done it this way, because each `cQuestion::question();` member "builds question", calling some other member methods, from other classes, putting them together on the screen (text, an pseudographic image, and some more).
    anon : That's not a good reason. Making question a class containing the various compinents might be better bet. You then build instances of this class using different components, and the quiz becomes a collection of the question instances.
    dygi : Technically i understand what you say. I know what an instance, composition and collection is but .. Can i ask You for a simple example ? I don't see how can i build instances of the class using **different** components.
    anon : If your questions are all the same form, say some text a graphic and an answer, then the class simply contains instances (say two strings and an image object). If they have variable numbers of components, then you need a vector (or similar container) of pointers to content objects, and the content objects need to instances of classes in a class heirarchy.
    dygi : Ok, so i need a small amount of redesigning to simplify my problem. Thank You very much.
    From anon
  • How about something like this?

    string[] questions = {"Q1","Q2","Q3"};
    void question(int i)
    {
        cout << questions[i];
    }
    
    From Amarghosh
  • Further to the OOP post above, how about:

    class Question { // Make this a C++ interface
      public:
        Question(string q, string a)
          : QuestionText(q), Answer(a)
        {}
        string QuestionText;
        string Answer;    
    } 
    

    Then instantiate these using a factory or just in your initialisation function:

      q1 = Question("What is the secret of life", "DNA");
      q2 = Question("What is the answer to the great question", "42");
    

    You should probably put these in a vector, rather than in local or global variables.

    Martin York : The question is "What is the the answer to life the universe and everything?". Even google has the answer: http://www.google.com/search?hl=en&client=firefox-a&rls=org.mozilla%3Aen-US%3Aofficial&hs=Whw&q=the+answer+to+life+the+universe+and+everything&aq=f&oq=&aqi=g-c1g4g-c2g1g-c1g1
    Alex Brown : Opinion is still divided as to what the actual question is.
    From Alex Brown
  • Apart from all the OOP dilemmas, maintain an array of function pointers to your member functions and randomly select one of them.

    dygi : The fastest and working approach in this situation, thanks. Didn't know about that: `Firstly, you can't use a member function to point to a static member function. You have to use a normal function pointer for that.`
    From Jacob

Ruby on Rails: Aggregating several columns into an Array

I'm developing a Ruby on Rails app where one of my database tables has 10 columns (pile_1 through to pile_10). It would be convenient to access these columns in the model as a 10-element Array.

It feels like I should be able to coerce composed_of into doing what I want, but I can't figure out how. Can anyone enlighten me, or suggest a better tactic?

  • Would

    def piles
        (1..10).map{ |num| self[ "pile_#{ num }"]}
    end
    

    not suffice?

    Chris : Hah. That's neat. In this case, yes, that should do all I need, because I don't expect to need to /write/ to piles_n at any point. Presumably Model.[]() is a method of ActiveRecord::Base?
    tadman : For clarity you might want to use read_attribute("pile_#{num}") instead, but the square-brackets accessor is functionally similar.
    From Farrel
  • Since you have the power to change the schema, you should. Storing an array as separate columns in a table is denormalized. Whether or not your schema is normalized might not matter to you, but your current difficulty is a direct result of a denormalized schema.

    What you ought to do is to create a new table, piles, like so. I'll use postgres syntax, since that's what I know. I don't know the name of the table which currently contains all of the piles* columns, so I'll call it "foo":

    create table piles (
      id serial primary key,
      foo_id int not null references foo(id),
      value text not null,
    );
    

    Every column you now have in foo exists instead as a row in piles. In the model for piles, add:

    belongs_to: foo
    

    and in the model for foo, add:

    has_many: piles
    

    In your controller, once you have a foo in hand, you can access its piles with foo.piles

    Chris : Well, I am doing this somewhat to teach myself RoR, so I should probably teach myself properly and do it like this (although Farrel's solution is tempting in simplicity). What would be the best way to grab input values for the Piles objects in a Foo creation page, in this case? form_for(@foo) presumably won't Just Work; do I want a loop over <% for @pile in @foo.piles %> creating
    s within my form_for? I can't figure out the right syntax. ... should I be creating a new question for this?
    Chris : Having futzed about with a lot of plausible variants, I can't get this to work, and it seems complex. I'm going to mark this answer as Correct (although I may end up resorting to Farrel's less architectural simple solution), and ask a new question about forms.

Creating login using a text file

I'm trying to create a very simple login for only one or two users, the username and password are stored in "admin.txt" the text file is formatted like: username password __ I cannot seem to have the username and password register... Thanks for the help!!

        // username and password sent from form 
       $myusername=$_POST['username']; 
       $mypassword=$_POST['password'];



        $sql = fopen("../admin8183/users/admin.txt", "r");

                    while (!feof($sql)) {
                      $myusername = fgets($sql);
                      $mypassword = fgets($sql);
                      $line = fgets($sql);



         $myusername = trim($myusername);
         $mypassword = trim($mypassword);

                }
            //  counting  rows
         $admin=count(file("../admin8183/users/admin.txt"));

           if($admin==1){
        // Register $myusername, $mypassword and redirect to file "sendmessage.php"
         session_register("myusername");
         session_register("mypassword"); 
          header("location:sendmessage.php");
             }
              else {
            echo "Wrong Username or Password";
              }

p.s. I am sure that there are a few things wrong with my code, and that there are more efficient ways of accomplishing my goal, this is my first stab at creating a login in php... Thanks for your help!

  • First, I must say this is the wrong way to acomplish your task, The offer on the comment to use htpasswd is very right.

    As for your code:

    1. You are using the same $myusername variable when reading from $_POST and from the file. You need to use seperate variables and compare then.
    2. You expect the file to have 3 rows (3 gets), yet you register only if it has 1 row)

    Update:

    Since you can't use htpasswd, i highly recommend hashing your password. Either if you save it in a file or hardcoded, it is a good practice. As @silky pointed out, sha1/md5 are no better then plain text, so here is an implementation of sha256 for PHP.

    Also, don't save your password/username in the sessoion, as @pygorex1 pointed out, use a different variable for marking the user as logged-in.

    Ryan : 1 and 2. are good points ill re evaluate that however, as I said to the other comment, I cannot access my server settings...
    Noon Silk : Avoid SHA1 if you can, it's considered weak and soon-to-be-dead: http://valerieaurora.org/hash.html
    Am : md5 then......?
    Noon Silk : Oh dear, MD5 is most definitely dead; you must use SHA-2 or up (sometime in the near future we should see a SHA-3 class being released, but for now, SHA-2 is pretty much the only option).
    Am : can't seem to find sha-2 for php
    Noon Silk : Am: Then SHA-1 will be acceptable, but just note it down to upgrade when SHA-2 for php becomes available :) (I'd think there is some sort of SHA-256 impl for PHP somewhere, though.)
    Am : @silky: thanks for the link, i`ll go change my own functions now...
    From Am
  • Well, it would seem that fgets() gets an entire line: http://php.net/manual/en/function.fgets.php

    so you are putting the entire line username password into $mysuername and then the next line into $mypassword and so on.

    From zipcodeman
  • There's several problems with this script:

    • $myusername, $mypassword - first these variables are being initialized from $_POST data, then overwritten with the file contents. I don't see any checking of the user-submitted password against the password in the file.
    • The password file is being loaded in twice - once via fopen/fgets and again via file. This is wasteful - load the file only once via file()
    • The following lines: $admin=count(file("../admin8183/users/admin.txt")); ... if($admin==1) will allow anyone access as long as the password file contains only one line. Which will never occur if the username/password are on separate lines. Worse yet, this check is independent of user input.
    • The password is being saved in the session. At the very least, if the username and password are correct, a session variable called $_SESSION['logged_in'] should be set to true.
    • Is the password being stored in an encrypted format? At a minimum the password should be stored as a SHA1/MD5 hash.
    • session_register is deprecated.

    Building a secure user authentication scheme is hard. As others have noted, try using basic Apache authentication. Here's a decent tutorial:

    http://www.nexcess.net/support/tutorials/misc-tools/htaccess-authentication/

    From pygorex1

Strange crash with WTSOpenServer on Windows 7 (Only in Delphi 2009/2010)

I am troubleshooting a problem with existing code that always worked fine (it's the Terminal Server unit from the Jedi Windows Security Library). After some investigation the problem part has been brought down to a call to WTSOpenServer:

  while true do
  begin
      hServer := WTSOpenServer(PChar('server'));
      WTSCloseServer(hServer);
      hServer := 0;
  end;

After a random (but small) number or runs we get a total app crash which makes it hard to debug. Here are the things I already tried:

  • WTSOpenServer does not write to the pServername parameter (like CreateProcessW) (in fact I checked the disassembly and it makes a copy)
  • The code runs fine when passing nil as parameter (and thus work with the localmachine).
  • When using a remote server, localhost or even dummy as pServerName the result is always crash (On Vista and higher even an invalid servername returns a valid handle as per documentation).
  • Tested with both Delphi 2009 and 2010
  • The same code runs fine in Visual Studio (c++).
  • Checked the disassembly in Visual Studio and made the call the WTSOpenServer in asm from Delphi (and change the Handle type to a pointer like in C):

    hModule := LoadLibrary('wtsapi32.dll');
    if hModule = 0 then
      Exit;
    
    
    WTSOpenServer := GetProcAddress(hModule, 'WTSOpenServerW');
    if WTSOpenServer = nil then
      Exit;
    
    
    while true do
    begin
      asm
        push dword ptr pServerName;
        call dword ptr WTSOpenServer;
        mov [hServer], eax;
      end;
    
    
      hServer := nil;
    end;
    
  • Leave out the call to WTSCloseServer

  • Test the code on both x64 and x86 version of Windows 7
  • Use External Debugger instead of Delphi one (seems to run fine in that case so my guess is that it's some kind of timing/thread/deadlock issue)
  • Added AddVectoredExceptionHandler then I see a EXCEPTION_ACCESS_VIOLATION but the stacks seems to be corrupted, EIP is 1 so cannot determine where it happens.

At this point I don't know how to further troubleshoot this or find an explanation.

  • Try run your application with FastMM in FullDebugMode. It looks more like a bug in your/3rd party-lib code - possible memory overwrite/buffer overflow (moslty like sth. GetMem too small for UnicodeString/String alike operations, and it 'works' but will sooner or later crash/AV).

    I've had several similar situations when migrating big app to D2009, and in most cases it was due to assumption Char=1 byte. Sometimes very strange things happened, but always FullDebugMode helped. Exception was CreateProcessW, but it's know/documented behaviour.

    With FullDebugMode if app overwrite memory, then when you free it, FastMM gives you exception where it was allocated, so easly you can track down this bug. It adds some bytes at begining and end of allocation, so will know if it was overwritten.

    I'm not able to reproduce it with new/empty VCL project, you can try it your self (this loop running for about 5 min):

    uses JwaWtsApi32;
    procedure TForm7.FormCreate(Sender: TObject);
    var
      hServer: DWORD;
    begin
      while true do
      begin
          hServer := WTSOpenServer(PChar('server'));
          WTSCloseServer(hServer);
          hServer := 0;
      end;
    end;
    
    Remko : My project consists of only that code! I even brought it back to a console project with using no units at all. Please note that the crash only occurs when running on Windows 7, when debugging, with Delphi 2009 or Delphi 2010.
    kibab : I'm using also Windows 7 (RC, Ultimate 32-bit) and Delphi 2009 (12.0.3420.21218), and using only one additional to std. new VCL project explicit import - JwaWtsApi32 rev. 820 (updated answer about with this). Running from delphi for 5-10min, and also with step-by-step about 30-40 times by that loop. Are you able reproduce it on another machine with same OS/Delphi? My very extreme thoughts about this: virus(rootkit;)/third party bug in code injected to exe, like madExcept,EurekaLog,JDBG,../unusual default Delphi compiler/linker options that is buggy/sth. wrong with OS, updates, antivir, LSP ...
    Remko : Did you test on RC or RTM?
    kibab : Windows 7 RC "I'm using also Windows 7 (RC, Ultimate 32-bit) ..." (get email from info@simulates...)
    Remko : Although I had disabled my Virusscanner/Firewall I still noticed injections of dll's from it (F-Secure Internet Security 2010). I ignored it before because it worked fine under the older Delphi versions but decided to do an uninstall. And guess what? No more crash, will do some more tests and if this was the problem I will accept your answer.
    kibab : So it was possible buggy LSP library (my last "very extreme thought" -> "sth. wrong with ... LSP" ;) It did overwrite memory... You can use Autoruns (http://technet.microsoft.com/pl-pl/sysinternals/bb963902(en-us).aspx?ppud=4), to list all LSP (WinSock Providers), then you can disable/remove some of them - non Microsoft (you will loose some functionality from eg. F-Secure, but it's buggy, so not worth to use it ;). LSP samples from Windows SDK (from MS) are also buggy (and leaks memory), so mostly like delivered work will be buggy too. I know that F-Secure and E-Set LSP dll's are buggy...
    From kibab