Monday, April 11, 2011

What is the best resource for BlackBerry CLDC programming?

I deployed many midlets on Blackberry, but now I want to try their CLDC model. Never deal with it. What is the best resource to read for a quick start (except the BB examples?)

From stackoverflow

What is the best way to embed SQL in VB.NET.

I am looking for information on the best practices or project layout for software that uses SQL embedded inside VB.NET or C#. The software will connect to a full SQL DB. The software was written in VB6 and ported to VB.NET, we want to update it to use .NET functionality but I am not sure where to start with my research. We are using Visual Studio 2005. All database manipulations are done from VB.

Update: To clarify. We are currently using SqlConnection, SqlDataAdapter, SqlDataReader to connect to the database. What I mean by embed is that the SQL stored procedures are scripted inside our VB code and then run on the db. All of our tables, stored procs, views, etc are all manipulated in the VB code. The layout of our code is quite messy. I am looking for a better architecture or pattern that we can use to organize our code.

Can you recommend any books, webpages, topics that I can google, etc to help me better understand the best way for us to do this.

From stackoverflow
  • Would it be possible to convert it to using LINQ? It's safer than converting it to using regular old embedded SQL statements.

  • It sounds like you're looking for a grand theoretical book that is written for one very specific case, i.e. what is the best practice for managing our current spaghetti SQL code framework, and I don't know that I've ever seen a book or document that describes that.

    That being said, we converted several applications from VB6 to C# a few years back and were in the same place. Other than breaking apart certain modules so that their organization made more logical sense overall, our applications are essentially the same as they were, just rewritten in C#. I don't personally like the idea of separating SQL code from the function for which it was written (which is sort of what it sounds like you're trying to do); in general, if we have a function that needs to hit the database, we create a SqlCommand and, optionally, a SqlDataReader, set the CommandType to StoredProcedure and add the parameters, then perform the call and consume the result, doing with it whatever the function was programmed to do.

    I don't know that that is the best way to do it, but it works for us.

  • I am looking for a better architecture or pattern that we can use to organize our code ...

    topics that I can google

    Take a look at DAL (Data Access Layer) for database transactions Here is a link to a StackOverflow question posted by someone who is facing a similar situation

    Creating a Class Library in VB.NET

    When you google "How to create DAL", you will see list of how to create a DAL as well as what DAL is. And here is a nice article that shows how DAL fits into an N-Tier achitecture

  • In addition to what Sung Meister said, you should also consider moving the SQL from the VB.NET code into Stored Procedures, and then call the SPs from the VB.NET code (the Data Access Layer). It provides many advantages.

SharePoint 2007 Publishing site with deep menu structure

I am a beginner in SharePoint and I need to create publishing site that will have multilevel menu. Requirement is that levels will not be fixed and that client should be able to add pages and customize menu.
If I am not mistaken pages can be created only in the first level under the site. I don't see something like folders concept. For the navigation purposes I can add heading and it will be shown as another level. If I need more levels I need to create sub sites.

Site
   Page1
   Page2
   Heading
     Page3

Is this correct?

Site
   Page1
   Page2
   Sublevel_1
     Page1_1
     Sublevel_2
        Page2_1
        Sublevel_3
            Page3_1
         ...

Can I do something like this without creating SharePoint sub sites ? If I don't need I will skip writing some custom menu control or write custom SiteMapProvider. I will than need to write UI for managing navigation also.

EDIT:
I have managed to create Folder in Pages list and create (actually move) pages to that folder and even create sub folder but they are not showing on the menu not even in the navigation settings page. I can't approve folder, it is in pending status what ever I try.

I looks like this is not possible by the Andrew Connell: Subfolders are not Supported in the Pages Library in MOSS Publishing Sites

From stackoverflow
  • You can create multiple document libraries in a site and then put the pages in the various libraries. That way you wouldn't need to create sub-sites

    Robert Vuković : As I said I am beginner, can you provide me some link or some more info ? Thanks for answer, I will surely investigate this.
    marcus.greasly : You can't put publishing pages into doc libraries other than the Pages on though, so this technique has limited use..
  • Out of the box, you can modify the navigation for a Publishing site manually.

    I assume that you are after a more automated way to do this. Unfortunately, the way to modify the navigation for a PublishingWeb is through the object model and the PublishingWeb.CurrentNavigationNodes object, which would require a timer job or some other method to update as pages are edited/added/deleted.

    This is non-trivial and you will still need to create a solution/feature package. The other way is to create a custom navigation provider. The issue with both of these options (aside from the actual coding and release) is caching the navigation structure. We have used the standard web cache for the object holding the navigation structure, but using the standard user browsing (i.e. the menu code itself) to kick of a refresh of the navigation is fraught with threading issues.

What is serialization in Java?

I've made a small RSS Reader app using Swing and Eclipse keeps telling me "The serializable class MochaRSSView does not declare a static final serialVersionUID field of type long"

What is serialization and what benefits would it have?

From stackoverflow
  • Serialization is writting the object into a form which is readable and allows the object to be re-created at a different time. So if I created a widget on computer A under one JVM, serialized and saved it and sent it to computer B running a different, the other JVm would be capable of de-serializing it and re-creating it with the same values and structure

  • Serializable is a marker interfaces that tells the JVM is can write out the state of the object to some stream (basically read all the members, and write out their state to a stream, or to disk or something). The default mechanism is a binary format. You can also use it to clone things, or keep state between invocations, send objects across the network etc.

    You can let eclipse generate one for you (basically just a long random but unique ID). that means you can control when you think a class would be compatible with a serialized version, or not.

    (note that all the non transient member variables must be of a serializable class, or you will get an error - as the JVM will recurse through the structure writing out the state of each object down to the level of writing primitives to the ObjectOutputStream).

  • Serialisation is the process of converting an object to a disk-storable format, for re-load at a later time. Check the link for more info!

  • Serialization is a way to take an object (an instance of your class) and set it up for transport--across a network, to disk, etc.

  • Serialization is process of writing an representation of object's instance to a stream (or, to a sequence of bytes). See what Sun says about it: http://java.sun.com/developer/technicalArticles/Programming/serialization/

  • Java Serialisation is a way to persist object structures.

    It is best practice for serialisable class to declare serialVersionUID as a private static final long compile-time constant. This is used to check that object data and class code are claimed to be compatible.

    So why is Eclipse telling you about this? Probably, the class that you are extending (or potentially interface you are implementing) implements java.io.Serializable. That means that all subtypes, including yours are serializable. Almost certainly you don't care. You should be able to clear the warnings by applying @SuppressWarnings("serial") on the class or package (in package-info.java). If you want to forcibly prevent instances of your class being serialised, then add (from memory):

    private static final java.io.ObjectStreamField[] serialPersistentFields = {
        null
    };
    private void writeObject(
        java.io.ObjectOutputStream ou
    ) throws java.io.IOException {
        throw new java.io.NotSerializableException();
    }
    private void readObject(
        java.io.ObjectInputStream in
    ) throws java.io.IOException, java.lang.ClassNotFoundException {
        throw new java.io.NotSerializableException();
    }
    private void readObjectNoData(
    ) throws java.io.ObjectStreamException {
        throw new java.io.NotSerializableException();
    }
    

    It's probably not the best thought out system in the world (although it is much better than many people give it credit for).

  • For more information http://www.google.co.uk/search?q=what+is+java+serialization 275,000 hits.

Triple Screen Setup (3 same size vs large center)

I'm splurging for my personal system that I've wanted a while so in choices between these for programming and other uses.... (home)

  1. 28 in main center monitor (HDMI) with 2 surrounding 19in widescreen
  2. 3 seperate 19 or 21 in monitors, no large one in the center, all equal size.

What would be ideal? 28 in is huge, seems like might be a lot of neck moving and the others wouldn't be used as much....

Interested in what you'd say.

From stackoverflow
  • General Advice

    I doubt you'd be comfortable with flanking monitors on a 28" unless you're sitting far enough away -- my 27" essentially fills most of my field of view. Additionally, you probably would prefer to have all 3 be the same resolution to make it easier to go back and forth (visually and window-dragging).

    It really comes down to what you're doing, though. Some people just can't get enough pixels, whereas others are fine once they've got enough physical real estate to position their common windows all visible together.

    Problems

    I tried to use my Laptop in combination with my primary PC's 19" display (via the fantastic Synergy program), but even the difference between 1280x1024 and 1400x1050 drove me crazy (not to mention screen brightness differences).

    Software

    You'll definitely want some extra software to aid in window management across multiple monitors. Ultramon is pretty highly-recommended for things like separate screensavers and intelligent taskbars. If you're finding yourself with a large monitor and needing to quickly position windows, Winsplit (picked up from Jeff's advice, of course) is awesome.

    Darryl Hein : Visually and I would also say it's easier to drag windows across so you don't have to resize the windows to move them onto a different screen.
    Sheldon : very good point! cheaper to get the same size anyway. :-)
    Andrew Coleson : Of course I didn't take my own advice and just have one 27" monitor. But I love it for DVDs/video games and WinSplit has really helped me stay sane for window management (with multiple smaller monitors, just maximizing everything is pretty good).
  • Resolution is an important factor to consider. For example, a 28" might have a resolution of 1920x1200 while a 20" might be 1680x1050. The 28" is slightly higher, but not by much. There are two implications:

    • You normally sit farther back from a larger monitor. Even though the resolution is higher, you're sitting as close to it as the smaller monitors, so each individual pixel will be relatively bigger. (Or conversely, you're sitting farther from the small monitors than normal, so they will be harder to see).
    • When you look at something on the monitors in comparison - eg, drag a window from the big monitor to a smaller monitor, the window will appear to shrink, since the resolution is changing. Fonts will be bigger/smaller as well.

    I would personally go with identically sized monitors.

  • I have a 30in flanked by 2 24in and I absolutely love it. I have the tops of the screens lined up so speakers lay on their sides underneath.

    I started with a single 24. Then I moved to 2 24's. Now that I have 3 monitors, I'm thinking of adding another 30. Putting the 2 30's on the outside and stacking the 2 24's vertically.

    I just don't think I can have too much real estate.

    Pixels is what is important to me. Whatever screen combination gets you the most pixels, go for that. You won't regret it.

    And get a copy of UltraMon while you're at it. Multiple screens with only one taskbar is annoying and hurts my productivity.

    UPDATE:

    I've added another 30in monitor and changed the layout. Since you asked for a picture, here it is: http://www.twitpic.com/el9p6

    Chris Hynes : +1000. I've got the same setup and I love every second of working on it. Going back to anything smaller is incredibly painful.
    Sheldon : post a pic on your setup? interested in seeing it.
  • I have to vote for not only equal sized monitors, but exactly the same model too. I've worked with both 2 identical Dell 1600x1200 LCDs, and 2 same-rez but differnet physical dimension LCDs.

    When the pixel density is different on multiple displays, things are physically larger/smaller as you move them from one display to the next, and its really annoying. Think about text... 10pt font may be 2mm tall on one display and 2.5mm on another.

  • I'm currently using a 20" - 28w" x 20" LCD setup.

    You are correct - there are drawbacks to using monitors of different sizes, especially if they all have similar native resolutions.

    • Pixel sizing makes windows appear to shrink or grow since a pixel is not the same size on all of the monitors

    • Spanning a window across multiple monitors (especially if your larger monitor is centered) is nearly impossible due to the above points. If you're looking to run a wide Excel spreadsheet or something like that, forget it.

    • The point you alluded to with sitting back further and field of view isn't as big a deal, but in addition to the above points, it adds to the pile.

    If you can help it, go with three identical monitors. Size, make, model. Identical video cards helps too, as it's a pain in the neck to have windows change color when you move them across monitors.

    Sheldon : so you think your setup right now with the larger center is less than ideal, and you'd go to 3 of the 20 ins?
    AvatarKava : Yes - I'd take the tradeoff in actual real estate in exchange for image/color consistency.
    Andrew Coleson : This is definitely something to think of ahead of time -- by the time I was ready to upgrade from a single 19" to dual 19", I could no longer get the same model (or even a similar model) 19". Monitors are definitely something to plan ahead for, since they last so long. Splurge!
  • This is the type of thing that probably depends on how you plan on mounting the monitors and how good your eyesite is.

    When I was thinking about which size/quantity of displays, what I did was simply looked up the specs on line, then I cut pieces of cardboard the size of the monitor(s) I was thinking about, and then I stuck it on my desk where I was planning on putting them. I stuck a piece of paper on the front of the cardboard with what the default windows font would look like at the optimum resolution.

    Sheldon : that's actually pretty funny
  • In general, I find it helpful for all screens to have the same height and vertical resolution. I have tried to pull that off with a huge wide-screen monitor in the middle, and two 4:3 screens flanking, both rotated 90 degrees, but software issues stopped it from working.

    Sheldon : come on! You're the pro guys here... i'm sure you can get it working so when people walk in they think "WOW" you must be a hacker...(( too much Live Free or Die Hard movie recently I guess. :-)))
  • For the record, what I decided and turned out to be beautiful is triple 20 in 4:3's. Namely the HP 2065, which is a s-ips monitor. I also switched to dual 20in in potrait mode at work and find it incredible.

    If you can get the chance, use potrait mode as others have recommended. It makes MUCH more usable space and is pleasing to the eye verus the neck craning widescreens. PERFECT for programmers.

Very simple web page won't display on IE but will on everything else

Hi,

I have just started making web pages and I'm having lots of trouble with this very simple web page. I can't make anything appear on IE but it works fine on everyother browser. I'll take the liberty of putting all the code in my question because it is really short. If anyone could help me it would be great!

The html is:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html
xmlns="http://www.w3.org/1999/xhtml">
<head> <title>Rhaya<title>
        <link rel='stylesheet' media="screen" type="text/css"
href='rhaya.css'/>

</head>
<body>

<div id="masthead"> Rhaya </div>

<div id="content"> Aca va todo el
contenido </div>

<div id="footer"> ©2009 Rhaya | Teresa
Siu | Pía Fabry </div>

</body>
</html>

and the css is:

ul,ol,li {list-style:none}
body {  margin:0 auto; padding:0;font-family: Tahoma;font-size:13px; background: #fff; line-height:15px; color:#000;}
a {color: #000;text-decoration:none}
a:hover {text-decoration:none;color:#000;cursos:default;}

/* Masthead */
#masthead {
    margin:10px 0 10px 0;
    height: 50px;
    font-weight: bold;
    padding:10px;
    border:1px solid #a2ebf4;
    background-color:#e1f2f9;
    background-image: url(img/header.png);
}

/* Content */
#content {
    margin-left:0px;
    margin-bottom:10px;
    padding:10px;
    border:1px solid #000;
    min-width: 300px;
    min-height: 300px;
    font-family: Tahoma;
    font-size:13px;
}

/* Footer */
#footer {
    clear:both;
    padding:10px;
    border:1px solid #a2ebf4;
    background-color:#e1f2f9;
    text-align:center;
}

 #wrapper{
    width:1002px;
    clear:both;
    height:auto;
    margin:0px auto;
    background:#fff;
}

I'm really sorry for asking so blatantly but I really am stumped.

Thanks!

From stackoverflow
  • You have a mistake in your html head:

    <title>Rhaya<title>
    

    should be

    <title>Rhaya</title>
    
    Juan Besa : Wow... that was really simple. Thanks a lot!
  • I suggest adding the following to you css:

    div { position: relative; }
    
    MK_Dev : While this did not end up being THE solution, only person not familiar with IE6 issues could've marked this down. Well done.
  • For future reference: http://validator.w3.org/#validate_by_input Use it for resolving html issues.

    cwap : Indeed - I was just about to post this :P +1 :)
  • Wow, it actually didn't show up at all in IE.

    The reason is that you have the entire page in the title of the page. Change this:

    <title>Rhaya<title>
    

    to:

    <title>Rhaya</title>
    
  • <html
    

    tag isn't closed properly

    title tag isn't closed properly.

    Trent : the html tag spans two lines, but it looks correct
  • I have tried and tested. it is your title problem. enclosed it title /title will definitely work.

Remove non-unique ids rows

From a database backup I have records without unique Ids.

Some records have unique IDs. Some records with duplicated IDs contains different DateCreated values. Some records with duplicated IDs contains the same DateCreated values.

I'm trying to get a MSSql 2005 query will leave only unique ID values with the most recent DateCreated value.

From

ID|    DateCreated  
1 |    1/1/09
2 |    1/2/09
2 |    2/2/09
3 |    1/3/09
3 |    1/3/09

To

ID|    DateCreated  
1 |    1/1/09
2 |    2/2/09
3 |    1/3/09

Help

From stackoverflow
  • DELETE FROM myTable AS t1 
    WHERE EXISTS (
        SELECT 1 FROM myTable AS t2 
        WHERE t1.ID=t2.ID AND t1.DateCreated<t2.DateCreated)
    

    ie, delete any row where there is another row with the same id and a later creation date.

  • create table #t ( id int, date datetime )
    
    insert #t 
    values(1, getdate())
    
    insert #t 
    values(1, getdate()+1)
    
    insert #t 
    values(1, getdate()-1)
    
    insert #t 
    values(2, getdate())
    
    insert #t 
    values(2, getdate()+1)
    
    delete t 
    from #t t
    left join (select id, min(date) as date from #t group by id) as t1 
        on t.id = t1.id and t1.date = t.date
    where t1.date is null
    

Can I create IOC controls using .NET to be placed in web projects?

I currently have a library of UserControls which I use in a lot of our web applications. I would like to update these controls so that I can use IOC to help seperate the logic.

So I would have something similar to the following on the web page itself:

<prefix:ControlName ID="myControl" runat="server" property="value1" />

And the control would have a constructor similar to:

public ControlName (IControlLogic logic)

Then ideally the IOC container would handle the injection. Can this be done? If so what libraries offer this? If you have any links that you know of that discuss this they would be great thanks.

Thanks in advance

From stackoverflow
  • Yes you can, I would suggest you look at spring.net

    http://www.springframework.net/doc-latest/reference/html/springair.html

    I am not sure if you want to keep the usercontrol idea that you are suggesting.

    Personally I use spring.net and nHibernate together (although avoiding the Hibernate Templates currently provided) which is working fantastically with .net MVC beta stuff.

    Using Spring.net to handle nHibernate slightly reduces the config entries, and MVC doesn't use the context xmls you would would need (springair is a good example).

    best of luck

    John_ : Unfortunately we have a quite a few usercontrols in this library so it can't just be ported across to MVC quickly. And injecting into a user control with a constructor doesn't work but I have worked out I inject into fields the relevant information / behaviour.
  • Unfortunatley ASP.NET does not seem to support any easy factory creation pattern for controls. However, in 3.5 you are given very fine grained control over the actual code that the ASP.NET runtime generates for your .aspx file.

    Simply apply [ControlBuilder(...)] attributes to all the controls that you want constructed by your container. Subclass ControlBuilder and override ProcessGeneratedCode to replace the constructor with a call to your container.

    Here's a simple example:

    public class ServiceProviderBuilder : ControlBuilder
    {
        public override void ProcessGeneratedCode(System.CodeDom.CodeCompileUnit codeCompileUnit, System.CodeDom.CodeTypeDeclaration baseType, System.CodeDom.CodeTypeDeclaration derivedType, System.CodeDom.CodeMemberMethod buildMethod, System.CodeDom.CodeMemberMethod dataBindingMethod)
        {
            // search for the constructor
            foreach (CodeStatement s in buildMethod.Statements)
            {
                var assign = s as CodeAssignStatement;
                if (null != assign)
                {
                    var constructor = assign.Right as CodeObjectCreateExpression;
                    if (null != constructor)
                    {
                        // replace with custom object creation logic
                        assign.Right = new CodeSnippetExpression("("+ ControlType.FullName + ")MyContainer.Resolve<" + ControlType.BaseType.FullName + ">()");
                        break;
                    }
                }
            }
            base.ProcessGeneratedCode(codeCompileUnit, baseType, derivedType, buildMethod, dataBindingMethod);
        }
    }    
    
    [ControlBuilder(typeof(ServiceProviderBuilder))]
    public partial class WebUserControl1 : System.Web.UI.UserControl
    {
        public WebUserControl1()
        {
    
        }
    
        protected void Page_Load(object sender, EventArgs e)
        {
    
        }
    }
    
  • Unfortunately there is no one answer to this question, many IOC containers contain some implementation of injecting control properties but there is no way (currently) of actually creating a control without a parameterless constructor.

C# model view controller

So I am creating a C#/Winforms application in a model-view-controller pattern. My view-controller needs to instantiate multiple groups of objects. The object groups are elements of the model and elements of the view. So for example a textbox and the model to go behind that text box.

I'm wondering if the best way to do this is to put everything in some sort of collection and tie them together with a key?

From stackoverflow
  • Have you considered using WPF instead of WinForms? It has a nicer MVC-like model and built-in databinding that is much more powerful. It would probably solve your problem and help you build with more modern technology besides.

  • In the WinForm MVC apps I've built, I typically don't allow the controller to instantiate anything (I try and keep the "new" keyword out of my controllers).

    If I need an object I ask a service for it, and internally that service is going to fetch that object from a data source (repository or the like), or in the case of a new object it will likely utilize some kind of factory to get me a new object (with any necessary pre-filled properties already set to default values, rules run, etc.).

    The way I like to think about this sort of problem is this: how would I make this work (and make it reusable) if I didn't have a GUI for a view, but instead had a command-line input for my view? The logic to create/add/delete/update the model should be somewhere in your domain, not in the controller. Then the controller just becomes the mediator between the model and the view. The view becomes an I/O mechanism that is just a prettier version of a command-line interface.

    Hope that makes sense.

  • Perhaps you should design your model to match what the view needs? Then there would be only one model for the controller to pass on to the view.

django / file uploads permissions

Hi there,

I wrote a django app, but i have a little problem with the file permissions of the uploads files from a web form.

Baically i can upload a .mp3 file but it always keep chmod 600.

Th container folder has chmod 775, and the umask is set to 022.

I'm in a shared hosting service.

Thanks if any one can give a clue.

From stackoverflow
  • Try this in your settings.py:

    FILE_UPLOAD_PERMISSIONS = 0644
    
    Van Gale : Glad to help :)

Rails Request Initialization

We all hear a lot about scaling issues in Rails.

I was just curious what the actual costs in handling a HTTP request is in the Rails framework. Meaning, what has to happen for each and every request which comes in? Is there class parsing? Configuration? Database Connection establishment?

From stackoverflow
  • That actually depends a lot on which web server you're using, and which configuration you're using, not to mention the application design itself. Configuration and design issues involved include:

    • Whether you're using fastcgi, old-school cgi, or some other request handling mechanism (affects whether you're going to have to rerun all of the app initialization code per request or not)
    • Whether you're using memcache (or an alternate caching strategy) or not (affects cost of database requests)
    • Whether you're using additional load balancing techniques or not
    • Which session persistence strategy you're using (if needed)
    • Whether you're using "development" mode or not, which causes code files to be reloaded whenever they're changed (as I recall; maybe it's just per-request) or not

    Like most web app frameworks, there are solutions for connection pooling, caching, and process management. There are a whole bunch of ways to manage database access; the usual, default ones are not necessarily the highest performance, but it's not rocket science to adjust that strategy.

    Someone who has dug into the internals more deeply can probably speak in more excruciating detail, but most apps use either FastCGI on Apache or an alternate more rails-friendly web server, which means that you only have app setup once per process.

  • Until the release of Phusion Passenger (aka mod_rails) the "standard" for deployment was not FastCGI but using a cluster of Mongrel servers fronted by Apache and mod_proxy (or Nginx etc).

    The main issue behind the "Rails doesn't scale" is the fact that there are some quite complicated threading issues which has meant tiwht the current version of Ruby and the available serving mechanisms, Rails has not been threadsafe. This has meant that multiple containers have been required to run a Rails app to support high-levels of concurrent requests. Passenger makes some of this moot, as it handles all of this internally, and can also be run on a custom build of Ruby (Ruby Enterprise Edition) that changes the way memory is handled.

    On top of this, the upcoming versions of both Ruby and Rails are directly addressing the threading issue and should close this argument once and for all.

    As far as I am concerned the whole claim is pretty bogus. "Scale" is an architectural concern.

  • Here's a good high level overview of the lifecycle of a Rails request. After going through this, you can choose specific sections to profile and optimize.

Getting single records back from joined tables that may produce multiple records

I've got a student table and an enrollment table; a student could have multiple enrollment records that can be active or inactive.

I want to get a select that has a single student record and an indicator as to whether that student has active enrollments.

I thought about doing this in an inline UDF that uses the student ID in a join to the enrollment table, but I wonder if there's a better way to do it in a single select statement.

The UDF call might look something like:

Select Student_Name,Student_Email,isEnrolled(Student_ID) from Student

What might the alternative - with one SQL statement - look like?

From stackoverflow
  • Try someting like this:

    SELECT Student_Name, Student_Email, CAST((SELECT TOP 1 1 FROM Enrollments e WHERE e.student_id=s.student_id) as bit) as enrolled FROM Student s
    

    I think you can also use the exists statement in the select but not positive

  • select  Student_Name,
            Student_Email,
            (select count(*) 
             from Enrollment e 
             where e.student_id = s.student_id
            ) Number_Of_Enrollments 
     from Student e
    

    will get the number of enrollments, which should help.

    banjollity : If you had 1000 students this statement is like running 1001 queries since it queries each student's enrollment count separately.
    Renze de Waal : No, it's not that bad. The database can optimise, especially if student_id is the first part of an index on enrollment (which I think it will be). The subquery will only need to perform an index range scan on the index of enrollment (the table itself is not needed).
  • Why not join to a secondary select? Unlike other solutions this isn't firing a subquery for every row returned, but gathers the enrollment data for everyone all at once. The syntax may not be quite correct, but you should get the idea.

    SELECT
        s.student_name,
        s.student_email,
        IsNull( e.enrollment_count, 0 )
    FROM
        Students s
    LEFT OUTER JOIN (
            SELECT
                student_id,
                count(*) as enrollment_count
            FROM
                enrollments
            WHERE
                active = 1
            GROUP BY
                student_id
        ) e
    ON s.student_id = e.student_id
    

    The select from enrollments could also be redone as a function which returns a table for you to join on.

    CREATE FUNCTION getAllEnrollmentsGroupedByStudent()
    RETURNS @enrollments TABLE
    (
        student_id       int,
        enrollment_count int
    ) AS BEGIN
        INSERT INTO
            @enrollments
        (
            student_id,
            enrollment_count
        ) SELECT
            student_id,
            count(*) as enrollment_count
        FROM
            enrollments
        WHERE
            active = 1
        GROUP BY
            student_id
    
        RETURN
    END
    
    
    SELECT
        s.student_name,
        s.student_email,
        e.enrollment_count
    FROM
        Students s
    JOIN 
        dbo.getAllEnrollmentsGroupedByStudent() e
    ON  s.student_id = e.student_id
    

    Edit:
    Renze de Waal corrected my bad SQL!

    Renze de Waal : Note that if a student does not have enrollments, the join would leave those students out. A left join would help, but then enrollment_count can be null.
    banjollity : Good spot. I've made a few edits.
  • try to avoid using udfs or subqueries, they are performance killers. banjolity seems to havea good solution otherwise because it uses a derivd table instead of a UDF or subselect.

  •   select students.name, 
    decode(count(1), 0, "no enrollments", "has enrollments")
         from students, enrollments 
         where 
           students.id = enrollments.sutdent_id and 
           enrollments.is_active = 1 group by students.name
    

    Of course, replace the decode with a function your database uses (or, a case statement).

Python port binding

Hey everyone,

I've recently been learning python and I just started playing with networking using python's socket library. Everything has been going well until recently when my script terminated without closing the connection. The next time I ran the script, I got:

File "./alert_server.py", line 9, in <module>
  s.bind((HOST, PORT))
File "<string>", line 1, in bind
socket.error: (98, 'Address already in use')

So it seems that something is still binded to the port, even though the python script isn't running (and I've verified this using $px aux. What's weird is that after a minute or so, I can run the script again on the same port and it will be fine. Is there any way to prevent/unbind a port for when this happens in the future?

From stackoverflow
  • What you want to do is just before the bind, do:

    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    

    The reason you are seeing the behaviour you are is that the OS is reserving that particular port for some time after the last connection terminated. This is so that it can properly discard any stray further packets that might come in after the application has terminated.

    By setting the SO_REUSEADDR socket option, you are telling the OS that you know what you're doing and you still want to bind to the same port.

    S.Lott : Also, you might want to call shutdown() and close() on the socket.

Biztalk Send Port Group and Filtering

So the model I need for my solution is as follows:

I need to poll the database and based on a result, create a request to the database for more data, get the response and pass it to a group of ports, for which based on a promoted property, only one of the ports will act.

It looks like this:

However, if you assign "Temp Out" to a send port group, the message is sent to all the ports in the group, irregardless of the filters set on each port. From my understanding, this is expected behavior (read here).

So I explored other options such as using Content Based Routing (CBR sample) like in the SDK. You can view this here.

I tried this and completely removed the orchestration (its really not needed). However, there are major routing/subscription errors, and upon further research, it appears that you can't do this if you have solicit-response ports. Some articles on that here. I pretty much have the same issue this user does.

In the end it doesn't matter to me whether I use an orchestration or not. However, I need a solution in which I can pass the message to multiple send ports, and I can have only one actually use the message and send. This is needed so that I can edit and add ports easily without having to modify anything else or hard code decisions into the orchestration.

From stackoverflow
  • You can use Direct Binding on the orchestration's send port to inject the message back into the message box db. Using multiple port groups, each port group can then directly subscribe to the desired message type and filter on promoted properties.

    achinda99 : In a way I found a solution. I removed the orchestration, promoted properties and on the second and third port, put filters where I defined BTS.SPName (which I thought was stored procedure name but now understand is Send Port name). The routing issues were because I hadn't fully subscribed them.
  • I found that the CBR example model does indeed work. The problem with routing were the subscriptions. If I was to subscribe a send port to a solicit-response port, I had to set the BTS.SPName (Send Port Name) filter instead of the BTS.ReceivePort filter. By doing this, the message was correctly filter through. You're answer would have worked too, but it requires using an orchestration which I was trying to avoid.

C# debugging across dlls

I have a project which has a calling structure similar to this:

  • main project/application
  • my library code
  • someone else's library code
  • my library code

Everything's written in C#, and I have access to 'someone else's library code'. Their code is not included in my project, because it's open source and not my code. I can make debug versions of all the libraries, and I've done so.

That 'someone else's library code (SELC, I guess?) is throwing an exception in a heisen-bug kind of way, and I'm trying to track it down and maybe submit a bugfix to the project maintainer. Problem is, my debugging stack is stopping at my library code, and lists the SELC as 'external' and I can't debug into it. I've copied the pdb files as well as the debug version of the library into the debug directory of my application, and still no luck; I can't seem to debug into their code, and I can't step into it at all.

Once upon a time, back in vs6 days, I could do this-- have two different projects open at the same time in two different environments, and have the debugger trace across dll boundaries from one project into another. I'd assume that functionality remains, because it's just so dang useful.

Any suggestions?

I've looked for this answer but not found it, so if this is a dupe, just let me know where to look.

From stackoverflow
  • Do you have "Just My Code" turned on in Visual Studio's debugging options?

    mmr : It doesn't seem to matter. I still can't step into their code.
    mmr : Ah, ok, I had to do it for both projects. This got it. Thanks!
  • If you have the sources (as i read from you), you can make an project with their source code, and then add the project to your solution.
    In visual studio the project in .csproj file , and solutions in .sln file.

    mmr : Yeah, as I said, I don't want to do that, because it's not my source. I want to keep the sources distinct from one another. I understand that I might not be able to do so, but still-- in vc6 I could do this kind of thing.

Javascript - onload, onclick events

I have a method that is instantiated on page load. The method fires two events, window.onload and image.onclick. The problem is only one of the event works at any given time (ie: if i comment image.onclick method, window.onload method works). How do i get both to work?

This works fine in Firefox (mozilla) but not in IE

example

test.method = function()
{
    window.onload = this.doSomeWork;

    for (i = 0; i < images.length; i++) {
        var image = images[i];
        image.onclick = this.imageClickEvent;

    }
}
From stackoverflow
  • Look at the code on a page with Firefox 3. Then open the Firefox Error Console (Ctrl Shift J) to see which line is breaking. Then update your question with the new info.

  • The problem us that you can only have one onload event.

    I recommend that yuu should try the addEvent method found here:

    http://ejohn.org/projects/flexible-javascript-events/

    DK : There is only one onload event. The other is the onclick event. Do you mean to say that there can be either onload or an onclick event?
    tan : if test.method() is executed onload, there are two methods/functions added to onload, only the last will be added.
  • There's not really enough information in the question to figure out what's going wrong, but things to look at include:

    • is the code in the doSomeWork() or imageClickEvent() expecting to receive a ‘this’ that points to anything in particular? Because it won't, when you peel a method off its owner object to assign to an event handler.

    • is there another method writing to window.onload, or image.onclick, that you might be overriding?

  • Perhaps you should be adding an event listener here, and not trying to capture window.onload?

  • after you fire the test.method on page load, you overwrite your window.onload with a new value: this.dosomework, so within the time frame of the body load, you call the first function, then immidiately overwrite, then second function takes over, and carries out... did you try to push the window.onload statement way to the bottom of the test.method? my guess if the function block is too long, the second window.onload is never gonna be carried out, because the window has already finished loading, its milliseconds, but thats all it takes

    apparently in firefox the function is carried out before it gets overwritten, or maybe appeneded to the current onload, not sure about technicalities. again, try to push onload to the bottom and see what happens

    you should not really call an onload function within any other function that is called after body load, because no matter how careful you are you cannot depend on the fact that the loading time frame is long enough to contain both events, you should append to window.onload before the body tag is called (or finished) to make sure the event is caught.

XAML tag list reference

As the question suggests I'm simply looking for a XAML tag list reference. I've banged the obvious queries in Google/SO but not found what I am looking for yet. Any useful links welcome.

Cheers, Chris.

From stackoverflow
  • With WPF the XAML elements map to the classes like StackPanel. MSDN seems to give XAML examples for many of the controls.

  • There are XAML-specific conventions about representing things like complex properties and bindings. However, there is no definitive list of XAML tags. XAML tags are actually mapped to WPF objects. For example, <Button> is just a XAML representation of the System.Windows.Controls.Button class and the attributes allowed on the <Button> tag are the public properties of the Button class.

  • There isn't such a thing as a xaml tag list.

    XAML is just a declarative way to instantiate .Net classes. Class names are elements in XAML and properties on the class are attributes or attribute elements using dot notation.

    Tags in XAML only mirror the types in one or more assemblies that are bound to a particular XAML namespace.

    There are however a specific set of elements that are specific to XAML in itself and are not related to any particular .Net assembly, those are usually in the x: namespace, more info here: XAML Namespace (x:).

  • There's a WPF Binding Cheatsheet and another XAML for WPF Cheatsheet which might help, but really the "tags" in XAML are just the properties of the classes.

  • There is no such thing as the XAML tag list since XAML is an open system.

    There are, however, standard vocabularies. Rob Relyea's Blog is a good place to keep track of the standardization around these vocabluaries. For example, this is an entry for the Silverlight XAML vocabulary.

Detect Changes webform controls asp.net

Hi all,

I have a webform with around 20 textboxes/drop down list controls and i would like a clean and simple way of checking to see if the form fields have changed or not. Does anyone know of a clean way to do this?

Thanks in advance!

From stackoverflow
  • onkeypress / onkeydown / onkeyup methods in javascript. Are able to monitor keystrokes aimed at the inputs.

    If there was a keystroke on the input there will probably be a change.

    example

  • The easiest way is to loop through the controls collection and then check the TextChanged property.

    Note that controls in the collection may have their own controls, so you'll have to do a recursive check.

nhibernate proxy generator

I am attempting to get nhibernate working in medium-trust. What I found said that I needed to use a proxy generator. I pulled the one from nhibernate's site. When I attempt to use it, I recieve an error that it could not load the assembly 'DynamicProxyGenAssembly2'. Is there something I am missing or is there one that works somewhere. I would prefer not to use the generator, but there seems to be no alternative with nhibernate.

From stackoverflow
  • From what I gather the issue with medium trust is the use of reflection being nerfed some what (though I could be completely off here).

    It also seems that your approach of physically pre-building the proxy objects seems to be the suggested one and this link may help.

    To be honest I had a similar issue with shared hosting and decided to opt for using a a hosting provider that offered virtual server. This obviously removes the medium trust issue as it's like having a cheap and nasty dedicated server at your disposal.

    I know that this answer may not have been the best, but I do feel your pain and wanted to chime up a little. Also, its worth mentioning that the best place to get NHibernate related questions answered is their forums (http://forum.hibernate.org).

  • Thad I know this question is old, but I just wanted to tell you and others with this issue that it is really pretty easy to run NHibernate in a medium trust environment once you know what to do. All you have to do is to do the following:

    1. Rebuild Castle from source and get the dlls from that
    2. Rebuild NHibernate from source using the dlls from the prior step and get the dlls
    3. Add the dlls to your project.

    You need to pay attention to the versions of Castle and NHibernate to make sure that they will work together, but you don't have to disable lazy loading or do anything else. Here is a blog post about it that outlines how you can easily set up your project in a medium trust environment: How To Run NHibernate In A Medium Trust Environment

Why are executable files not included in 'Extract All' on one machine, but not another?

We're providing a zip file of our application for testing and the same zip file on two separate machines is extracted differently. One will extract all files, the other will extract all but the executables (.exe and .msi specifically).

We're going to have to tell our customers something other than 'use WinZip' (or 7zip, or whatever)

When I look at what is happening using ProcessMonitor, I see that the explorer.exe process is creating each file, then deleting it. WTF?

The two systems are Windows Server 2003 with SP2. Surely there is a setting that we can point to that explains why this happens.

UPDATE 1** I enabled/disabled virus scanning with no noticeable effect.

From stackoverflow
  • My guess is it's a virus scanner or other "anti-malware" bit of kit - possibly something to do with group policy?

  • IIRC, ProcessMonitor has the option to show the stack for the delete event. You would need Windows symbols (or a configured symbol server), but the function names should give you an hint why the executables are deleted.

  • There was a security patch/setting that one machine had that the other didn't. The zip file needed to be 'unlocked' by looking at the properties.

    Until then, no executables/dlls would be extracted from the file.

Getting the current GMT world time

How can i get the current time? (in JavaScript)

Not the time of your computer like:

now = new Date;
now_string = addZero(now.getHours()) + ":" + addZero(now.getMinutes()) + ":" + addZero(now.getSeconds());

But the real accurate world time?

Do i need to connect to to a server (most likely yes, which one? and how can i retrieve time from it?)

All the searches I do from google return the (new Date).getHours().

Edit:

I want to avoid showing an incorrect time if the user has a wrong time in his computer.

From stackoverflow
  • You can use the toGMTString method.

    var d = new Date();
    alert(d.toGMTString()); // Will give you: Wed, 28 Jan 2009 22:05:04 GMT
    

    You can also get the current time offset:

    var gmtHours = d.getTimezoneOffset()/60;
    alert("The local time zone is: GMT " + gmtHours);
    
    fmsf : But that still gives local computer time
    CMS : Exactly, because JavaScript code is executed on the client browser. You will need to get the date from the server side, you can do it through AJAX, can you give some info of what are you using on the server side?
    fmsf : I'm using nothing! I have access to php though and mysql on the server. although last time i've coded it was 4 years ago and i remember nothing :(
  • You could use getTimezoneOffset to get the offset between the local date and the GMT one, and then do the math. But this will only be as accurate as the user's clock.

    If you want an accurate time, you should connect to a NTP server. Because of the Same Origin Policy, you can't make a request with JS to another server then yours. I'd suggest you to create a server-side script that connects to the NTP server (in PHP, or whatever language you want) and return the accurate date. Then, use an AJAX request to read this time.

  • First, to get the accurate GMT time you need a source that you trust. This means some server somewhere. Javascript can generally only make HTTP calls, and only to the server hosting the page in question (same origin policy). Thus that server has to be your source for GMT time.

    I would configure your webserver to use NTP to synchronize its clock with GMT, and have the webserver tell the script what time it is, by writing a variable to the page. Or else make and XmlHttpRequest back to the server when you need to know the time. The downside is that this will be inaccurate due to the latency involved: the server determines the time, writes it to the response, the response travels over the network, and the javascript executes whenever the client's cpu gives it a timeslice, etc. On a slow link you can expect seconds of delay if the page is big. You might be able to save some time by determining how far off from GMT the user's clock is, and just adjusting all the time calculations by that offset. Of course if the user's clock is slow or fast (not just late or early) or if the user changes the time on their PC then your offset is blown.

    Also keep in mind that the client can change the data so don't trust any timestamps they send you.

    Edit: JimmyP's answer is very simple and easy to use: use Javascript to add a <script> element which calls a url such as http://json-time.appspot.com/time.json?tz=GMT. This is easier than doing this yourself because the json-time.appspot.com server works as a source of GMT time, and provides this data in a way that lets you work around the same-origin policy. I would recommend that for simple sites. However it has one major drawback: the json-time.appspot.com site can execute arbitrary code on your user's pages. This means that if the operators of that site want to profile your users, or hijack their data, they can do that trivially. Even if you trust the operators you need to also trust that they have not been hacked or compromised. For a business site or any site with high reliability concerns I'd recommend hosting the time solution yourself.

    Edit 2: JimmyP's answer has a comment which suggests that the json-time app has some limitations in terms of the number of requests it can support. This means if you need reliability you should host the time server yourself. However, it should be easy enough to add a page on your server which responds with the same format of data. Basically your server takes a query such as

    http://json-time.appspot.com/time.json?tz=America/Chicago&callback=foo
    

    and returns a string such as

    foo({
     "tz": "America\/Chicago", 
     "hour": 15, 
     "datetime": "Thu, 09 Apr 2009 15:07:01 -0500", 
     "second": 1, 
     "error": false, 
     "minute": 7
    })
    

    Note the foo() which wraps the JSON object; this corresponds to the callback=foo in the query. This means when the script is loaded into the page it will call your foo function, which can do whatever it wants with the time. Server-side programming for this example is a separate question.

    fmsf : usefull teory (not joking, nor hinorising) :) but how do i do that? me == noob in javascript
    fmsf : an example or tutorial link will be great, and with that answer you'll get correct answer for this question :)
    Mr. Shiny and New : @fmsf: since you are a noob, you're probably better off using JimmyP's answer. My answer involves programming on the server and giving a code sample is not trivial.
  • You can use JSON[P] and access a time API:

    (The code below should work perfectly, just tested it...)

    function getTime(zone, success) {
        var url = 'http://json-time.appspot.com/time.json?tz=' + zone,
            ud = 'json' + (+new Date());
        window[ud]= function(o){
            success && success(new Date(o.datetime));
        };
        document.getElementsByTagName('head')[0].appendChild((function(){
            var s = document.createElement('script');
            s.type = 'text/javascript';
            s.src = url + '&callback=' + ud;
            return s;
        })());
    }
    
    getTime('GMT', function(time){
        // This is where you do whatever you want with the time:
        alert(time);
    });
    
    Crescent Fresh : Nice. Self contained. Terse.
    Mr. Shiny and New : Wow, that's far simpler than my answer. But the downside is that you have to trust this site fully, or else they are running arbitrary code on your pages.
    J-P : You're right Mr Shiny... I think this API is quite trustworthy, it's hosted by Google and was created by Simon Willison (the guy who co-created Django) :)
    Jason S : +2 if it were possible.
    benc : JasonS, I plussed again for you :)
    Matt Miller : The API works okay, but tonight it's down because it has exceed Google's quota for the day. The quota for free AppEngine accounts is only 1.3 million requests daily.
  • Like Mr. Shiny and New said, you need a server somewhere with correct time. It can be the server where you site are or some other server that sends the correct time in a format that you can read.

    If you want to use the date several times on your page, one or more seconds apart, you probably don't want to get the time from the server every time, but instead cache the difference and use the clients clock. If that is the case, here is one of many solutions:

    var MyDate = new function() {
        this.offset = 0;
        this.calibrate = function (UTC_msec) {
            //Ignore if not a finite number
            if (!isFinite(UTC_msec)) return;
    
            // Calculate the difference between client and provided time
            this.offset = UTC_msec - new Date().valueOf();
    
            //If the difference is less than 60 sec, use the clients clock as is.
            if (Math.abs(this.offset) < 60000) this.offset = 0;
        }
        this.now = function () {
            var time = new Date();
            time.setTime(this.offset + time.getTime());
            return time;
        }
    }();
    

    Include it on your page and let your server side script produce a row like:

    MyDate.calibrate(1233189138181);
    

    where the number is the current time in milliseconds since 1 Jan 1970. You can also use your favorite framework for AJAX and have it call the function above. Or you can use the solution JimmyP suggested. I have rewritten JimmyPs solution to be included in my solution. Just copy and paste the following inside the function above:

        this.calibrate_json = function (data) {
            if (typeof data === "object") {
                this.calibrate (new Date(data.datetime).valueOf() );
            } else {
                var script = document.createElement("script");
                script.type="text/javascript";
                script.src=(data||"http://json-time.appspot.com/time.json?tz=UTC") +
                    "&callback=MyDate.calibrate_json";
                document.getElementsByTagName('head')[0].appendChild(script);
            }
        }
        this.calibrate_json(); //request calibration with json
    

    Notice that if you change the name of the function from MyDate you have to update the callback in *this.calibrate_json* on the line script.src.

    Explanation:

    Mydate.offset is the current offset between the server time and the clients clock in milliseconds.

    Mydate.calibrate( x ); is a function that sets a new offset. It expects the input to be the current time in milliseconds since 1 Jan 1970. If the difference between the server and client clock is less than 60 seconds, the clients clock will be used.

    Mydate.now() is a function that returns a date object that has the current calibrated time.

    *Mydate.calibrate_json( data )* is a function that either takes an url to a resource that gives back a datetime reply, or an object with the current time (used as a callback). If nothing is supplied, it will use a default url to get the time. The url must have a question mark "?" in it.

    Simple example of how to update an element with the current time every second:

    setInterval(
        function () {
            var element = document.getElementById("time");
            if (!element) return;
            function lz(v) {
                return v < 10 ? "0" + v : v;
            }
            var time = MyDate.now();
            element.innerHTML = time.getFullYear() + "-" +
                lz(time.getMonth() + 1) + "-" +
                lz(time.getDate()) + " " +
                lz(time.getHours()) + ":" +
                lz(time.getMinutes()) + ":" +
                lz(time.getSeconds())
            ;
    },1000);
    
  • Why don't you send the time with every page? For example somewhere in the html:

    <span id="time" style="display:none;">
        2009-03-03T23:32:12
    </span>
    

    Then you could run a Javascript while the site loads and interpret the date. This would reduce the amount of work the network has to do. You can store the corresponding local time and calculate the offset every time you need it.

  • We've used an API from EarthTools with much success:

    EarthTools

    The service returns XML with information such as the current GMT & timezone offsets (when supplying a latitude & longitude). We used a WebClient in conjunction with an XMLDocument in the VB backend of our ASP.NET page to read & interpret the XML.