Monday, February 21, 2011

An architecture question

Hi guys,

I got a general architecture question, hope guys can help me. So some basic background first. I have a midsize customer base using my flagship product, which is mainly a crm accounting software. Its a windows based product and they host the data on their servers (usually at their offices).

I have a clickonce application that uploads a subset of their database to our servers. We store all our customer's data in one database. We give each customer and their subsequent records a datasetid.

The clickonce works using a manifest, which essentially figures out which records to add, delete or update on our servers. The transfer of data between the customer's server and our server is through a web service. After the inital upload (which is data intensive), the subsequent uploads only push the difference up (which is much smaller). A majority of our clients tend to upload once day.

We also have a web application that accesses this subset of data to display information to a variety of users, who are our customer's clients. We have about 3000 active users for this web application, which hit the website about once a week.

The issue lie in this, the queries to our database from the website, as well as from the upload service are timing out. Everytime we do a new release, we expand the subset of data (ie add a new table or 2). So immediately after the release we get bombarded with uploads. Hence our site is down alot recently. I think too much traffic is happening to the one database, in terms of data being uploaded and data retrieval for the website.

We would like to keep the subset of data as synchronised with flagship products data as much as possible.

Things we have aleady got include, Scheduler for the clickonce to upload data early in the morning. We are currently implementing a queueing system so only x amount of people can upload at once.

What are some avenues I can explore for the long term and the short term?

Cheer.

From stackoverflow
  • One thing I would make sure you look at before you start digging too deep into the optimization process is identifying your bottlenecks. Is it client-side processing, client bandwidth, server bandwidth, or server-side processing. Assuming you're not shipping massive amounts of data around, it's likely server-side processing, but making assumptions like that can get you into trouble on these kinds of things.

  • If the uploads don't have to be instantly available (can wait a little bit before you select the data) I'd strongly consider putting a queue in front of that using MSMQ / WCF. That can help you throttle your intake of that data.

    Next it's important to analyze your database structure. There isn't too much information about your schema here, or number of rows, etc... but there are several things I can recommend if you have a lot of incoming data.

    • Make sure that you aren't using a technology that isn't up to the task (like Access or Sqlite).
    • Consider optimizing a database for Inserts, then replicate that database to other databases you might use for selects.
    • If you have a tremendous amount of data, consider setting up a cluster
    • Consider switching to a cloud based data service like Amazon SimpleDB or Azure Data Services
  • Where's your bottlneck? Is it a bandwidth issue with your data connection, an issue on your database server, or on your web server, etc?

    What database software are you running? If it's access or something like that it's got to go, in favor or something slightly more enterprise like sql server or similar.

    Are all the clients trying to upload at the same time? Can you stager them somehow, maybe by having them upload at a random time throughout the day, or a randome time during a specific window.

    Would clustering your web server or db server help?

    Can you implement some sort of queue through msmq as already mentioned, or use biztalk or a similar product. That way the client can submit their results, and forget about it, then the queue software handles the actual delivery.

Recaptcha image not showing on IIS

Hello Guys,

I deployed my MVC application in our IIS server. When I go to registration page the recaptcha image is not showing. However, When I run it on Visual Studio its working properly. I'm using IIS 6.

Do you guys have any idea regarding this issue?

Best regards,

From stackoverflow
  • Just a guess, but have you set up your public/private keys correctly?

    From the recaptcha API docs

    In order to use reCAPTCHA, you need a public/private API key pair. This key pair helps to prevent an attack where somebody hosts a reCAPTCHA on their website, collects answers from their visitors and submits the answers to your site.

    Your reCAPTCHA token is valid only at the domain you sign up for and any subdomains (due to the potential attack mentioned above).

    As for why it works in development, but not off your server:

    If one of your servers is "localhost" or "127.0.0.1", reCAPTCHA will not enforce the same-domain rule. Just use the same key as for the production server.

    ... so even if you haven't set up your keys properly, the reCAPTCHA will still work if the page is being served from your local machine. Once you deploy though, and incorrect or missing key will prevent the reCAPTCHA from loading.

    samer : Thanks for the reply. Though I haven't tried it yet but definitely your right.

Using UTM with geodjango

I'm looking into using the UTM coordinate system with geodjango. And I can't figure out how to get the data in properly.

I've been browsing the documentation and it seems that the "GEOSGeometry(geo_input, srid=None)" or "OGRGeometry" could be used with an EWKT, but I can't figure out how to format the data.

It looks like the UTM SRID is: 2029

From the wikipedia article the format is written like this:

[UTMZone][N or S] [easting] [northing]

17N 630084 4833438

So I tried the following with no luck:

>>> from django.contrib.gis.geos import *
>>> pnt = GEOSGeometry('SRID=2029;POINT(17N 630084 4833438)')
GEOS_ERROR: ParseException: Expected number but encountered word: '17N'
>>>
>>> from django.contrib.gis.gdal import OGRGeometry
>>> pnt = OGRGeometry('SRID=2029;POINT(17N 630084 4833438)')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python26\lib\site-packages\django\contrib\gis\gdal\geometries.py", line 106, in __init__
    ogr_t = OGRGeomType(geom_input)
  File "C:\Python26\lib\site-packages\django\contrib\gis\gdal\geomtype.py", line 31, in __init__
    raise OGRException('Invalid OGR String Type "%s"' % type_input)
django.contrib.gis.gdal.error.OGRException: Invalid OGR String Type "srid=2029;point(17n 630084 4833438)"

Are there any example available to show how this is done?

May be I should just do any necessary calulations in UTM and convert to decimal degrees?
In this case does GEOS or other tools in geodjango provide convertion utitilites?

From stackoverflow
  • The UTM zone (17N) is already specified by the spatial reference system -- SRID 2029, so you don't need to include it in the WKT you pass to the GEOSGeometry constructor.

    >>> from django.contrib.gis.geos import *
    >>> pnt = GEOSGeometry('SRID=2029;POINT(630084 4833438)')
    >>> (pnt.x, pnt.y)
    (630084.0, 4833438.0)
    >>> pnt.srid
    2029
    

    Then, for example:

    >>> pnt.transform(4326)   # Transform to WGS84
    >>> (pnt.x, pnt.y)
    (-79.387137066054038, 43.644504290860461)
    >>> pnt.srid
    4326
    
    mloskot : I would add that geometry given in form of Well-Known-Text, either OGC WKT or PostGIS/GEOS-specific format of Extended WKT, components given between parenthesis () after geometry tag, should only specify coordinates: X Y, optionally Z and M dimensions. No other exotic elements are allowed, so 17N is an invalid token. In case of EWKT, spatial reference system can be given using dedicated specifier SRID.

What is the best way to handle returning multiple formats in ASP.NET MVC

Rails has a nice idiom that makes it easy for you to have a single action method return properly formated data (json, xml, just the data) based on the format specified by the client (or else deduced from the request. It looks something like this ...

respond_to do |format|
  format.html #edit.html.erb
  format.json {render :text=> <your json here>), :layout=> false}
  format.xml ...

end

What is the preferred way to do this in ASP.NET MVC? Ideally, I'd like the framework to work in the same way as Rails (e.g. be able to return the ViewData properly formatted for the format specified by the client or else deduced from the request itself).

Rails also allows you to create views that are specific to each type giving you the opportunity to essentially return the same data to all views and letting them handle formatting the data correctly (so you have a view that builds xml, another that builds json and yet another that builds html). Is this possible with ASP.NET MVC? In fact, this model seems to best keep with the goal of separating concerns imho as it lets the controllers return view-agnostic data whereas most approaches I see today (including the above line "format.json .... :layout => false") do the JSON conversion inside the controller and return that data directly to the client given a request for that format.

Anyhow ... suggestions, thoughts, recommendations?

Thanks

From stackoverflow
  • In ASP.NET MVC, controller actions generally return objects that derive from ActionResult, which is then invoked by the runtime while generating the response stream.

    Out-of-the-box you have several classes that derive from ActionResult - ContentResult for text results, ViewResult for content from a view, JsonResult for serializing an object hierarchy into JSON, RedirectResult for redirecting, and so on.

    Generally you pass in the model to the result and let it decide how to generate the result, but it doesn't have to be the same model - I can pass a different object to each result if necessary.

    The concrete type of result returned by an action is not 'baked in' to the action's signature - you can easily pass in a format parameter to your action, and have it generate and return a different ActionResult accordingly:

    public ActionResult ListProducts(string format)
    {
        List<Product> products = ProductService.GetAllProducts();
        if (format == "JSON")
        {
            // eg., transform model for JSON consumption
            List<JsonProduct> jsonProducts = ProductService.ToJSON(products); 
            return Json(jsonProducts);
        }
        else if (format == "XML")
        {
            return new XmlResult(products);
        }
    
    
       // default is to return HTML from view, which expects List<Product> for model
       return View(products);
    

    }

    Note that the methods Json() and View() are built into the controller and are convenience methods for returning JsonResult and ViewResult respectively. XmlResult is an example of a custom ActionResult that takes an object, serializes it to XML, then returns the result as an XML stream.

    The example is a little contrived, but it shows that the controller orchestrates all the work of selecting the result and constructing / transforming the model that is passed to that result. Controller actions should still be light-weight though so you offload the heavy tasks to services, such as loading the model from the business layer, or transforming objects in one model to objects in another model, such as for JSON consumption.

    wgpubs : The only problem here is that rarely is it so easy to just return Json (your model). Typically, I'd expect folks to be using something like JQuery or ExtJs in the client that requires the Json (or xml) to be structured in a particular way. So ... where does that restructuring happen? If we should do it in the controller ... where/how? Also, if we do it there ... does this not violate "separation of concerns"? If we do it in the View ... how do we modify the framework to intelligibly pick the right view based on the requested format? Thanks.
    Sam : I agree, most of the time you will need a separate model for working with JSON. I don't see why separation of concerns is violated though - the controller's concern is to provide the model to the view, which includes working out what that model should be, and which view should be given that model. It's entirely relevant for the controller to do that. It would definitely be a violation if the view was doing the work of the controller. I edited my sample to indicate model construction.
    wgpubs : I guess I'm kind of torn on this one because yes, the controller should be responsible for how the data is packaged and sent of to the view ... but does that mean it should be responsible for such if that means returning the data in potentially many formats based on one or many client-side frameworks being used (e.g. ExtJs, Jquery, Mootools, etc...)? You see, we aren't just returning a bunch of data here ... we are returning data FOR JQuery or FOR ExtJs. That is where the separation thing gets a bit more obscured and also unit testing controllers a bit more hairy.
    Sam : Why would you need to return different formats for different JavaScript frameworks? Surely they can all consume the same JSON? It's just objects, after all - can you give an example of where this would be necessary?
    wgpubs : Nope. The JQuery and ExtJs widgets all have detailed specifications for what the JSON needs to look like ... and they aren't uniform and thus, my question: "By returning JSON in a format suitable for a given framework are we not violating proper separation of concerns?" Now I know most folks are following your approach here as it is the most straightforward ... but I'm wondering if it might be best to return the *same* DTO regardless of request type and define diff. views per request type (e.g. index_json.ascx, index_xml.ascx, index.aspx)? Seems more testable and prop. separated to me.

creating/editing textfile through vb.net

how do i code in vb.net the algorithm below. tnx!

Procedure logfile()
{
    if "C:\textfile.txt"=exist then
        open the textfile;
    else
        create the textfile;
    end if  
    go to the end of the textfile;
    write new line in the textfile;
    save;
    close;
}
From stackoverflow
  • Dim FILE_NAME As String = "C:\textfile.txt"
    Dim i As Integer
    Dim aryText(4) As String
    
    aryText(0) = "Mary WriteLine"
    aryText(1) = "Had"
    aryText(2) = "Another"
    aryText(3) = "Little"
    aryText(4) = "One"
    
    Dim objWriter As New System.IO.StreamWriter(FILE_NAME, True)
    
    For i = 0 To 4
        objWriter.WriteLine(aryText(i))
    Next
    
    objWriter.Close()
    MsgBox("Text Appended to the File")
    

    If you set the second parameter to True in the System.IO.StreamWriter's constructor it will append to a file if it already exists, or create a new one if it doesn't.

  • Giving you the code will be very easy. But here is a nice article which has code as well as some good explanation. : Reading and writing text files with VB.NET

    Cyril Gupta : +1 I agree, give the guy a fishing reel instead of a fish.
  • It's best to use a component that does this type of logging out of the box. The Logging Application Block from Enterprise Library for example. That way, you get flexibility, scalability and don't have contention with your log file.

    To answer your question specifically (sorry, I don't know VB, but the translation should be simple enough) ...

    void Main()
    {
        using( var fs = File.Open( @"c:\textfile.txt", FileMode.Append ) )
        {
         using( var sw = new StreamWriter( fs ) )
         {
           sw.WriteLine( "New Line" );
           sw.Close();
         }
    
         fs.Close();
        }
    }
    
  • This can be achieved in a single line too:

    System.IO.File.AppendAllText(filePath, "Hello World" & vbCrLf)
    

    It will create the file if missing, append the text and close it again.

    See MSDN, File.AppendAllText Method.

mysql LIKE returning only one row when three match.

When I query my database with the following in my file, search.php, it only returns the first result it comes across.

$qry = "SELECT business_id FROM business WHERE zip like '%91326%'";

$rs = mysql_query($qry);
$rec = mysql_fetch_array($rs);
echo $session->showContents($rec);

showContents is just a utility function...

function showContents($array)
{
        echo "<pre>";
        print_r($array);
        echo "</pre>";
}

showContents returned this:

Array
(
    [0] => 3
    [business_id] => 3
)

The crazy thing is, when I put the same query in sqlbuddy it gives me:

business_id
3
5
6

I am at a loss

From stackoverflow
  • mysql_fetch_array fetches only a single row. You want to use it several times to build an array with the entire result set:

    $rec = array();
    
    while(($row = mysql_fetch_array($rs)) !== FALSE) {
        $rec[] = $row;
    }
    

    If you just want the ID's you want to select the ID:

    $rec = array();
    
    while(($row = mysql_fetch_array($rs)) !== FALSE) {
        $rec[] = $row[0];
    }
    
  • Try this:

    $qry = "SELECT business_id FROM business WHERE zip like '%91326%'";
    $rs = mysql_query($qry);
    while ($rec = mysql_fetch_array($rs)) {
        echo $session->showContents($rec);
    }
    
  • That's because mysql_fetch_array only fetches a single row from the result set.

    Typically you use it like this (from the manual):

    while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
        printf("ID: %s  Name: %s", $row[0], $row[1]);  
    }
    

jQuery post parameter to load

How do I pass the values of txtname and tel as variables to the .load???

$(document).ready(function(){
    $("#add").click(function(){
        $("#result").load("add.php", {name: #txtname});
    });
});

The html:

<p>Name:<input type="text" name="name" value="" id="txtname" /></p>
<p>Telephone:<input type="text" name="tel" id="tel" value="" /></p>
<input type="submit" value="Submit" id="add" />
From stackoverflow
  • $(document).ready(function(){
      $("#add").click(function(){
        $("#result").load("add.php", {
          'name': $("#txtname").val(), 
          'telephone': $("#tel").val()
        });
      });
    });
    
  • $(document).ready(function() {
        $("#add").click(function() {
           $("#result").load("add.php", {
               name: $("#txtname").val(), 
               tel: $("#tel").val()
           });
        });
    });
    

HttpService requestTimeout

How do I determine if the HttpService instance timed out? Thanks!

From stackoverflow
  • If you set requestTimeout then your request will raise a fault when it times out. So you can just add an event listener to the httpservice faultevent.

Migrate InnoDB tables to PBXT

Is there any migration procedures or tools to migrate a Database (Liferay database to be exact) from InnoDB to PBXT?

From stackoverflow
  • what's wrong with just doing an ALTER TABLE? you might have to remove the foreign keys, change all of the tables, and add foreign keys back.

  • Run

    ALTER TABLE my_table_name ENGINE=PBXT;
    

    for each of your tables. If you have lots of tables, take a look at Maatkit as a possible automation solution. With it, you'd do something like:

    mk-find <db_name> --engine InnoDB --exec "ALTER TABLE %D.%N ENGINE=PBXT" --print
    

Unacceptable performance rendering PDF Tables with ITextSharp and PDFSharp

I am trying to generate PDF files containing large numbers of tables. Each PDF could potentially be 150 pages in length.

When using ITextSharp, the file sizes are up to 16 megabytes and have no noticeable shrinkage when zipped.

When using PDFSharp, the file size is very reasonable at 2 or 3 megabytes but it takes an unacceptable length of time (I canceled it after 3 minutes) to generate the document.

Does anybody have a suggestion of generating complex PDF files efficiently w/ .NET?

From stackoverflow
  • When my company tested out the performance of writing out PDFs we chose TallPDF by TallComponents. I wrote a wrapper around the lib and thought it was pretty easy to work with and did perform well on large datasets.

  • You say PDFsharp but you actually use MigraDoc. Yes, table rendering with MigraDoc Foundation is still slow.

    We have this issue on our task list for the forthcoming releases.

    The best place to ask PDFsharp and MigraDoc Foundation related questions is the PDFsharp forum. The PDFsharp Team will not monitor stackoverflow.com on a regular basis.

    PDFsharp Forum:
    http://forum.pdfsharp.net/

    ooo : @PDFsharp Team - was this ever fixed or is performance still an issue here?
    PDFsharp Team : When it comes to table rendering, performance is still not as good as it could be. Table rendering is fast enough for our applications, therefore this didn't have highest priority for us so far. It should be fixed with the next release which will hopefully be out late(r) this year.

applicationWillResignActive how to test on iPhone simulator

My iPhone application has code that handles the event for when the iPhone falls asleep, and re-awakens. My question is, how do I test this using either the iPhone or the simulator. Is there a hotkey or command to force the phone or simulator to fake "go to sleep?".

Thanks.

From stackoverflow
  • Yes, Command-L ("Lock" on the "Hardware" menu) will lock the simulator.

    It will not go to sleep, but according to the documentation, this should be enough to trigger the "applicationWillResignActive" method:

    "The delegate can implement this method to make adjustments when the application transitions from an active state to an inactive state. When an application is inactive, it is executing but is not dispatching incoming events. This occurs when an overlay window pops up or when the device is locked."

    Kevin : Perfect, thanks!

Database-sessions in Spring

Hi guys,

I'm quite new to Spring, and I would like to understand a bit more about sessions. I've mapped a legacy database with Hibernate annotated entities and built a couple of service objects to fetch, retrieve etc. My entities also contain other entities (mapped through foreign keys) and sets of entities. When I traverse the entitiy graph in my services, I have no problem. My services been wrapped in a TransactionProxyFactoryBean, so all should be good.

So, in my View Controller I request a bunch of entities from the services. But when I traverse the entity graph in my view controller (for example to display user's state's country's name, with both state and country being lazily loaded entities), the Hibernate session is already closed and I get a "LazyInitializationException: could not initialize proxy - no Session"

I wouldn't want my services to eagerly fetch the data, that'll consume way to much RAM because my graphs are deep and can even have circular references. I also don't want to explicitly have to touch on the parts that I'll be displaying in the services, as that'd mean that I'll have to copy/paste write similar services over and over again. So what I want is to have the Hibernate session still open when I'm in my view controller and not close down the session until the view has been served. What can I do to keep it open?

My view bean looks like this, is there any way I can inject my TransactionProxyFactoryBean-derived bean into it?

  <bean name="/" class="example.SimpleViewController">
    <property name="userService" ref="userService"/>
    <property name="catalogService" ref="catalogService"/>
  </bean>

Cheers

Nik

From stackoverflow
  • See my answer to this question: http://stackoverflow.com/questions/1139985/in-spring-with-jpa-hibernate-how-do-i-keep-a-session-open-to-avoid-lazy-initiali/1140096#1140096

    I'm using Hibernate without Spring, so I am not 100% sure of the capabilities Spring has to deal with Sessions, but I believe it has both a built in Filter and Interceptor. The best way to handle sessions outside of JPA is to write a filter that opens the session before handing off to the rest of your server side stuff, then closes the session afterwards. I believe this is what Spring's built in stuff does.

    André Neves : Very common issue. Opening the session in a filter is the way to go.
  • You still have to use the open-session-in-view pattern to avoid this particular problem, regardless of whether you're using Spring; although Spring has some facility to help with implementing the design pattern on some frameworks like Struts or plain JSP.

PyS60 on device debug ?

A simple matter makes me suffering as I'm new to PyS60 development.

What is the IDE for

  • Executing program on-device with a single reasonable amount of clicks,
  • Typical step-into, step-over, run-to, watch (used from PC) for the on-device running program ?
From stackoverflow
  • Real on-device debugging is not (yet) possible, I'm afraid. You have to use popup notes, audio.say() or write to log files.

    Personally I forward sys.stdout and sys.edterr into a log file and use sys.settrace() and sys.setprofile(). Works reasonably well, no need to modify real app source code, just dump EVERYTHING into a log file and do search afterwards.

how to setup bindable checkbox value automatically changed to male/female

I'm using detailsview in asp.net. I have gender field. when this field checked, checkbox text automatically changed to 'male', otherwise 'female'. How can i do? How to setup checkbox to this feature?

From stackoverflow
  • While I hope you aren't actually doing this, the following will accomplish it:

    protected void chkSex_CheckedChanged(object sender, EventArgs e)
    {
        CheckBox chkSex = (CheckBox)sender;
        chkSex.Text = SexString(chkSex.Checked);
    }
    protected string SexString(bool sex)
    {
        return sex ? "Male" : "Female";
    }
    

    And the markup:

    <asp:UpdatePanel runat="server">
        <ContentTemplate>
            <asp:CheckBox runat="server" 
                Checked='<%# Eval("Sex") %>'
                OnCheckedChanged="chkSex_CheckedChanged" 
                AutoPostBack="true" 
                Text='<%# SexString((bool)Eval("Sex")) %>'/>
        </ContentTemplate>
    </asp:UpdatePanel>
    
  • You can do this with some simple javascript.

    Mark Up

    <label id="sexLabel" for="sexCheckBox">Male</label>
    <input id="sexCheckBox" type="checkbox" onclick="sexClick(this);" />
    

    Code

    function sexClick(checkbox) {
        document.getElementById('sexLabel').innerHTML = (checkbox.checked) ? 'Female' : 'Male';     
    }
    

    jQuery

    Mark Up

    <label id="sexLabel" for="sexCheckBox">Male</label>
    <input id="sexCheckBox" type="checkbox" />
    

    Code

    $(function() {
        $('#sexCheckBox').click(function() {
            $('#sexLabel').text((checkbox.checked) ? 'Female' : 'Male');
        });
    });
    
    Yuriy Faktorovich : Ha, I went overboard.
  • Suppose the column or property name is Sex and is true if sex is male. Use this in markup:

    <asp:CheckBox runat="server" ID="chkSex" Text='<%# GetText((bool)Eval("Sex"))%>' 
             Checked='<%# Eval("Sex")%>' />
    

    write this method in code-behind:

    protected static object GetText(bool b)
    {
        return b ? "Male" : "Female";
    }
    

ASP.NET Dynamic GridView Creation

How can I add an Edit column in this GridView dynamically?

alt text

I have been able to create this GridView dynamically with the following code.

The aspx file:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="GridView___Test._Default" %>

<!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 runat="server">
    <title>Untitled Page</title>
</head>

<body>
    <form id="form1" runat="server">
    <div>

        <asp:GridView ID="GridView1" runat="server" Font-Names="Verdana" Font-Size="Small" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" AutoGenerateColumns="False">            
        </asp:GridView>

    </div>
    </form>
</body>

</html>

The code behind:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using Ice_Web_Portal.BO;

namespace GridView___Test
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                CreateGridView();
            }
        }

        private void CreateGridView()
        {
            DataTable dataTable = Book.GetBooksDataSet().Tables[0];

            foreach (DataColumn c in dataTable.Columns)
            {
                BoundField boundField = new BoundField();

                boundField.DataField = c.ColumnName;
                boundField.HeaderText = c.ColumnName;

                GridView1.Columns.Add(boundField);
            }

            GridView1.DataSource = dataTable;
            GridView1.DataBind();
        }
    }
}

Now please tell how to add some more code to add Edit column in this GridView dynamically.

From stackoverflow
  • out of the foreach, try

    CommandField c = new CommandField();
    c.ShowEditButton = true;
    
    c.Columns.Add(c);
    
    JMSA : GridView1.Columns.Add(c);
    michele : yep...sorry for the mistake!

Tracking down max-specpdl-size errors in emacs

I've been randomly getting the following error in emacs:

Variable binding depth exceeds max-specpdl-size

...and I've been getting it at very random moments. After researching this, it seems as though some elisp somewhere is recursing too deeply. Are there any strategies for tracking this down? I'm totally at a loss as far as what is actually causing this.

I've gotten some errors indicating something along the lines of infinite recursion with ropemacs (but these are usually Python errors). Could something be misconfigured with ropemacs?

Update: Interestingly enough, I've found that I always get this error if I do a "C-h a" for "speedbar" but not for "rope-".

From stackoverflow
  • To track the problem down, you can try this:

    (setq max-specpdl-size 5)  ; default is 1000, reduce the backtrace level
    (setq debug-on-error t)    ; now you should get a backtrace
    C-h a ; in speedbar
    

    You should get a backtrace upon the error, and at that point, you can track down the offending routine.

    I'd also try loading emacs w/out your configuration file (emacs -q), to see if there's something in your .emacs that is affecting things. (I don't get the infinite loop using C-h a). And if it is your .emacs, then the best way I've found to track that down is either binary search (put an error (error "frog") or somesuch in the middle of your .emacs, load, test, if no problems, put the error at 3/4, otherwise at 1/4, repeat...), or manually evaluate your .emacs line by line (region by region), testing after each portion. Those settings should help.

    seth : fixed a typo...hope you don't mind.
    Trey Jackson : Of course not. Wish SO had a 'diff' utility while editing, I wanted to see where I mussed up.
    seth : You had `debug-on-errot`. If you click on the link next to edited (e.g. '5 hours ago') above my gravatar, you can see the diff. Or do you mean something different?

ehcache auto-discovery (via multicast) between 2 instances on the same host

Hello

I run 2 tomcat instances on the same host. Each instance runs the same web application which tries to communicate some ehcache caches via RMI replication. I use the autodiscovery configuration in ehcache so I don't have to explicitly define which are the hosts and which are the caches I want to replicate. The ehcache instances do not manage to find each other and communicate:

DEBUG (RMIBootstrapCacheLoader.java:211) - cache peers: []
DEBUG (RMIBootstrapCacheLoader.java:133) - Empty list of cache peers for cache org.hibernate.cache.UpdateTimestampsCache. No cache peer to bootstrap from.

If I try the same thing but this time run each tomcat instance on a separate host (box) then everything works like a charm.

Am I doing something wrong, or isn't autodiscovery via multicast possible when the instances are on the same host?

My configuration uses the defaults presented in the RMI Distributed Caching documentation:

<cacheManagerPeerProviderFactory
        class="net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory"
        properties="peerDiscovery=automatic, multicastGroupAddress=230.0.0.1, 
                    multicastGroupPort=4446, timeToLive=32"/>
<cacheManagerPeerListenerFactory
        class="net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory"
        properties="port=40001, socketTimeoutMillis=2000"/>

And inside each cache region I want to replicate I have:

<cacheEventListenerFactory
        class="net.sf.ehcache.distribution.RMICacheReplicatorFactory" 
        properties="asynchronousReplicationIntervalMillis=500 " />
<bootstrapCacheLoaderFactory 
        class="net.sf.ehcache.distribution.RMIBootstrapCacheLoaderFactory" />

thanks

From stackoverflow
  • Am I doing something wrong, or isn't autodiscovery via multicast possible when the instances are on the same host?

    While I'm not really familiar with ehcache I'd think this to be possible and they are in fact providing an example doing something similar at least (multiple nodes per host, though one instance only): see section Full Example in the RMI Distributed Caching documentation you mentioned.

    Usually you cannot open the same TCP port (40001 here) more than once per host though, it is bound to the first application/service allocating it (there do exist things like TCP Port Sharing on Windows for example, but you'd have to specifically account for that).

    Consequently, if you are really using their identical default configurations, the second Tomcat instance trying to allocate TCP port 40001 will fail to do so. Of course, this should manifest itself somewhere earlier in the Tomcat logs, have you had a thorough look already?

    Just using another free port for one Tomcat instance should solve the issue; you can see this in action within the ehcache.xml's for the Full Example mentioned above: the port number is increased one by one from 40001 up to 40006 per node.

    cherouvim : That was it. There was a port collision but no WARN or ERROR on logs (and I have everything set to level ALL). Thanks a lot!!!

C# - Interface inside a class

According to the MSDN document interface can be a member of a class or namespace :

for Example i can declare:

public class Test
{
    public interface IMemberofTest
    {
        void get();
    }
}

What is the use of having interface inside a class? Won't it break the purpose of real interface usage?

From stackoverflow
  • Not if, for some reason, that interface only makes sense within the context of that class, and you want to make that clear by implementing it like so.

    I must say, I've never used this construct once, for what it's worth.

  • The class is another namespace. Therefore the interface can be used to enforce contracts on data that flows between methods in the class, or just to scope the interface more precisely.

  • They are useful when you want to break things up within a class.

        public class Invoice
        {
         public String Print(Type type)
         {
          IPrinter printer = null;
          switch (type)
          {
           case Type.HTML:
            printer = new HtmlPrinter(this);
            break;
           case Type.PDF:
            printer = new PdfPrinter(this);
            break;
           default:
            throw new ArgumentException("type");
          }
    
          printer.StepA();
          printer.StepB();
          printer.StepC();
    
          return printer.FilePath;
         }
    
    
         private interface IPrinter
         {
          void StepA();
          void StepB();
          void StepC();
          String FilePath { get; }
         }
    
         private class HtmlPrinter : IPrinter
         {
          //Lots of code
         }
    
         private class PdfPrinter : IPrinter
         {
          //Lots of code
         }
    
         public enum Type
         {
          HTML,
          PDF
         }
        }
    
    Paddy : Personally I'm not a fan of many classes within one code file - I find it just makes things hard to find.
    macke : Wouldn't dependancy injection be a better alternative in this case? That way you could let whoever calls Print decide in what manner it should be printed (as long as IPrinter is implemented) thus reducing the complexity of Invoice while at the same time allowing for more types of printers than HTML and PDF (Mocking for instance).

Setting up an existing project on aptana (No Rakefile found problem)

I just installed aptana, and i have the repository for the rails project.. So i open a new project and point it to my repository.. and it opens... But i can't do any rake tasks. Under rake tab, it says that "no rake tasts found. Likely cause is no Rakefile for the project"

But i can see the Rakefile in the project.. Can anyone help?

From stackoverflow
  • The problem is you have to change the Installed Interpreter path in aptana studio , by default the aptana studio takes it own version of the interpreter ie org.jruby . Make sure to change the path to your locally installed ruby environment .

    In order to change it go to Windows->Preference->Ruby->Installed Interpreters

    If you are working in windows Add a new environment provide

      RubyVM home directory = c:\ruby
    

    If you are working in ubuntu or any other linux platform provide

      RubyVM home directory = /usr/bin
    

    This makes all the gems ,rake to available to your aptana studio . still if doesnot work second option would be, provide the rake path where you have installed in aptana .

    In order to change it go to Windows->Preference->Ruby->Rake

    provide the rake path = (your-installed-rake path )

    Good luck !

    Wonder : i tried both of them... my installed interpreter was already pointing to c:\ruby then i tried the second way and pointed it to c:\ruby\bin\rake but still not working :(
    YetAnotherCoder : update your rake gems , can you post the rake version and gem version
  • I'm a bit late but I've encountered a similar issue and finally found out that there was no target in Rakefile, that's why this message is displayed. Just add one and this error message will go away.

Is necessary to compile linq queries in subsonic?

I'd like to know if it's necessary to compile linq queries to the subsonic entities?

For example would I'd need to compile the following linq query?

var comments = from a in All()
                           where a.ParentCommentId == ArticleCommentId
                           select a;
From stackoverflow
  • Compiled queries are an optional optimization that allow you avoid parsing an expression tree multiple times. It's never required, but may be necessary to meet your performance requirements.

    romkyns : I should mention that the cost can be quite significant unexpectedly. Any place where a query is invoked in a loop may need either refactoring or compiling the queries in the loop. Otherwise a tiny innocent-looking query invoked a mere 10 times may suddenly give you a 0.5 second delay in the user interface.

Using Gcc on Win32 and linking to msvcrt.dll

I know microsoft recommends against linking to the msvcrt.dll, so please spare me from that warning. They do it all the time in their software (like WinDbg) and they won't introduce breaking changes since all VC6 apps link against msvcrt.dll.

Linking against msvcrt.dll has several benefits. Small executable, easy deployment: msvcrt is there since win98 and I don't have to bundle few MB C runtime with my installer.

Now, is it possible to use gcc to link agains the C library in msvcrt.dll instead of glibc? If yes, how?

Thanks!

From stackoverflow
  • AFAIK the MinGW port for gcc does link your program to msvcrt.dll.

insert data in multiple tables

hi i have a problem to insert data in multiple tables. i have define primary key & reference key in tables now i want to insert data in both tables in single query.......how can i do this...........???????

From stackoverflow
  • Does your language support the INSERT ALL construct? If so, that is the best way to do this. In fact it's the only way. I posted an example of this construct in another SO thread (that example syntax comes from Oracle SQL).

    The other option is to build a transactional stored procedure which inserts a record into the primary key table followed by a record into the referencing table.

  • This is what transactions are meant for. Standard SQL does not permit a single statement inserting into multiple tables at once. The correct way to do it is:

    -- begin transaction
    insert into table 1 ...
    insert into table 2 ...
    commit
    
  • And 1 of your choice to do that is use ORM (like Hibernate, NHibernate) the you make your object and set other relation to it and finally just save the main object , like:

    A a;
    B b;
    C c;
    a.set(b);
    a.set(c);
    DAO.saveOrUpdate(a);
    

    you must notice your DAO.saveOrUpdate(a); line of code just work with hibernate but it insert data into 3 table A, B, C.

  • Your question isn't exactly clear on what the particular problem is. I can see three possibilities:
    1. You want to insert into two tables wiht a single INSERT statement
    2. You want to do two inserts, but without anything else being able to 'get in the middle'
    3. You want to insert into one table, then get the primary key to insert into the second table


    The answer to 1. is simple:

    You can't.
    


    The answer to 2. is simple too:

    BEGIN TRANSACTION
       INSERT INTO <table1> (a,b,c) VALUES (1,2,3)
       INSERT INTO <table2> (a,b,c) VALUES (1,2,3)
    COMMIT TRANSACTION
    


    The answer to 3. is has several possibilities. Each depending on exactly what you want to do. Most likely you want to use SCOPE_IDENTITY() but you may also want to look up @@identity and IDENT_CURRENT() to understand the various different options and complexities.

    BEGIN TRANSACTION
    
       INSERT INTO <dimension_table> (name)
          VALUES ('my new item')
    
       INSERT INTO <fact_table> (item_id, iteam_value)
          VALUES (SCOPE_IDENTITY(), 1)
    
    COMMIT TRANSACTION
    

Sharing objects between C# and C++ code

Is it possible to share references to C# objects between C# and C++ code without massive complexity? Or is this generally considered a bad idea?

From stackoverflow
  • The best solution for sharing a C# object between native and managed code is to use COM interop. This allows you to essentially share an interface of an object between managed code and it's equivalent signature in C++.

    As for the complexity side of things. The majority of COM interop scenarios are straight forward and really are no more complex than good old COM programming. On the managed side it looks really no different than a normal interface.

    Once you introduce multiple threads or start playing around between COM apartments though, things can get a bit tricky.

    In my experience, the easiest way to get this working is the following.

    • Define an interface in C# that you wish to use in C++
    • Mark the interface with the ComVisible(true) attrbute
    • Run tlbexp on the assembly which generates a TLB file
    • Import the TLB into your native project

    This will get the interface definition into both of your projects. How to pass that between the projects requires a bit more detail into your architecture.

  • Another solution I can recommend, from personal experience, is to use a managed C++ interface between the two if the C++ code you want to access is too large or too complex.

    For example, I am using the RakNet C++ network library in a C# project. The solutions are to either create a massive wrapper class in C# to access the required C++ functions, create a C++ wrapper around those functions which can than be used as a COM interop or use Managed C++ (Visual C++/CLI).

    I chose the latter which allows me to use C++ to access the RakNet library, but the classes created can be used directly in another .NET project as if. So the main logic has been created in those Managed C++ classes, which also allow me to use the .NET framework and some of its wonderful features. In my C# project I simply need to call the Managed C++ library which provides me with all in all 20 functions I need to perform everything.

How can I edit Shark configurations on the iPhone?

The default shark 'Time Profile' configuration on the iPhone appears to sample every 1 ms. I'd like to tweak it to sample every 100us. I know this is possible to do on my local machine by editing the shark configurations, but I don't see a way to edit the configurations on the phone.

Thank you,

From stackoverflow
  • Answer: it would appear that you can't.

    From the Shark User Manual:

    Important: Currently, while you can make custom ARM counter configurations with Shark, there is no way to load customized configuration files onto your iPhone OS device using the iPhone OS SDK. This restriction may be relaxed in future versions of the SDK. In the meantime, send suggestions for useful configurations to perftools-feedback@group.apple.com and we may include them in future iPhone OS SDK releases.

Viewing swf files in magazine format

I have a set of swf files and can view them one at a time. However what I would like to is to view them in magazine format, as below: First view is: swf file1 (magazine front cover) Next view: swf file2 (magazine page 1) on left + swf file3 (magazine page 2) on right Next view: swf file4 (magazine page 3) on left + swf file5 (magazine page 4) on right Next view: swf file6 (magazine page 5) on left + swf file7 (magazine page 6) on right etc etc Last view: swf filex (magazine back cover)

So it's like flipping through a amagzine. This is what one can see on issuu.com I'd like to get the software that will do this. Preferably free!

From stackoverflow
  • I'm not familiar with issuu.com, but seems like you could very easily accomplish this with basic HTML. Split your viewing area into two equally-sized side-by-side regions and put a flash object in each one. If you've got a fairly standard naming convention, you could programmatically determine the files that would go together. (even always on right, odd on left)

    For a given spread, the pages for that spread are

    leftpage = (spreadnumber * 2) - 2;
    

    and

    rightpage = (spreadnumber * 2) - 1;
    

    So, spread 3 would be pages (3*2)-2 = 4 (left) and (3*2)-1 = 5 (right).

  • Check out Megazine, it's an open source page flip engine that will do exactly what you need written in AS3, source code is available.

    http://megazine.mightypirates.de/

How to compare values of two controls with a trigger?

I have to buttons, named btnOK and btnSave.

I want that the IsEnabled of btnSave should be the same as the btnOK's value, i.e. if btnOK goes disabled, btnSave should do the same.

I actually need something like (pseudu):

<Button TabIndex="3" Name="btnOK">
    <Button.Triggers>
        <Trigger Property="IsEnabled">
            <Setter TargetName="btnSave" Property="IsEnabled" Value="Self.IsEnabled"/>
        </Trigger>
    </Button.Triggers>
</Button>
<Button Name="btnSave"/>
From stackoverflow
  • <Button Name="btnOK">OK</Button>
    <Button Name="btnSave" IsEnabled="{Binding IsEnabled, ElementName=btnOK}">Save</Button>
    

    HTH, Kent

    Shimmy : If I wouldn't have this question I could of died without knowing that the ElementName thing even exists.... Thanks man!!!

Client side event handler on validation for asp.net validator controls

Hi,

I have an asp.net form with bunch of sections that can be expanded/collapsed and are normally collapsed. Now, most controls on the form have RequiredFieldValidator or some other validators attached. If the user tries to submit the form with required fields not filled out, for m is not submitted but because most sections are normally collapsed, the user doesn't see the validator text (like exclamation mark on the right of a text box) prompting to fix the error. What I want to do is for the controls that fail validation, to expand their parent containers so user could see those failed controls, but for that I need to hook up some client sode javascript that woudl execute when client side validation failed. I haven't foudn any way of doing it - validators naturally dont' expose those "validation events" to hookup to. Of course I can create my custom validators but that would mean rewriting (and duplicating functionality) completely all existing asp.net validators which sounds a big chunk of work.

Any ideas?

Thank you in advance! Andrey

From stackoverflow
  • Here is how I solved a similar issue. For every validator that is added to the accordion, I store the validator id in an array, along with the accordion panel that it is contained in. I then pass this list to the client. I also hook into the OnSubmit event by calling Page.ClientScript.RegisterOnSubmitStatement. The javascript function that executes during the onSubmit first checks to see if the page is valid, if so then it just exits, if not then it loops through the list of validators looking for ones that are not valid, when it finds one, it expands the section associated with that validator.

    Andrey : It's an interesting idea! In fact, the page will already have an array of all validators in Page_Validators variable; so I just need to loop over the array and for each failed validator get associated control and expand it's parent container. Sounds like it might work for me! Thanks!