input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
Connecting to SQL Server with ActiveRecord <p>Have you ever had to connect to SQL Server with ActiveRecord? Is this possible? Can anyone provide some starting points?</p>
| <p>This what I used:</p>
<p>From here:
<a href="http://github.com/rails-sqlserver/2000-2005-adapter/tree/master">http://github.com/rails-sqlserver/2000-2005-adapter/tree/master</a></p>
<p><em>Installation</em></p>
<p>First, you will need Ruby DBI and Ruby ODBC. To my knowledge the ADO DBD for DBI is no longer supported. The installation below is not a comprehensive walk thru on how to get all the required moving parts like FreeTDS installed and/or configured. It will also assume gem installations of both the dependent libraries and the adapter itself.</p>
<p>It should be noted that this version of the adapter was developed using both the ancient 0.0.23 version of DBI up to the current stable release of 0.4.0. Because later versions of DBI will be changing many things, IT IS HIGHLY RECOMMENDED that you max your install to version 0.4.0 which the examples below show. For the time being we are not supporting DBI versions higher than 0.4.0. The good news is that if you were using a very old DBI with ADO, technically this adapter will still work for you, but be warned your path is getting old and may not be supported for long.</p>
<pre><code>$ gem install dbi --version 0.4.0
$ gem install dbd-odbc --version 0.2.4
$ gem install rails-sqlserver-2000-2005-adapter -s http://gems.github.com
</code></pre>
<p>From here: <a href="http://lambie.org/2008/02/28/connecting-to-an-mssql-database-from-ruby-on-ubuntu/">http://lambie.org/2008/02/28/connecting-to-an-mssql-database-from-ruby-on-ubuntu/</a></p>
<p>Firstly, update your ~/.profile to include the following:</p>
<pre><code>export ODBCINI=/etc/odbc.ini
export ODBCSYSINI=/etc
export FREETDSCONF=/etc/freetds/freetds.conf
</code></pre>
<p>Then reload your .profile, by logging out and in again.</p>
<p>Secondly, on Ubuntu 7.10 Server I needed to install some packages.</p>
<pre><code>mlambie@ubuntu:~$ sudo aptitude install unixodbc unixodbc-dev freetds-dev sqsh tdsodbc
</code></pre>
<p>With FreeTDS installed I could configure it like this:</p>
<pre><code>mlambie@ubuntu:/etc/freetds$ cat freetds.conf
[ACUMENSERVER]
host = 192.168.0.10
port = 1433
tds version = 7.0
</code></pre>
<p>The important thing here is ACUMENSERVER, which is the DSN that Iâll use when connecting to the database. The host, and port are self-explanatory, and itâs worth noting that I had to use 7.0 specifically as the tds version.</p>
<p>Testing FreeTDS is not too hard:</p>
<pre><code>mlambie@ubuntu:~$ sqsh -S ACUMENSERVER -U username -P password
sqsh: Symbol `_XmStrings' has different size in shared object, consider re-linking
sqsh-2.1 Copyright (C) 1995-2001 Scott C. Gray
This is free software with ABSOLUTELY NO WARRANTY
For more information type '\warranty'
1> use acumen
2> go
1> select top 1 firstname, lastname from tblClients
2> go
[record returned]
(1 row affected)
1> quit
</code></pre>
<p>Next up itâs necessary to configure ODBC:</p>
<pre><code>mlambie@ubuntu:/etc$ cat odbcinst.ini
[FreeTDS]
Description = TDS driver (Sybase/MS SQL)
Driver = /usr/lib/odbc/libtdsodbc.so
Setup = /usr/lib/odbc/libtdsS.so
CPTimeout =
CPReuse =
FileUsage = 1
mlambie@ubuntu:/etc$ cat odbc.ini
[ACUMENSERVER]
Driver = FreeTDS
Description = ODBC connection via FreeTDS
Trace = No
Servername = ACUMENSERVER
Database = ACUMEN
</code></pre>
<p>I then tested the connection with isql:</p>
<pre><code>mlambie@ubuntu:~$ isql -v ACUMENSERVER username password
+---------------------------------------+
| Connected! |
| |
| sql-statement |
| help [tablename] |
| quit |
| |
+---------------------------------------+
SQL> use ACUMEN
[][unixODBC][FreeTDS][SQL Server]Changed database context to 'Acumen'.
[ISQL]INFO: SQLExecute returned SQL_SUCCESS_WITH_INFO
SQLRowCount returns -1
SQL> select top 1 firstname from tblClients;
[record returned]
SQLRowCount returns 1
1 rows fetched
SQL> quit
</code></pre>
<p>OK, so weâve got ODBC using FreeTDS to connect to a remote MSSQL server. All thatâs left is to add Ruby into the mix.</p>
<pre><code>mlambie@ubuntu:~$ sudo aptitude install libdbd-odbc-ruby
</code></pre>
<p>The last thing to test is that Ruby can use DBI and ODBC to hit the actual database, and thatâs easy to test:</p>
<pre><code>mlambie@ubuntu:~$ irb
irb(main):001:0> require "dbi"
=> true
irb(main):002:0> dbh = DBI.connect('dbi:ODBC:ACUMENSERVER', 'username', 'password')
=> #<DBI::DatabaseHandle:0xb7ac57f8 @handle=#<DBI::DBD::ODBC::Database:0xb7ac5744
@handle=#<odbc::database:0xb7ac576c>, @attr={}>, @trace_output=#</odbc::database:0xb7ac576c><io:0xb7cbff54>,
@trace_mode=2>
irb(main):003:0> quit
</code></pre>
<p>And a more complete test (only with SQL SELECT, mind you):</p>
<pre><code>#!/usr/bin/env ruby
require 'dbi'
db = DBI.connect('dbi:ODBC:ACUMENSERVER', 'username', 'password')
select = db.prepare('SELECT TOP 10 firstname FROM tblClients')
select.execute
while rec = select.fetch do
puts rec.to_s
end
db.disconnect
</io:0xb7cbff54>
</code></pre>
<p>From here (to fix the odbc lib being in the wrong place):
<a href="http://ubuntuforums.org/showthread.php?t=433435&page=2">http://ubuntuforums.org/showthread.php?t=433435&page=2</a></p>
<pre><code>libtdsodbc.so
with freeTDS (freetds-dev, tdsodbc), you can either edit the path in the odbcinst.ini file for the [FreeTDS] driver section OR cp the /usr/lib/odbc/libtdsodbc.so into /usr/lib/libtdsodbc.so.
</code></pre>
<p>either way works when accessing mssql from the prompt</p>
<pre><code>isql -v $dsn $user $passwd
</code></pre>
<p>i found this to be useful</p>
<p><a href="http://www.unixodbc.org/doc/FreeTDS.html#Configuration">http://www.unixodbc.org/doc/FreeTDS.html#Configuration</a></p>
<p>And then in the database.yml file:</p>
<pre><code>development:
adapter: sqlserver
mode: odbc
dsn: dsn_name
username: my_username
password: my_password
</code></pre>
|
What happens to viewstate in a text/plain page? <p>Let's say you have a page that produces text/plain output. If you set the ViewState in Page_Load, it doesn't do anything to the output (which makes sense).</p>
<p>My question is, does text/plain turn off ViewState processing? What does ASP.NET do to decide when it'll turn things off?</p>
| <p>In order to have a view state enabled you must have <form runat="server"> element in your ASP.Net. Since you are using plain text as output you probably don't have this element.</p>
|
log4net only logs when running in the Visual Studio debugger <p>I'm running Visual Studio 2008 - and have a problem with log4net logging (v1.2.10).
I have a small console test program with a single log statement.
I have log4net configured for RollingLogFileAppender and ConsoleAppender. </p>
<p>When I run the compiled exe from the command line, I see the correct creation of the log file in my runtime directory. The log file is created (or appended to, when it exists), but the only output is the [Header] and [Footer] as configured. There is no output to console.</p>
<p>However, <b>when I run under the debugger, the log message appears both in the log file and on the console</b>. Following is my log4net configuration:</p>
<pre><code><log4net>
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout" value="%date [%thread] %-5level %logger - %message%newline" />
</appender>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="quicktest-log-" />
<appendToFile value="true" />
<immediateFlush value="true" />
<datepattern value="yyyy-MM-dd" />
<maxSizeRollBackups value="100" />
<maximumFileSize value="1048576" />
<rollingStyle value="Composite" />
<staticLogFileName value="false" />
<layout type="log4net.Layout.PatternLayout">
<header value="[Begin Quicktest program log]&#13;&#10;" />
<footer value="[End Quicktest program log]&#13;&#10;" />
<conversionPattern value="%date{HH:mm:ss} [%thread] %-5level %logger: %message%newline" />
</layout>
</appender>
<root>
<level value="ALL" />
<appender-ref ref="ConsoleAppender" />
<appender-ref ref="RollingLogFileAppender" />
</root>
</log4net>
</code></pre>
| <p>This theory could be a stretch, but have you ensured that the app.config has been copied to the folder where your executable is? App.config must be copied to where the output executable is, and you also must rename it to <executablename>.config, so if your executable is MyProgram.exe, config must be in MyProgram.exe.config.</p>
|
Apply an ID to a GridView <p>Before you say it, I'm perfectly aware that a data repeater could do it, but I'm looking for the solution using a GridView.</p>
<p>I'm implementing a jQuery feature and require unique ID's to be applied to individual rows in order to respond to click events in the correct manner. I can't see how you're supposed to apply values to an ID or a row.</p>
<p>Basically I'm looking at doing something along the lines of</p>
<pre><code>$('tr').click(function() {
// get the ID of the tr and redirect the page based on that
});
</code></pre>
<p><strong>EDIT:</strong> Oh, and I can do it for a row cell if that's the value I want to pass as the query string, however, I don't want to do that as it'd mean displaying a unique identifier which is something the user shouldn't be able to see.</p>
| <p>Okay, I didn't expect to actually solve my own question. Just for reference, here it is:</p>
<pre><code>If e.Row.RowType = DataControlRowType.DataRow Then
e.Row.ID = e.Row.DataItem("Issue_Key")
End If
</code></pre>
<p>which is placed in the RowDataBound event.</p>
|
How to access the properties of a file upload button? <p>can you show me how to assign css properties to the button that is of type=file,say:</p>
<pre><code><input type="file" name="coolFile">
</code></pre>
<p>I know that in css you need to do this:</p>
<pre><code> input[type=file]{
background:#ccf;
//and so on
}
</code></pre>
<p>How do I assign values for the button?</p>
| <p>Assuming you want to change the button's text, here's one tutorial on how to do that:</p>
<p><a href="http://www.quirksmode.org/dom/inputfile.html" rel="nofollow">http://www.quirksmode.org/dom/inputfile.html</a></p>
<p>If it's just the plain CSS properties like colour/border/etc, you already have the answer, you just need to check stuff to find out why it's not working.</p>
|
sprintf outcome problem <p>Here is my code:</p>
<pre><code><?php
$variable1 = 00001;
$variable2 = (sprintf('%04d', $variable1 + 1));
echo $variable2;
?>
</code></pre>
<p>How come the outcome of this code is "0002" and not "00002"? in other words it is missing a 0.</p>
| <p>The 4 in %04d sets the total width of the printed value</p>
|
Instantly detect client disconnection from server socket <p>How can I detect that a client has disconnected from my server?</p>
<p>I have the following code in my <code>AcceptCallBack</code> method</p>
<pre><code>static Socket handler = null;
public static void AcceptCallback(IAsyncResult ar)
{
//Accept incoming connection
Socket listener = (Socket)ar.AsyncState;
handler = listener.EndAccept(ar);
}
</code></pre>
<p>I need to find a way to discover as soon as possible that the client has disconnected from the <code>handler</code> Socket.</p>
<p>I've tried:</p>
<ol>
<li><code>handler.Available;</code></li>
<li><code>handler.Send(new byte[1], 0,
SocketFlags.None);</code></li>
<li><code>handler.Receive(new byte[1], 0,
SocketFlags.None);</code></li>
</ol>
<p>The above approaches work when you are connecting to a server and want to detect when the server disconnects but they do not work <em>when you are the server and want to detect client disconnection.</em></p>
<p>Any help will be appreciated.</p>
| <p>Since there are no events available to signal when the socket is disconnected, you will have to poll it at a frequency that is acceptable to you.</p>
<p>Using this extension method, you can have a reliable method to detect if a socket is disconnected.</p>
<pre><code>static class SocketExtensions
{
public static bool IsConnected(this Socket socket)
{
try
{
return !(socket.Poll(1, SelectMode.SelectRead) && socket.Available == 0);
}
catch (SocketException) { return false; }
}
}
</code></pre>
|
Is there an equivalent to the Scanner class in C# for strings? <p>In Java I can pass a Scanner a string and then I can do handy things like, <code>scanner.hasNext()</code> or <code>scanner.nextInt()</code>, <code>scanner.nextDouble()</code> etc.</p>
<p>This allows some pretty clean code for parsing a string that contains rows of numbers.</p>
<p>How is this done in C# land?</p>
<p>If you had a string that say had:</p>
<pre><code>"0 0 1 22 39 0 0 1 2 33 33"
</code></pre>
<p>In Java I would pass that to a scanner and do a </p>
<pre><code>while(scanner.hasNext())
myArray[i++] = scanner.nextInt();
</code></pre>
<p>Or something very similar. What is the C#' ish way to do this?</p>
| <p>I'm going to add this as a separate answer because it's quite distinct from the answer I already gave. Here's how you could start creating your own Scanner class:</p>
<pre><code>class Scanner : System.IO.StringReader
{
string currentWord;
public Scanner(string source) : base(source)
{
readNextWord();
}
private void readNextWord()
{
System.Text.StringBuilder sb = new StringBuilder();
char nextChar;
int next;
do
{
next = this.Read();
if (next < 0)
break;
nextChar = (char)next;
if (char.IsWhiteSpace(nextChar))
break;
sb.Append(nextChar);
} while (true);
while((this.Peek() >= 0) && (char.IsWhiteSpace((char)this.Peek())))
this.Read();
if (sb.Length > 0)
currentWord = sb.ToString();
else
currentWord = null;
}
public bool hasNextInt()
{
if (currentWord == null)
return false;
int dummy;
return int.TryParse(currentWord, out dummy);
}
public int nextInt()
{
try
{
return int.Parse(currentWord);
}
finally
{
readNextWord();
}
}
public bool hasNextDouble()
{
if (currentWord == null)
return false;
double dummy;
return double.TryParse(currentWord, out dummy);
}
public double nextDouble()
{
try
{
return double.Parse(currentWord);
}
finally
{
readNextWord();
}
}
public bool hasNext()
{
return currentWord != null;
}
}
</code></pre>
|
How to use User Control properties? <p>If I make a UserControl, it has numbers properties. How I can use them? My UserControl contained several Shapes and I need to bind a Foreground property to all Shape.Fill. But I do not know how to do it.</p>
| <p>If you set your properties to Public, you will be able to access your UserControl's properties from outside its own class.</p>
<p>I'm not sure if this is your issue though. Please elaborate on your issue.</p>
|
PHP and OpenID = 500 error <p>Having a really strange problem.</p>
<p>Scenario: PHP5.2.9, IIS7, PHP running as FastCGI. I have a site at test.concentratedtech.com. Click login, enter OpenID credentials, hit "Verify," and immediate 500 error.</p>
<p>Click Back, resubmit the page, works fine.</p>
<p>An IIS failed request trace reveals two messages, below. These messages seems to generally indicate that all is well, which is apparently enough to trigger an error. WTF.</p>
<p>Any ideas whatsoever? As I say, if you hit back and resubmit, it works perfectly - and you can consistently repeat that experience: Every even-numbered attempt works fine, odd-numbered attempts fail with a 500. </p>
<p>ONE:</p>
<pre><code>ModuleName FastCgiModule
Data1 FASTCGI_RESPONSE_ERROR
Data2 Successfully fetched 'http://concentrateddon.myopenid.com/': GET response code 200
ErrorCode 5
ErrorCode Access is denied. (0x5)
</code></pre>
<p>TWO:</p>
<pre><code>ModuleName FastCgiModule
Notification 128
HttpStatus 500
HttpReason Internal Server Error
HttpSubStatus 0
ErrorCode 0
ConfigExceptionInfo
Notification EXECUTE_REQUEST_HANDLER
ErrorCode The operation completed successfully. (0x0
</code></pre>
| <p>Well... I'm a little incredulous but I've been randomly making changes and testing after each one.</p>
<p>I turned PHP's error display to off (normal production setting, but this machine is still in test so errors were being displayed). The problem went away.</p>
<p>I'm surmising that the 200 ("OK") response was somehow being logged as an "error" by the Yadis OpenID library. With an error to display, PHP tossed a 500. With error display off, PHP just sucks it up and keeps going. I guess. </p>
<p>UPDATE: Actually, the trick is the error must have SOMEWHERE to go. I disabled error display and enabled error LOGGING (e.g., to the Windows app event log, but could also be to a file), and all's well.</p>
|
How do I remove the focus rectangle from a silverlight textbox control <p>Does anyone have any ideas on how I can remove the focus rectangle from a silverlight textbox? (I'm talking about the blue rectangle that appears when you click on the texblock to start typing)</p>
<p>I'm looking through the default style and template for the textbox but can't seem to figure out which element to tweak.</p>
<p>Thanks!</p>
| <p>In the template you will find a border called <code>FocusVisualElement</code>. In the base and Unfocused Visual State it has an opacity of 0%. In the focused Visual state it has 100% opacity. You can simply delete the FocusVisualElement if you don't want any border indicating the focus.</p>
<p>This probably looks weird when the MouseOverBorder still appears so you might want to delete that too from the Template, however move the ContentElement it holds to the parent Grid first.</p>
<p>Alternatively you could set the Opacity to 0% for these borders in all states.</p>
|
NHibernate: How do I map mutiple parents' children of a common type into a single table? <p>Is there any way to get NHibernate to let me store multiple ChildObjects in the ChildObjectTable but refer them back to different ParentObjects? Or do I have to create a separate ChildObject class/table for each ParentObject type?</p>
<p>I've boiled this down to the following, I'm trying to map these objects:</p>
<pre><code>public class ParentObjectA
{
public virtual Int64 Id { get; private set; }
public virtual IDictionary<int, ChildObject> Children { get; private set; }
}
public class ParentObjectB
{
public virtual Int64 Id { get; private set; }
public virtual IDictionary<int, ChildObject> Children { get; private set; }
}
public class ChildObject
{
public virtual Int64 Id { get; private set; }
}
</code></pre>
<p>into the following table structure:</p>
<pre><code>ParentObjectTableA
Id bigint
ParentObjectTableB
Id bigint
ChildObjectTable
Id bigint
ParentId bigint
ParentQualifier varchar(50)
</code></pre>
| <p>Perhaps you could create an abstract base class for your parent classes? That way, a given child object could refer back to the abstract type for its parent.</p>
<p>For example, you can have a class called ParentBase, which ParentClassA and ParentClassB extend. Your child object will have a reference back to ParentBase.</p>
<p>This is all possible with NHibernate's various <a href="http://www.hibernate.org/hib%5Fdocs/nhibernate/1.2/reference/en/html%5Fsingle/#persistent-classes-inheritance" rel="nofollow">inheritance models</a>.</p>
|
Querying Many-To-Many relationship with Hibernate Criteria API <p>I've the following many to many relation: <code>File 1 --- * File_Insurer * --- 1 Insurer</code>. I'm trying to query this relation using the Criteria API (Active Record) to get Files that meet ALL specified Insurers (Get all Files where <code>Insurer.Id == 2</code> AND <code>Insurer.Id == 3</code>).</p>
<p><em><strong>Mapping files (parts)</em></strong>:</p>
<h2>File</h2>
<pre><code>[HasAndBelongsToMany(typeof(Insurer),
Table = "Insurer_File", ColumnKey = "IdFile", ColumnRef = "IdInsurer")]
public virtual IList<Insurer> Insurers
{
get { return insurers; }
set { insurers = value; }
}
</code></pre>
<h2>Insurer</h2>
<pre><code>[HasAndBelongsToMany(typeof(File),
Table = "Insurer_File", ColumnKey = "IdInsurer", ColumnRef = "IdFile")]
public virtual IList<File> Files
{
get { return files; }
set { files = value; }
}
</code></pre>
<p><strong>I've tried many options</strong>:</p>
<pre><code>DetachedCriteria dc = DetachedCriteria.For<File>();
dc.SetResultTransformer(new DistinctRootEntityResultTransformer());
dc.CreateCriteria("Insurers").Add(Expression.Eq("Id", long.Parse("2")));
dc.CreateCriteria("Insurers").Add(Expression.Eq("Id", long.Parse("3")));
List<File> searchResults = File.FindAll(dc).ToList<File>();
</code></pre>
<p>That gives me an error: <code>duplicate association path: Insurers</code>.</p>
<p><strong>Next option</strong>:</p>
<pre><code>DetachedCriteria dc = DetachedCriteria.For<File>();
dc.SetResultTransformer(new DistinctRootEntityResultTransformer());
dc.CreateCriteria("Insurers").Add(Expression.And(Expression.Eq("Id", long.Parse("3")), Expression.Eq("Id", long.Parse("2"))));
List<File> searchResults = File.FindAll(dc).ToList<File>();
</code></pre>
<p>The result list is empty (but shouldn't be).</p>
<p><strong>Next option with alias</strong>:</p>
<pre><code>DetachedCriteria dc = DetachedCriteria.For<File>();
dc.SetResultTransformer(new DistinctRootEntityResultTransformer());
dc.CreateAlias("Insurers", "i").Add(Expression.Eq("i.Id", long.Parse("2"))).Add(Expression.Eq("i.Id", long.Parse("3")));
List<File> searchResults = File.FindAll(dc).ToList<File>();
</code></pre>
<p>The result list is empty again - strange.</p>
<p><strong>Next try</strong>:</p>
<pre><code>DetachedCriteria dc = DetachedCriteria.For<File>();
dc.SetResultTransformer(new DistinctRootEntityResultTransformer());
List<long> insurerIds = new List<long>();
insurerIds.Add(2);
insurerIds.Add(3);
dc.CreateCriteria("Insurers").Add(Expression.In("Id", insurerIds));
List<File> searchResults = File.FindAll(dc).ToList<File>();
</code></pre>
<p>This works somehow, but the result set contains a all possible options (OR) - it's not an exact match.</p>
| <p>This has been <a href="http://stackoverflow.com/questions/264339/querying-manytomany-relationship-with-hibernate-criteria">answered already</a> - see my take on it below. The hibernate site seems to be down, but check out this copy of chapter 11, <a href="http://www.kkaok.pe.kr/doc/hibernate/reference/html/queryhql.html" rel="nofollow">HQL</a>, of the Hibernate user guide.</p>
<pre><code>public List<Files> findFilesForInsurers(Insurer... insurers) {
StringBuilder hql = new StringBuilder();
hql.append("select f from Files ff where 1=1 ");
for (int i = 0; i < insurers.length; i++) {
hql.append(String.format(" and :i%d in elements(ff.insurers)", i));
}
Query query = getSession().createQuery(hql.toString());
for (int i = 0; i < insurers.length; i++) {
query.setParameter("i" + i, insurers[i]);
}
return query.list();
}
</code></pre>
<p>Giving HQL like this:</p>
<pre><code>select f from Files ff where 1=1
and :i1 in elements(ff.insurers)
and :i2 in elements(ff.insurers)
</code></pre>
<p>I suspect the SQL you are trying to achieve is something like this, although i couldn't tell you <em>exactly</em> what the above HQL translates into...</p>
<pre><code>select f.* from files f
left outer join files_insurers fi1 on fi1.files_id = f.id
left outer join files_insurers fi2 on fi2.files_id = f.id
where 1 = 1
and fi1.insurers_id = :i1
and fi2.insurers_id = :i2;
</code></pre>
|
How to pull PostBack data into a dynamically added UserControl (.NET)? <p>I have a Panel on my Page:</p>
<pre><code><asp:Panel ID="pnlTest" runat="server" />
</code></pre>
<p>Then I dynamically add a TextBox to it on Page_Load:</p>
<pre><code> TextBox simpleTextBox = new TextBox();
pnlTest.Controls.Add(simpleTextBox);
simpleTextBox.ID = "SimpleTextBox-1";
</code></pre>
<p>Is there a way to pull in the information typed in this TextBox without pulling it directly from Request.Form? I thought I could do something like this after I added it again:</p>
<pre><code>lblPresentResults.Text = myTextBox.Text;
</code></pre>
<p>I know this example seems contrived, but I figured I'd try to eliminate all the other variables in my specific application, especially to ask a question here.</p>
| <p>You need to add the textbox before viewstate loads, such as in Page_Init, and you should be able to do this.</p>
|
What are the ranges of the accelerator on the iPhone? <p>I can't seem to find any documentation online about this, and what I am googling is giving me a lot of conflicting information...</p>
| <p>From <a href="http://www.iphonedevsdk.com/forum/iphone-sdk-development/4822-maximum-accelerometer-reading.html">iphonedevsdk.com</a>:</p>
<blockquote>
<p>The accelerometers used in the first
and second generation iPhones (and I
assume also the iPod touches) operate
in two modes: +/- 2 g, and +/- 8 g.
(Actually, as you observed, they
report accelerations somewhat outside
the nominal range. Accuracy is not
spec'ed outside that range, though.)</p>
<p>Apple operates them in the +/- 2 g
mode. There is a tradeoff: The current
resolution is nominally 0.018 g,
according to the datasheet (though my
first generation iPhone uses
0.018168604, according to a modified version of AccelerometerGraph). In the
+/- 8 g mode, the resolution would be four times cruder.</p>
<p>I assume Apple decided that the finer
resolution would be more useful than
the wider range. (I'd rather see finer
resolution than 0.018 g. So neither of
us is fully satisfied.)</p>
<p>You cannot change the mode with any
published feature of the APIs. Since
they are passing acceleration as a
double, they could theoretically allow
a change in mode, and simply look at
the mode when rescaling the A/D value,
before reporting acceleration. (The
obvious place to set the mode would be
in the call which sets up the
application to receive accelerometer
information.) However, for backward
compatibility, the OS would have to
set the accelerometer mode to +/- 2 g
at the beginning of the application.
And none of the background processes
could be allowed to set the
accelerometer mode.</p>
</blockquote>
|
Python class inclusion wrong behaviour <p>I have into my main.py</p>
<pre><code>from modules import controller
ctrl = controller
help(ctrl)
print(ctrl.div(5,2))
</code></pre>
<p>and the controllor.py is:</p>
<pre><code>class controller:
def div(self, x, y):
return x // y
</code></pre>
<p>when I run my main I got the error:</p>
<pre><code>Traceback (most recent call last):
File "...\main.py", line 8, in ?
print(ctrl.div(5,2))
AttributeError: 'module' object has no attribute 'div'
</code></pre>
<p>WHat is wrong?</p>
| <p>This is very confusing as shown.</p>
<p>When you say</p>
<pre><code>from modules import controller
</code></pre>
<p>You're making the claim that you have a module with a filename of <code>modules.py</code>.</p>
<p>OR</p>
<p>You're making the claim that you have a package named <code>modules</code>. This directory has an <code>__init__.py</code> file and a module with a filename of <code>controller.py</code></p>
<p>You should clarify this to be precise. It looks like you have mis-named your files and modules in the the example code posted here.</p>
<p>When you say</p>
<pre><code>from modules import controller
</code></pre>
<p>That creates a <em>module</em> (not a class) named <code>controller</code>.</p>
<p>When you say</p>
<pre><code>ctrl = controller
</code></pre>
<p>That creates another name for the <code>controller</code> <em>module</em>, <code>ctrl</code>.</p>
<p>At no time to you reference the class (<code>controller.controller</code>). At no time did you create an instance of the class (<code>controller.controller()</code>).</p>
|
WPF: TreeView inside a ComboBox <p>I'm trying to put a TreeView inside a ComboBox in WPF so that when the combo box is dropped, instead of a flat list the user gets a hierarchical list and whatever node they select becomes the selected value of the ComboBox.</p>
<p>I've searched quite a bit for how to accomplish this but the best I could find was only peices of potential soltuions that, because I'm ridiculously new to WPF, I couldn't make work. </p>
<p>I have enough knowledge of WPF and databinding that I can get my data into the treeview and I can even get the treeview inside of the combo box, however what I've been able to accomplish doesn't behave properly at all. I've attached a screenshot to show what I mean. In the screenshot the combo box is "open", so the treeview on the bottom is where I can select a node and the treeview "on top" is being drawn on top of the combobox where I want the text/value of the selected node in the tree to be displayed.</p>
<p>Basically what I don't know how to do is how do I get the treeview's currrently selected node to return its value back up to the combobox which then uses it as its selected value?</p>
<p>Here is the xaml code I'm currently using:</p>
<pre><code> <ComboBox Grid.Row="0" Grid.Column="1" VerticalAlignment="Top">
<ComboBoxItem>
<TreeView ItemsSource="{Binding Children}" x:Name="TheTree">
<TreeView.Resources>
<HierarchicalDataTemplate DataType="{x:Type Core:LookupGroupItem}" ItemsSource="{Binding Children}">
<TextBlock Text="{Binding Path=Display}"/>
</HierarchicalDataTemplate>
</TreeView.Resources>
</TreeView>
</ComboBoxItem>
</ComboBox>
</code></pre>
<p>Screenshot: <img src="http://i.stack.imgur.com/oi95R.jpg" alt="TreeView"> </p>
| <p>For those who still need this control, I've implemented a WPF version of my <a href="http://vortexwolf.wordpress.com/2011/04/29/silverlight-combobox-with-treeview-inside/">Silverlight control</a>. It works only with view models and requires these view models to implement a special interface, but apart of this it's not difficult to use.</p>
<p>In WPF it looks like this:</p>
<p><img src="http://i.stack.imgur.com/08Ubm.png" alt="WPF Combobox with TreeView"></p>
<p>You can download source code and sample application from here: <a href="https://dl.dropboxusercontent.com/u/8047386/WordPress/WpfComboboxTreeview.zip">WpfComboboxTreeview.zip</a></p>
|
WPF data binding and type conversion <p>I have a question regarding WPF binding and converting the data types seen by the UI objects in XAML.</p>
<p>I have a user control that I would like to reuse in different applications. The user control displays a thumbnail image and several TextBlocks to display person demographic information such as name and address. The user control is used in an MVVM design, so itâs bound to a ViewModel specific to the user control.</p>
<p>Following typical MVVM design principles, The ViewModel for the user control is often embedded in other ViewModels to make up a larger UI.</p>
<p>The user control view model expects a certain type (class) as its binding object.
However, the ViewModels in which the UCâs VM in embedded have entirely different object models, so they cannot simply pass-through their data to the UCâs VM. There needs to be a conversion of the parent VMâs data model to the UC VMâs data model.</p>
<p>My question is this: Is there a sanctioned way to perform this conversion?</p>
<p>I looked at IValueConverter and IMultiValueConverter and these do not look like the way to go.</p>
<p>I guess what I need is a sort of shim between the parent VM and the embedded UC VM where the parent VMâs data is converted to the format required by the UC VM.</p>
<p>Or, does it basically come down to I have to write a custom UC VM to handle whatever types the parent VM provides?</p>
| <p>I agree with Ken, I think he has the answer. If you have n many configurations of your data that you want to pass into a common user control, then you want the owner of that configuration of data to convert it into a common form to be bound to the user control.</p>
<p>Each view that uses the control would have a corresponding view model that exposes a property in a common format:</p>
<pre><code>public class SampleViewModel {
...
IUserControlData ControlData
{
get
{
// Do conversion here or do it early and cache it.
}
}
...
}
</code></pre>
<p>Then you would bind that property to your user control in the view</p>
<pre><code><common:CommonUserControl DataContext={Binding Path=ControlData} ... >
</code></pre>
|
Passing enviroment variables to Data Access Layer <p>Every stored procedure we write has to have clientip, serverip, windows username, etc passed on to it. </p>
<p>The question is how do I efficiently pass these to DAL?</p>
| <p>I'm assuming this is a web app in ASP.NET. If that's the case, you have access to all these things in the context of a web request outside of the web application through the following static instance:</p>
<pre><code>System.Web.HttpContext.Current
</code></pre>
<p>If everything you need is standard stuff that you usually have in the Request, Response, and User objects that are available by default at the Page level, then this should be all you need. If you need information that is custom to your web app, then Ben's answer (above) should work.</p>
|
Is there a better Windows command-line shell? <p>CMD.EXE is posing lots of problems for me. I have Cygwin installed and use bash regularly, and I also have the mingwin bash shell that comes with mSysGit, but sometimes I really do need to run things from the Windows shell.</p>
<p>Is there a replacement for the Windows shell that:</p>
<ul>
<li>has a persistent command-line history, available in my next session after I close a session? (as in bash HISTFILE)</li>
<li>remembers what directory I was just in so that I can toggle between two directories? (as in bash cd -)</li>
</ul>
<p>(Or is there a way to enable these features in CMD.EXE?)</p>
<p>I see some has asked about <a href="http://stackoverflow.com/questions/5724/better-windows-command-line-shells">a better windows shell before</a>, but they were asking about cut and paste which is lower in priority for me at this point. It's not the console that's killing me, it's the command-line interpreter.</p>
| <p>Microsoft's just released <a href="http://www.microsoft.com/windowsserver2003/technologies/management/powershell/default.mspx">Powershell</a>. (about 2 years ago)</p>
<p>I've already downloaded it; didn't try it much, but seems a nice tool.</p>
|
Fluent Nhibernate problem (ClassMap) <p>I have the following XML (.hbm): </p>
<pre><code><property name="Geometry" column="the_geom">
<type name="NHibernate.Spatial.Type.GeometryType,NHibernate.Spatial">
<param name="subtype">MULTIPOLYGON</param>
<param name="srid">-1</param>
</type>
</property>
</code></pre>
<p>It´s using Nhibernate Spatial type...
How can I map that property using ClassMap (Fluent Nhibernate) ?</p>
<p>Thanks</p>
| <p>Well, I've not used NHibernate Spatial, but I browsed through the code and it looks like <code>GeometryType</code> inherits from IUserType so you should be able to use it with <code>.CustomTypeIs<></code></p>
<p>For example:</p>
<pre><code>Map(x => x.Geometry, "the_geom").CustomTypeIs<GeometryType>();
</code></pre>
<p>Unless it happens automagically, that probably won't get you your <code>param</code> elements though. I'm not sure of a truly nice way to do this but you can always add an XML alteration like so:</p>
<pre><code>Map(x => x.Geometry, "the_geom").AddAlteration(p => p.AddElement("type")
.WithAtt("name", "NHibernate.Spatial.Type.GeometryType,NHibernate.Spatial")
.AddElement("param")
.WithAtt("name", "subtype")
.WithText("MULTIPOLYGON")
.ParentNode
.AddElement("param")
.WithAtt("name", "srid")
.WithText("-1")
);
</code></pre>
<p>Note that to get the <code>WithText</code> functionality, you'll have to add an extension for <code>XmlElement</code> like so (WithAtt and AddElement are extensions in the FluentNHibernate.Mapping namespace):</p>
<pre><code>public static class XmlExtensions
{
public static XmlElement WithText(this XmlElement element, string text)
{
element.InnerText = text;
return element;
}
}
</code></pre>
|
Do .NET GUI components support HTML (like Java swing does)? <p><a href="http://java.sun.com/docs/books/tutorial/uiswing/components/html.html" rel="nofollow">HTML can be used in Java swing GUI components</a>, like <code>JTextBox</code>, <code>JButton</code>, ... etc.</p>
<p>Is there an equivalent to that in .NET (C#) WinForms? Or at least some simple way of making a single word <strong>bold</strong> inside a textbox without using another GUI component?</p>
| <p>For .Net you'll need to either use a RichTextbox control (and rtf formatting), embed a WebBrowser control, or inherit your own OwnerDrawn control from textbox.</p>
<p>I would be surprised if there aren't third-party controls out there that do that last option for you, but there's nothing "official" for this and you'll have to evaluate them yourself. </p>
|
Copy data from one database to another? <p>I am upgrading a clients app to a newer version, the databases are close but slightly different. I need to figure out a way to transform and copy the data from one table in one database to another table in the new database. Oh geez :(</p>
| <pre><code>INSERT INTO new_db.dbo.TableA
SELECT * FROM old_db.dbo.TableB
</code></pre>
<p>If the tables are the same, this is probably the easiest way.</p>
|
What would cause a query to run slowly when used a subquery, but not when run separately? <p>I have something similar to the following:</p>
<pre><code>SELECT c.id
FROM contact AS c
WHERE c.id IN (SELECT s.contact_id
FROM sub_table AS s
LEFT JOIN contact_sub AS c2 ON (s.id = c2.sub_field)
WHERE c2.phone LIKE '535%')
ORDER BY c.name
</code></pre>
<p>The problem is that the query takes a very very very long time (>2minutes), but if I take the subquery, run it separately, implode the ids and insert them into the main query, it runs in well less than 1 second, including the data retrival and implosion.</p>
<p>I have checked the explains on both methods and keys are being used appropriately and the same ways. The subquery doesn't return more than 200 IDs.</p>
<p>What could be causing the subquery method to take so much longer?</p>
<p>BTW, I know the query above can be written with joins, but the query I have can't be--this is just a simplified version.</p>
<p>Using MySQL 5.0.22.</p>
| <p>Sounds suspiciously like <a href="http://bugs.mysql.com/bug.php?id=32665" rel="nofollow">MySQL bug #32665: Query with dependent subquery is too slow</a>.</p>
|
In an onclick handler, how can I detect whether shift was pressed? <p>How can I write an onclick handler that does one thing for regular clicks and a different thing for shift-clicks?</p>
| <p>You can look at the click event's shiftKey property.</p>
<pre><code>window.addEventListener("click",
function(e){
if(e.shiftKey) alert("Shift, yay!");
},
false);
</code></pre>
|
Format of Time registry value in HKCU\Software\Microsoft\Office\Common\Offline\Files entries <p>What is the information in the Time registry value in the entries in HKEY_CURRENT_USER\Software\Microsoft\Office\Common\Offline\Files?</p>
<p>I see (example):0x01c99b84|0x11990880</p>
<p>I'm pretty sure that the first "half" (prior to the bar character) is the file modified time (probably in File Time format. I'm not sure what the 2nd "half" of the entry is.</p>
<p>Entries were made by SharePoint checkouts</p>
| <p><a href="http://blogs.msdn.com/oldnewthing/archive/2003/09/05/54806.aspx" rel="nofollow">http://blogs.msdn.com/oldnewthing/archive/2003/09/05/54806.aspx</a> is a good overview of different time formats. In this case, it looks like an NT time (100 ns intervals since Jan 1, 1600.)</p>
<p>Filetime is 64-bit. You need to combine the two 32-bit values together, i.e. 0x01c99b8411990880.</p>
<p>Is this registry key documented? If not, you shouldn't be depending on it.</p>
|
TinyMCE - external toolbar position <p>I am trying to work with TinyMCE in creating a multi-textbox, click-to-edit type graphical content editor. I have got TinyMCE to the point where I can add and remove them, position and size them, click to edit them, and so forth - but one thing is bothering me and that is the toolbar.</p>
<p>I have an external toolbar that I'm trying to position along the bottom edge of the page, along with my "Save and Close" button and some other toolbuttons. The external toolbar is created by TinyMCE in a DIV with class <code>"mceExternalToolbar"</code>. I tried setting <code>position: fixed</code> and <code>left:</code> and <code>top:</code> attributes in the page stylesheet, but to no avail - TinyMCE sets <code>position: absolute</code> and <code>top: -28px</code> on the DIV when it creates it.</p>
<p>I cannot modify the source code for TinyMCE due to project restrictions, but I can supplement it with extra CSS files.</p>
<p>Can anyone point me in the right direction to get the toolbar positioned properly?</p>
| <p>The CSS selectors in the provided stylesheets are overriding the selectors that you're writing. What you need to do is either target the toolbar element with a selector of greater specificity:</p>
<pre><code>body div.mceExternalToolbar {
position: fixed ;
top: -28px ;
};
</code></pre>
<p>Or use the <code>!important</code> directive to override it:</p>
<pre><code>.mceExternalToolbar {
position: fixed !important ;
top: -28px !important ;
}
</code></pre>
<p>For more detail about both selector specificity and <code>!important</code>, see <a href="http://www.w3.org/TR/CSS21/cascade.html#specificity">the W3C's documentation</a>.</p>
|
how do i use a ado.net dataservice to check if a row exists? <pre><code>var svc = new LocationDataServiceContext();
var q = from c in svc.LocationTable
where c.ID == int.Parse(location.ID)
select c;
if (q.ToArray().Length == 0)
</code></pre>
<p>id there a neater way to do this?</p>
| <p>yes, I believe so...</p>
<pre><code> var svc = new LocationDataServiceContext();
if (svc.LocationTable.SingleOrDefault(c => c.ID == int.Parse(location.ID) != null))
{
}
</code></pre>
<p>I thought there was an Exist() method... but I guess not.</p>
|
What's the best way to prevent adding a record whose primary key is already present in mnesia? <p>Suppose I've got a simple record definition:</p>
<pre><code>-record(data, {primary_key = '_', more_stuff = '_'}).
</code></pre>
<p>I want a simple function that adds one of these records to a mnesia database. But I want it to fail if there's already an entry with the same primary
key.</p>
<p>(In the following examples, assume I've already defined</p>
<pre><code>db_get_data(Key)->
Q = qlc:q([Datum
|| Datum = #data{primary_key = RecordKey}
<- mnesia:table(data),
RecordKey =:= Key]),
qlc:e(Q).
</code></pre>
<p>)</p>
<p>The following works, but strikes me as sort of ugly ...</p>
<pre><code>add_data(D) when is_record(D, data)->
{atomic, Result} = mnesia:transaction(fun()->
case db_get_data(D#data.primary_key) of
[] -> db_add_data(D);
_ -> {error, bzzt_duplicate_primary_key}
end
end),
case Result of
{error, _} = Error -> throw(Error);
_ -> result
end.
</code></pre>
<p>This works too, but is also ugly:</p>
<pre><code>add_data(D) when is_record(D, data)->
{atomic, Result} = mnesia:transaction(fun()->
case db_get_data(D#data.primary_key) of
[] -> db_add_data(D);
_ -> throw({error, bzzt_duplicate_primary_key})
end
end).
</code></pre>
<p>It differs from the above in that the above throws</p>
<pre><code>{error, bzzt_duplicate_primary_key},
</code></pre>
<p>whereas this one throws</p>
<pre><code>{error, {badmatch, {aborted, {throw,{error, bzzt_duplicate_primary_key}}}}}
</code></pre>
<p>So: is there some convention for indicating this sort of error? Or is there a built-in way that I can get mnesia to throw this error for me?</p>
| <p>I think both of them are fine, if you only make your code more pretty, like:</p>
<pre><code>add_data(D) when is_record(D, data)->
Fun = fun() ->
case db_get_data(D#data.primary_key) of
[] -> db_add_data(D);
_ -> throw({error, bzzt_duplicate_primary_key})
end
end,
{atomic, Result} = mnesia:activity(transaction, Fun).
</code></pre>
<p>or </p>
<pre><code>add_data(D) when is_record(D, data)->
Fun = fun() ->
case db_get_data(D#data.primary_key) of
[] -> db_add_data(D);
_ -> {error, bzzt_duplicate_primary_key}
end
end,
{atomic, Result} = mnesia:activity(transaction, Fun),
case Result of
{error, Error} -> throw(Error);
_ -> result
end.
</code></pre>
<p>Do you throw errors or return errors? I would return an error myself. We split out code out into mnesia work units - a module with a set of functions that perform basic mnesia activities not in transactions, and an api module which 'composes' the work units into mnesia transactions with functions that look very similar to the one above.</p>
|
Error Handling in 3 layered architecture <p>How do I implement error handling elegantly? For example, my data access layer can potentially throw 2 types of errors:
1) not authorized access, in which case the page should hide everything and just show the error message
2) errors that inform the user that something like this already exists in the database (say name not unique - for example), and in this case I wouldn't want to hide everything.</p>
<p>EDITED:</p>
<p>As a result of some comments here I devised that I should create derived specialized exception types, such as NotAuthorizedException, DuplicateException, etc etc.... it's all fine and dandy, however I can see 2 problems potentially:</p>
<p>1) Every stored proc has a return field p_error where it contains an error message. Upon getting the data from DB, I need to check this field to see what type of an error has been returned, so I can throw an appropriate exceptions. So, I still need to store my error types/error messages somewhere.....In other words, how do I should the exact message to the user (at certain times I need to) w/o checking the p_error field first. WHich brings me back to error object. Anyone?</p>
<p>2) I can this potentially turning into a nightmare where the number of exceptions equals the number of error message types.</p>
<p>Am I missing something here?</p>
<p>Much thanks to everyone!</p>
| <p>You should check out the exception handling block in <a href="http://msdn.microsoft.com/en-us/library/dd203099.aspx" rel="nofollow">Enterprise Library</a>. Lots of good tips and codeware surrounding wrapping exceptions and passing them between layers.</p>
|
Unity Framework's container type's constructor param's type <p>Currently I am trying to use a config file to give Unity Framework information that looks like this...</p>
<pre><code><configuration>
<unity>
<typeAliases>
<typeAlias alias="singleton" type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager, Microsoft.Practices.Unity, Culture=neutral, Version=1.1.0.0, PublicKeyToken=31bf3856ad364e35" />
</typeAliases>
<containers>
<container>
<types>
<type type="Common.ISharedConfiguration, Common, Version=3.1.0.0, Culture=neutral, PublicKeyToken=1111111111111111" mapTo="Common.SharedConfigurationManager, Common, Version=3.1.0.0, Culture=neutral, PublicKeyToken=1111111111111111">
<lifetime type="singleton" />
<typeConfig extensionType="Microsoft.Practices.Unity.Configuration.TypeInjectionElement, Microsoft.Practices.Unity.Configuration, Version=1.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
<constructor>
<param name="OurEnumChoice" parameterType="MyProjectsEnum" >
<value value="MyProjectsEnum.OurFirstConstant" type="MyProjectsEnum"/>
</param>
</constructor>
</typeConfig>
</type>
</types>
</container>
</containers>
</unity>
</configuration>
</code></pre>
<p>If I choose something like <code>System.String</code> and have my concrete class have a construtor of string this config file info for Unity works great. The moment I choose to use an <code>Enum</code> instead of string Unity throws an error like this...</p>
<blockquote>
<p>Could not load type MyProjectsEnum from assembly Microsoft.Practices.Unity.Configuration, Version=1.1.0.0, Culture=neutral, PublicKeyToken=31bf33856ad364e35</p>
</blockquote>
<p>I think I need an understanding of what I can pass as an understood type by Unity beyond simple types through this configuration process.</p>
| <p>You need to specify fully qualified type name for both 'parameterType' and 'type' attributes. Much the same you did for 'typeAlias' node. By default, Unity looks up its own assembly for unqualified types.</p>
|
max number of concurrent file downloads in a browser? <p>Two related questions:</p>
<ol>
<li><p>What are the maximum number of concurrent files that a web page is allowed to open (e.g., images, css files, etc)? I assume this value is different in different browsers (and maybe per file type). For example, I am pretty sure that javascript files can only be loaded one at a time (right?).</p></li>
<li><p>Is there a way I can use javascript to query this information?</p></li>
</ol>
| <p>For Internet Explorer see <a href="http://msdn.microsoft.com/en-us/library/cc304129%28VS.85%29.aspx" rel="nofollow" title="MSDN">this MSDN article</a>. Basically, unless the user has edited the registry or run a 'internet speedup' program, they are going to have a maximum of two connections if using IE7 or earlier. IE8 tries to be smart about it and can create up to 6 concurrent connections, depending on the server and the type of internet connection. In JavaScript, on IE8, you can query the property <strong>window.maxConnectionsPerServer</strong>.</p>
<p>For Firefox, the default is 2 for FF2 and earlier, and 6 for FF3. See <a href="http://kb.mozillazine.org/Network.http.max-persistent-connections-per-server" rel="nofollow">Mozilla documentation</a>. I'm not aware of anyway to retrieve this value from JavaScript in FF.</p>
<p>Most HTTP servers have little ability to restrict the number of connections from a single host, other than to ban the IP. In general, this isn't a good idea, as many users are behind a proxy or a NAT router, which would allow for multiple connections to come from the same IP address.</p>
<p>On the client side, you can artificially increase this amount by requesting resources from multiple domains. You can setup www1, www2, etc.. alias which all point to your same web server. Then mix up where the static content is being pulled from. This will incur a small overhead the first time due to extra DNS resolution.</p>
|
Stack-based palindrome checker <p>i have a problem with my program. It should be program that recognize palindome through the stack. Everything works great, only thing that don't work is printing stacks(original and reversed) after the funcion is done.
Here is my entire code, and the problem is at case d and e:</p>
<pre><code>#include <iostream>
using namespace std;
const int MAXSTACK = 21;
class stack {
private:
int stop;
char stk[MAXSTACK];
public:
stack();
~stack();
stack(const stack& s);
void push(const char c);
char pop();
char top(void);
int emptystack(void);
int fullstack(void);
void stack_print(void);
int stack::create(void);
};
stack::stack()
{
stop = 0;
}
stack::~stack() { }
stack::stack(const stack& s)
{
stop = s.stop;
strcpy(stk,s.stk);
}
void stack::push(const char c)
{
stk[stop++] = c;
}
char stack::pop()
{
return stop--;
}
char stack::top(void)
{
return stk[stop - 1];
}
int stack::emptystack(void)
{
return !stop;
}
int stack::fullstack(void)
{
return stop == MAXSTACK;
}
void stack::stack_print(void)
{
for (int i=0; i<stop; i++)
cout<<stk[i];
cout<<endl;
}
int stack::create(void)
{
return !stop;
}
char menu()
{
char volba;
cout<<"\n";
cout<<" **********.\n";
cout<<"\n";
cout<<" a ... make new containers\n";
cout<<" b ... delete content\n";
cout<<" c ... enter string\n";
cout<<" d ... print on screen first stack\n";
cout<<" e ... print on screen first stack\n";
cout<<" f ... is it palindrom\n";
cout<<" x ... exit\n";
cout<<"\n your choice : ";
cin >> volba;
return volba;
}
int main() {
char palindrome[MAXSTACK];
char volba;
stack original,reversed;
int stackitems = 0,i;
//cin.getline(palindrome,MAXSTACK);
do{
volba = menu();
switch (volba)
{
case'a':
{
original.create();
reversed.create();
cout<<"done'";
break;
}
case'b':
{
original.emptystack();
reversed.emptystack();
cout<<"empty";
break;
}
case'c':
{
cout<<"enter your string"<<endl;
cin.get();
//cin.get();
cin.getline(palindrome,MAXSTACK);
for(int o = 0; o < strlen(palindrome); o++)
if (isalpha(palindrome[o]))
{
original.push(tolower(palindrome[o]));
stackitems++;
}
original.stack_print();
break;
}
case'd':
{
original.~stack();
for(int g = 0; g < strlen(palindrome); g++)
original.push(tolower(palindrome[g]));
original.stack_print();
}
/*//cin.getline(palindrome,MAXSTACK);
for(int g = 0; g < strlen(palindrome); g++)
if (isalpha(palindrome[g]))
{
original.push(tolower(palindrome[g]));
stackitems++;
}
}
original.stack_print();*/
break;
/*{
cout<<"original: ";
original.stack_print();
break;
}*/
break;
case'e':
{
cout<<"reversed:"<<endl;
for( i = 0; i < stackitems; i++) {
reversed.push(original.top());
original.pop();
}
reversed.stack_print();
}
break;
case'f':
{
for( i = 0; i < stackitems / 2; i++) {
reversed.push(original.top());
original.pop();
}
if (stackitems % 2)
original.pop();
while (!original.emptystack()) {
if (original.top() != reversed.top()) break;
original.pop(); reversed.pop();
}
if (original.emptystack())
cout << "it is palindrom\n";
else
cout << "not palindrom\n";
break;
}
default:cout<<"!??!";
}
} while(volba!='x');
}
</code></pre>
| <p>You've explicitly called your stack's destructor. There is almost never a good reason to do this. If the stack is a local ("on the stack", hee hee), the compile will do it for you. If it's on the heap, created with <code>new</code>, call <code>delete</code> on it, which will cause the compiler to call the destructor.</p>
<pre><code> case'd':
{
original.~stack();
</code></pre>
|
why does my JScript (windows script host) exit with 0 on an uncaught exception? <p>I have some JScript which does some stuff with an ODBC connection. An exception was thrown by the ODBC ActiveXObject object and not caught in my script. I expected that the script would exit with an non 0 value but it didn't. Anyone know why this is the case and how to get it to exit with a non 0 value on an uncaught exception?</p>
| <p>The JScript engine can be thought of as a virtual machine. If the JScript engine itself or the script host were to have some form of catastrophic failure you could expect to get a non zero exit code (for example an the script host couldn't find one of the DLLs it needs).</p>
<p>However if the script program being run on this 'VM' throws an exception even an unhandled one that does not constitute a failure in the engine or the host.</p>
<p>What you can do is place the whole script in a try block and then just throw the exception in the catch. The scripting engine will handle this thrown exception exactly as you wanted the original handled:-</p>
<pre><code>try
{
// the rest of your script
}
catch(e)
{
throw(e); // returns nonzero exit code
}
</code></pre>
|
How do you generate a database schema diagram in visual studio (express)? <p>Right now all I did was use the Dataset designer and dragged tables into it from the Database Explorer. It works (for what I need anyway) but it feels like it's a misuse of Datasets. (Actually I'm not really sure how to use Datasets or what the intended usage is, I was planning on using LINQ2SQL to interact with the DB)</p>
<p>Is this ok? I only need it for the designer view and it's a very simple DB layout (just 4 tables). I'm sure there's other tools out there, but is there anything integrated into VS Express that I should be using instead?</p>
| <p>You download MS SQL Express with the SQL Studio Management Studio Express. Only in the Studio Express can you connect to the server, select the database, open the database diagrams and edit diagrams.</p>
<p>Then, you can drag and drop the entire set of Tables in to Linq to SQL. Entity Framework is nice, but I have yet to get it to render my tables well yet. I would stick to Linq to SQL until they release another upgrade to EF (easier for you). </p>
|
Connect Visual Studio 2008 to Virtual PC 2007 <p>How do I go about connecting Visual Studio on my host machine to Window Server 2008 that is running in VPC? I basically want to be able to deploy ASP.Net apps to it as well as access the apps from the host machines browser.</p>
| <p>Treat the VPC in exactly the same way as if it were a separate physical machine.</p>
<p>VS and the browser on the host will simply use HTTP to communicate to the IIS/ASP.NET instance on the VPC guest.</p>
|
Objective-C: Why am I getting a compile error when importing a header file? <p>I'm curious what some reasons might be as to getting a compiler error for simply importing a header file. If I comment it out, everything compiles just fine -- the header/implementation for the class I'm trying to import into one of my UIViewController's get passed the compiler without any warnings. However, as soon as I include it, I get a multitude of errors.</p>
<p>I'm trying to use Apple's Reachability app in my own code, and by doing something like:</p>
<pre><code>#import "Reachability.h"
</code></pre>
<p>I get a ton of:</p>
<pre><code>error: syntax error before 'target'
error: syntax error before 'SCNetworkReachabilityFlags'
error: syntax error before 'SCNetworkReachabilityRef'
error: syntax error before 'SCNetworkReachabilityRef'
fatal error: method definition not in @implementation context
</code></pre>
<p>It's mostly complaining regarding:</p>
<pre><code>static void ReachabilityCallback(SCNetworkReachabilityRef target, SCNetworkReachabilityFlags flags, void *info);
- (BOOL)isNetworkAvailableFlags:(SCNetworkReachabilityFlags *)outFlags;
- (SCNetworkReachabilityRef)reachabilityRefForHostName:(NSString *)hostName;
- (CFRunLoopRef)startListeningForReachabilityChanges:(SCNetworkReachabilityRef)reachability onRunLoop:(CFRunLoopRef)runLoop;
</code></pre>
<p>Any idea why this is only happening when I try to import the header file?</p>
| <p>It sounds like you probably need to </p>
<pre><code>#import <SystemConfiguration/SystemConfiguration.h>
</code></pre>
|
Does IIS or ASP.NET do any sort of connection throttling? <p>I am trying to create an ASP.NET Web Service which I can use to show the difference between implementing a Web Method asynchronously vs. synchronously. It is sort of a proof-of-concept that I can use to show how writing things asynchronously can make an app more scalable. To make the comparison, I implemented two methods, RunSqlSync and RunSqlAsync . Like this:</p>
<pre><code>[WebMethod]
public int RunSqlSync(string sql)
{
// call SQL synchronously
}
[WebMethod]
public IAsyncResult BeginRunSqlAsync(string sql, AsyncCallback callback, object state)
{
// call SQL asynchronously
}
[WebMethod]
public int EndRunSqlAsync(IAsyncResult result)
{
}
</code></pre>
<p>I would expect that I would be able to process more concurrent requests by using the Async version of the methods, especially if the SQL call took a while to complete. Unfortunately, for both methods, it seems that I hit a request/sec limit (the limit depends on the latency of the SQL calls) and I am not even close to maxing out my CPU. When I increase the number of requests being sent to the web service (by increase the number of users using in my Ocracoke Load Test), the average response time just increases without changing the actual TPS throughput. I instrumented the Web Service internally to measure the time it takes for a request to complete, and within my code, each individual request is being processed in the same time, regardless of load. This makes me think that ASP.NET is somehow throttling. Does anyone know why this would happen?</p>
| <p>you can set the max pool size in the .net sql connection string call. I believe the default is 20 connections max so if your hitting that then it would only allow those to be used and essentially you would get the same results. Here is an article on connection pooling.</p>
<p><a href="http://www.15seconds.com/Issue/040830.htm" rel="nofollow">http://www.15seconds.com/Issue/040830.htm</a></p>
|
How do I render text on to a square (4 vertices) in OpenGL? <p>I'm using Linux and GLUT. I have a square as follows:</p>
<pre><code>glVertex3f(-1.0, +1.0, 0.0); // top left
glVertex3f(-1.0, -1.0, 0.0); // bottom left
glVertex3f(+1.0, -1.0, 0.0); // bottom right
glVertex3f(+1.0, +1.0, 0.0); // top right
</code></pre>
<p>I guess I can't use <code>glutBitmapCharacter</code>, since this is <a href="http://stackoverflow.com/questions/14318/using-glut-bitmap-fonts">only ideal for 2D ortho</a>.</p>
<p>Simple enough, I'd like to render "Hello world!" anywhere on said square. Should I create a texture and then apply it to the vertices using <code>glTexCoord2f</code>?</p>
| <p>The simplest way is to load a font map from a image, such as those generated by the <a href="http://www.lmnopc.com/bitmapfontbuilder/" rel="nofollow">bitmap font builder</a> (I know it's windows but I can't find one for linux), eg:</p>
<p><img src="http://i.stack.imgur.com/VFKM2.gif" alt="bitmap font example"></p>
<p>The example is a 256x256 gif, though you may what to convert it to a png/tga/bmp. It's full ASCII mapped gird, 16x16 characters. Load the texture and use glTexCoord2f to line it up on your quad, and you should be good to go.</p>
<p>Here's an example using a bitmap of the above:</p>
<pre><code>unsigned texture = 0;
void LoadTexture()
{
// load 24-bit bitmap texture
unsigned offset, width, height, size;
char *buffer;
FILE *file = fopen("text.bmp", "rb");
if (file == NULL)
return;
fseek(file, 10, SEEK_SET);
fread(&offset, 4, 1, file);
fseek(file, 18, SEEK_SET);
fread(&width, 1, 4, file);
fread(&height, 1, 4, file);
size = width * height * 3;
buffer = new char[size];
fseek(file, offset, SEEK_SET);
fread(buffer, 1, size, file);
glEnable(GL_TEXTURE_2D);
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, buffer);
fclose(file);
printf("Loaded\n");
}
void DrawCharacter(char c)
{
int column = c % 16, row = c / 16;
float x, y, inc = 1.f / 16.f;
x = column * inc;
y = 1 - (row * inc) - inc;
glBegin(GL_QUADS);
glTexCoord2f( x, y); glVertex3f( 0.f, 0.f, 0.f);
glTexCoord2f( x, y + inc); glVertex3f( 0.f, 1.f, 0.f);
glTexCoord2f( x + inc, y + inc); glVertex3f( 1.f, 1.f, 0.f);
glTexCoord2f( x + inc, y); glVertex3f( 1.f, 0.f, 0.f);
glEnd();
}
</code></pre>
|
How can I keep my Ajax call from posting back to the server when using Prototype? <p>I am trying to keep my <a href="http://en.wikipedia.org/wiki/Ajax_%28programming%29" rel="nofollow">Ajax</a> call from posting back to the server when using <a href="http://en.wikipedia.org/wiki/Prototype_JavaScript_Framework" rel="nofollow">Prototype</a>.</p>
<h3>Code:</h3>
<pre><code>echo " <a href='my.php?action=show&amp;id=".$fid."'
onclick=\"return display('".$fid."');\"> ";
echo "" .$fname."</a> ";
</code></pre>
<p>How can I do this?</p>
| <p>Your <code>display()</code> function should <code>return false;</code> to prevent the default link action from happening.</p>
|
Code signing Windows Mobile applications - Recommendations? <p>I'm tasked with obtaining a code signing certificate. Our application actually consists of 2 complementary components: a desktop application and a Windows Mobile application designed to run on PDAs. Currently our mobile install (via CAB file) triggers the security prompts in Windows Mobile 6 and it is confusing to our users. We want to eliminate those security warnings.</p>
<p>It seems easy enough to find certificates to sign a desktop application -- which we also need -- but I'm less clear about whether or not such a code signing certificate will fix our Windows Mobile problems. My ideal solution is 1 certificate that can sign both the desktop and mobile apps.</p>
<p>So much I read about mobile app signing revolves around Mobile2Market and crazy multi-step signing procedures -- even sending your executables in to have them signed and returned. I think this is mainly aimed at the mobile phone market, where cellular providers have tightly locked down the phones against non-signed apps.</p>
<p>Our devices are primarily Windows Mobile 6 PDAs (iPAQ 210) that come pre-configured with One Tier security. We don't want to provision devices, install a certificate, etc (unless absolutely necessary). We just want to sign the files and forget about it.</p>
<p>Has anyone done something similar and have any recommendations? I'm especially interested in lower-cost solutions that don't involve paying lots of money to Verisign -- something like Comodo perhaps.</p>
| <p>You can self-sign the binaries, but the end user will have to install your certificate into the device store, and that is probably going to be more painful, and more expensive in support costs than to just get a real signature.</p>
<p>What you need is to purcahse a <a href="http://www.verisign.com/code-signing/content-signing-accounts/microsoft-windows-mobile/index.html" rel="nofollow">M2M certificate from Verisign</a>. They will send you a USB key that contains some sort of key material, and you will use it and their application to sign your binary.</p>
<p>What level of security gives what prompts is <a href="http://msdn.microsoft.com/en-us/library/ms839681.aspx" rel="nofollow">outlined here</a>.</p>
|
how to get NHibernate aggregate function sum() to return decimal? <p>I can't get sum() to return decimal and it always returns int64 truncating the decimals. I have Googled for a whole day but still can't find a real work around. I have a DB table called ProductPurchase with </p>
<p>QtyPurchased(int)
and
UnitPurchasePrice(money) columns, </p>
<p>these are mapped to a C# POCO object using NHibernate,
where
QtyPurchase is a int and UnitPurchasePrice is a decimal property. </p>
<p>I have the following HQL query where I want to get the total purchase amount for a given day:</p>
<p>select sum(detail.QtyPurchased * detail.UnitPurchasePrice)
from Domain.Entities.ProductPurchase AS detail
where datediff("day", detail.PurchaseDate, :trading_date) = 0</p>
<p>Now for what ever reason, the query.UniqueResult always returns an Int64 integer, truncating the decimals, whereas the SQL generated obviously returns the correct number complete with decimals. Can someone shed somelight on how to get this to return decimal?</p>
<p>I have noticed that if I use SQL (i.e. CreateSqlQuery), I can get the decimal back. Is this a bug with Nhibernate?</p>
<p>Thanks heaps</p>
<p>Steven Kuo</p>
| <p>Inverting the order of the factors did it for me: (price * qty) instead of (qty * price). </p>
<p>I guess it must be checking just the first parameter type, please fill a <a href="http://nhjira.koah.net/secure/Dashboard.jspa" rel="nofollow">JIRA issue</a> if this workaround worked for you.</p>
|
Writing NUnit test code <p>How can I write code for the below method so that it can be tested in NUnit? How to handle a <code>Hashtable</code>?</p>
<pre><code>public DataSet MySampleMethod(int param1, string param2, Hashtable ht)
{
if(ht==null)
{
ht = new Hashtable();
}
ht.Add("testKey","testData");
DataSet ds = new DataSet();
ds.Tables.Add();
ds.Tables[0].Columns.Add("Column1");
ds.Tables[0].Columns.Add("Column2");
ds.Tables[0].Columns.Add("Column3");
DataRow dr = ds.Tables[0].NewRow();
dr["Column1"] = "My column 1";
dr["Column2"] = "My column 2";
dr["Column3"] = "My column 3";
ds.Tables[0].Rows.Add(dr);
DataRow dr1 = ds.Tables[0].NewRow();
dr1["Column1"] = param1.ToString();
dr1["Column2"] = param2;
dr1["Column3"] = ht["testKey"].ToString();
ds.Tables[0].Rows.Add(dr1);
return ds;
}
</code></pre>
| <p>First question to ask is: Why do I need to write this method? What's it doing for me? </p>
<p>Give the method a more human-friendly name.
From what I can see, the method takes in an integer, a string and a hashtable. The method is then expected to return a dataset containing a solitary table with 3 columns,</p>
<ul>
<li>the first row contains values like {"My Column {ColumnNo}"..}</li>
<li>the second row of which contains the [ intParam.ToString(), stringParam, hashtable["testKey"] ]</li>
</ul>
<p>Testing this method should be trivial,
Test#1:</p>
<ol>
<li>Arrange : Create known inputs (an int I , string S, a hashtable with some "testData"=> Y)</li>
<li>Act : Call the method and obtain the resulting dataset</li>
<li>Assert : Query the dataset to see if it has the single table with 2 records. Inspect the contents of the records of the table to see if they contain the header row and the row with [I, S, Y].</li>
</ol>
<p>Test#2:
Similar to above test, except that you pass in null for the hashtable parameter.</p>
<p>That's all I could see based on the snippet you posted.
HTH</p>
<p><strong>Update</strong>: Not sure what you mean here by "handle hashtable" or "write test fixture code for hashtable" ? The hashtable is just a parameter to your function.. so I reckon the test would look something like this (Forgive the bad naming and lack of constants... can't name them unless I know what this function is used for in real life)</p>
<pre><code>[Test]
public void Test_NeedsABetterName()
{
int intVal = 101; string stringVal = "MyString"; string expectedHashValue = "expectedValue";
Hashtable ht = new Hashtable();
ht.Add("testKey", expectedHashValue);
Dataset ds = MySampleMethod(intVal, stringVal, ht);
Assert.AreEqual(1, ds.Tables.Count);
Assert.AreEqual(2, ds.Tables[0].Rows.Count);
// check header Row1.. similar to Row2 as shown below
DataRow row2 = ds.Tables[0].Rows[1];
Assert.AreEqual(intVal.ToString(), row2["Column1"]);
Assert.AreEqual(stringVal, row2["Column2"]);
Assert.AreEqual(expectedHashValue, row2["Column3"])
}
</code></pre>
<p>I'd recommend getting a good book like Pragmatic Unit Testing in C# with NUnit or one from the list <a href="http://stackoverflow.com/questions/31837/best-books-about-tdd">here</a> to speed you up here.</p>
|
How to add a classpath entry when executing the app with exec plugin <p>One of the components is looking for the persistence.xml using the java.class.path system property. It is desired to keep this file separately from jars in the /conf folder. </p>
<p>When running the app with exec:exec, classpath is formed from the path to the main jar plus path to every dependency. I can't seem to figure out how to add the /conf entry to the classpath. </p>
<p>My command line looks like this:</p>
<p>mvn exec:exec -Dexec.executable="java" -Dexec.args="-classpath %classpath com.testjar.App"</p>
<p>I tried "arguments" parameter but the execution fails if I try to append anything to %classpath.
I also tried to add a Class-Path entry to the manifest by specifying </p>
<pre><code><manifestEntries>
<Class-Path>/conf</Class-Path>
</manifestEntries>
</code></pre>
<p>in the configuration for maven-jar-plugin, but the entry in the manifest has no effect on the value of java.class.path property.</p>
| <p>You may use the element 'resources' in the 'build' section of your POM file. For example</p>
<pre><code><build>
<resources>
<resource>
<directory>src/main/resources/config</directory>
<includes>
<include>persistence.xml</include>
</includes>
<targetPath>/</targetPath>
</resource>
</resources>
...
</build>
</code></pre>
<p>This will copy the persistence.xml into the build output directory, i.e. it will place the persistence.xml on the classpath.</p>
|
Framework Vs. API <p>Now, this may be a silly question but sometimes the terms Framework and API are used interchangeably. The way I see it is that a Framework is a bigger more generic thing, containing many API's, that could be used for various programming tasks (for example, the .NET Framework.) An API is smaller and more specialized (for example, the Facebook API.) Anyone want to share their insights on the matter?</p>
<p>And take for instance that Microsoft call .NET a Framework whereas Sun calls theirs a Platform ... so could it be also a business/marketing decision as to how call a "collection of libraries."?</p>
| <p><a href="http://en.wikipedia.org/wiki/Design_Patterns_(book)" rel="nofollow">Design Patterns</a> provide the following definitions:</p>
<ul>
<li>toolkits: "often an application will incorporate classes from one or more libraries of predefined classes called toolkits. A toolkit is a set of related and reusable classes designed to provide useful, general-purpose functionality".</li>
<li>frameworks: "a framework is a set of cooperating classes that make up a reusable design for a specific class of software".</li>
</ul>
<p>The key here is that while toolkits (APIs) can be useful in many domains, frameworks are geared to solve issues for <em>specific</em> classes of problems, that can be customized "by creating application specific subclasses of abstract classes of the framework".</p>
<p>Moreover, and maybe more importantly, "the framework dictates the architecture of your application": Inversion Of Control is one of the characteristics of frameworks (see <a href="http://martinfowler.com/articles/injection.html" rel="nofollow">Martin Fowler on this</a>); instead of having your application call specific APIs to implement a specific behavior, it's the framework that calls your code. </p>
|
how to use web service on flex? <p>i am going to use https://adwords.google.com/api/adwords/v13/AdService?wsdl .
google adwords apI to my project . so how do i use that ? do u know any example plz refer me</p>
| <p>Thanks for the question, I liked it.</p>
<p>Here is a tutorial which i am going to follow myself now. It looks quite straight forward and used with Flex 3.0:</p>
<p><a href="http://livedocs.adobe.com/flex/3/html/help.html?content=data_access_3.html" rel="nofollow">http://livedocs.adobe.com/flex/3/html/help.html?content=data_access_3.html</a></p>
<p>If you want to obtain a free serial code for Flex also for educational or out of work developers visit this link for info:</p>
<p>https://freeriatools.adobe.com/</p>
<p>Cheers,</p>
<p>Andrew</p>
|
How do you mock UnitOfWork from Rhino.Commons? <p>My application is using Rhino.Commons - NHRepository and UnitOfWork. I like the With.Transaction() syntax for transactions and have been using it for some time.</p>
<p>But I ran into a problem - how do I mock a UnitOfWork for testing? Especially this is causing trouble for me: </p>
<pre><code>With.Transaction(() => Repositories.TwinfieldSpooler.Update(spool));
</code></pre>
<p>I can mock repositories with Rhino.Mocks, but how can I easily mock UnitOfWork for this kind of code?</p>
| <p>With.Transaction uses UnitOfWork.Current property. UnitOfWork is a static class -- you can't mock it with RhinoMocks. </p>
<p>UnitOfWork.Current is a public static property, so you can swap it out. Unfortunately, the setter is internal.</p>
<p>I see 3 options for you:</p>
<ul>
<li><p>Modify the Rhino.Commons source to make UnitOfWork.Current setter
public, and set it in your unit test.</p></li>
<li><p>Use reflection to set the UnitOfWork.Current to your fake unit
of work.</p></li>
<li><p>Since UnitOfWork.Current internally uses Local.Data to find the current
transaction, you should be able to
go:</p>
<p>Rhino.Commons.Local.Data[UnitOfWork.CurrentUnitOfWorkKey] = myFakeUnitOfWork;</p></li>
</ul>
<p>One bit of good news is that UnitOfWork.Current is an IUnitOfWork, and RhinoMocks can easily fake interfaces.</p>
<p>I must finish by saying, I'm not very familiar with Rhino.Commons, so Ayende might have built a proper way of faking UnitOfWork. If this is super-important to you, you ought to ask in the Rhino discussion groups.</p>
|
printing in client machine <p>i am creating a jsp application in which i want to print a file in client (linux os only )machine by sending a command lets say "cat /root/data.txt >/dev/lp0" to the local port of the client systm because my printer is a thermal printer which will print a ticket... the data.txt will be on the client machine.. and i cant use window.print();</p>
<p>but i don't know how to run client command shell from server through scriplet /javascript)... and i i also cant use activexobject as the client os is linux..</p>
<p>so plz help me...</p>
<p>smruti,Delhi</p>
| <p>I don't think this is possible in pure JavaScript, it would be a security hole. You could set up a website, that prints spam when I surf on it.</p>
<p>There might be some technique that allows you more access to the client, e.g. Java Webstart, Flash or somethings else, but pure JS would not do the job right now. </p>
<p>(I know Webstart can get read/write access to your filesystem, if you use signed jars and the client confirms it. And Flash can access you Webcam if you allow it, so I guess it may access your printer as well)</p>
|
Initialize Critical Section only once for a process <p>In a multi threaded application, is there a way to ensure that a Critical Section is initialized only once except for putting the code in DLL main() ??</p>
| <p>On Windows Vista you can use the one-time initialization functions. <a href="http://msdn.microsoft.com/en-us/library/ms686934%28VS.85%29.aspx" rel="nofollow">Using One-Time Initialization</a> shows how to use them to make sure an event is initialized only once.</p>
|
Error, can anybody help me <p>I'm getting this error while trying to run a page:</p>
<pre><code>ERROR:
500 | Internal Server Error | PropelException
Unable to open PDO connection [wrapped: could not find driver]
</code></pre>
<p>What is the problem, what do I need to do to eliminate this problem?</p>
<p>Thanks</p>
| <p>Take a look in php.ini and enable the appropriate PDO driver for your RDBMS vendor. For MySQL you need to uncomment php_pdo_mysql.</p>
|
ctypes bindings for Subversion in windows <p>Is there a binary installer or a faq for the new ctypes bindings for Subversion 1.6 in Windows (32 and 64bit)?</p>
<p>What library would you use to make an easy to deploy (both win32 and x64) svn client in python for svn version >= 1.5?</p>
| <p>You have the <a href="http://pysvn.tigris.org/project%5Fdownloads.html" rel="nofollow">pysvn</a> module which will allow you to do that:</p>
<p>Binary installer based on subversion 1.5.5</p>
|
Migrating from NUnit to Team System error in Enterprise library configuration <p>I get this error from my migration of NUnit to Team System when running some of the tests in Visual Studio:</p>
<blockquote>
<p>Test method
XXX.XXX.Data.Tests.Path.Method> threw exception:Â
System.Configuration.ConfigurationException:
Invalid section name. The section
'dataConfiguration' does not exist in
the requested configuration file
'C:\Program Files\Microsoft Visual
Studio
9.0\Common7\IDE\vstesthost.exe.Config' or the file
'c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Config\machine.config'.
Make sure that the
'enterpriseLibrary.configurationSections'
configuration section exists in one of
the files and that the section
'dataConfiguration' is defined..</p>
</blockquote>
<ol>
<li>We are assuming it is the enterprise
library, what is needed in the<br />
"configuration section" for my tests
to work?</li>
<li>Where does one usually find the
configuration file in team system?</li>
<li>Also why is the application still
working and the tests not?</li>
</ol>
| <p>It sounds like it can't find the app.config/web.config file.</p>
<p>With MSTest, it doesn't test in the usual "output" directory. As a consequence, the "copy to output directory" (etc) flags do nothing. You need to tell it which files to deploy to the test folder; there are two ways:</p>
<ul>
<li>edit the testrunconfig file and add the files to the deployment list</li>
<li>add the <a href="http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.webtesting.deploymentitemattribute.aspx" rel="nofollow"><code>[DeploymentItem]</code></a> attribute to your test, telling it which files are needed</li>
</ul>
<p>I don't really like either approach - in fact, I tend to use TestDriven.NET to run the tests, which does it the way you <em>expect</em> it to behave.</p>
<p>Of course, TestDriven.NET would also run your NUnit tests in the IDE including code-coverage etc - which would then beg the question: why change your existing tests if they can work in the IDE? And the obvious answer is "we've paid for MSTest, and TestDriven.NET isn't free"...</p>
|
Best practice(s) for on screen real-time log viewer for log4net <p>I have a multi-threaded C# application that use log4net for logging capabilities. Mainly the RollingFileAppender.</p>
<p>I want to offer the capability for the user to view the activity of the application in an "application log" window. This will consist of a listview (details mode), a grid or something similar.</p>
<p>I'm looking for best ways to do it. The only solution I have so far is to setup an UDP appender and create a special thread that will listen and foward all messages to the UI.</p>
<p>I also examined the possibility to create a "wrapper" that both write to the UI, the log the message using log4net... hum.</p>
<p>Thanks a lot in advance for your help.</p>
| <p>If you're happy to rely on another program you can use <a href="http://technet.microsoft.com/en-us/sysinternals/bb896647.aspx" rel="nofollow">dbgview</a> from Sysinternals. This will display anything that is logged with <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.debug.writeline.aspx" rel="nofollow">Debug.WriteLine()</a> method. I think that the <a href="http://logging.apache.org/log4net/release/sdk/log4net.Appender.OutputDebugStringAppender.html" rel="nofollow">OutputDebugStringAppender</a> will do this, but I've not used Log4Net so I can't be sure.</p>
|
java swing program with multi lingual support <p>I want to create a TextArea in java where i can write data in chinese. How can I achieve this</p>
<p>Thanks
Bapi</p>
| <p>See <a href="http://stackoverflow.com/questions/718776/how-to-display-japanese-characters-in-jtextarea">this question</a>.</p>
<p>The only thing you have to do is to make sure that the JTextArea uses a font that can display Chinese characters, which the default one unfortunately can't.</p>
|
How do you take input values from users in T-SQL? <p>I want to know how to take input from users in T-SQL.</p>
<p>For example, how would I do a program which takes two numbers from user and adds them together?</p>
| <p>There are any number of ways to build a UI that can accept the user input. That may be the subject of another question.</p>
<p>As other commenters note, do consider the security risk in accepting user input directly, it is critical to sanitize data at multiple layers of the application. That said all data driven applications must accept and act upon user data. This is not impossible, it is just important that you have a full understanding of the risks. The potential problem with accepting user data and executing on it, is that there is the risk of a nefarious user to attempt to execute their own code on your database and drop tables, extract sensitive data or other nasty things. Unless the whole application is behind a coprorate firewall, this is not a task for anybody without significant security experience.</p>
<p>That said, the simplest UI would be to have an internal and trusted user install something like SQL server management studio and then give them .sql scripts that call a stored procedure. This technique is only something that I could reccomend for a trusted user that is somewhat technical.</p>
<p>you create a procedure like this:</p>
<p><hr /></p>
<pre><code>create procedure AddNumbers
@augend int,
@addend int
as
/*
if all the input that you are accepting is numeric
it is somewhat safer as long as you use int or numeric datatypes from the start.
I would stay away from using any alphanumeric data in a function like this
without running it through some validation with a regular expression or other method.
*/
select @augend+@addend
</code></pre>
<p><hr /></p>
<p>and then instruct you user to call it like this </p>
<p><hr /></p>
<pre><code>execute AddNumbers
@augend = 4,
@addend = 5
</code></pre>
<p><hr /></p>
<p>further you could build a UI that calls this procedure and gives the result. But you will need to carefully condder the access and security needed.</p>
|
Deny access when a false category is given <p>I have a website with items that can be divided into categories (items have one, not like tags).</p>
<p>This gives me URL's like <a href="http://example.com/tutorials/12/Do-nice-things" rel="nofollow">http://example.com/tutorials/12/Do-nice-things</a>. However, the category and title in the URL are for SEO-purposes, I don't need them, just the ID. It would also work with <a href="http://example.com/somethingwrong/12/Foobar" rel="nofollow">http://example.com/somethingwrong/12/Foobar</a>.</p>
<p>Now, the question is: Should I check that the given category and title match the actual properties of the item, and show a 404 if the URL is wrong?</p>
<p>Keep in mind that the category and URL can be changed.</p>
| <p>Yes, otherwise people may link to multiple versions of the same thing, and to search engines it will look like duplication.</p>
|
Some Parameters in $.ajax not passing <p>I have this function</p>
<pre><code>$.ajax({
url:aurl,
method:'GET',
beforeSend:function(req) {req.setRequestHeader('Authorization', auth);},
cache:false,
dataType:"json",
error:function() {...},
success:function(t) {...}
});
</code></pre>
<p>However, the parameters:</p>
<ul>
<li>method</li>
<li>beforeSend</li>
<li>Cache</li>
</ul>
<p>are ignored by my browsers FF3, IE8 and Chrome. So, whatever is put there does not change the request sent by the browser to the given url, eg: cannot set method to "POST", or more importantly no Authorization parameter can be placed as part of the request so that the HTTP Authorization form is processed.</p>
<p>The other strange behaviour is that unless
dataType:"json"
there will be no request or response sent orreceived as shown using LiveHTTPHeaders in FF3. eg if dataType:"xml".</p>
<p>URL seems to get processed correctly by the browser. </p>
<p>How does one make sure these extra parameters get sent, anyone with these issues?</p>
| <p>Is the URL remote or local?</p>
<p>According to <a href="http://docs.jquery.com/Ajax/jQuery.ajax" rel="nofollow">JQuery Documentation</a></p>
<blockquote>
<p>Note: All remote (not on the same domain) requests should be specified as <code>GET</code> when <code>'script'</code> or <code>'jsonp'</code> is the <code>dataType</code> (because it loads script using a DOM script tag). Ajax options that require an <code>XMLHttpRequest</code> object are not available for these requests. The complete and success functions are called on completion, but do not receive an <code>XHR</code> object; the <code>beforeSend</code> and <code>dataFilter</code> functions are not called. </p>
</blockquote>
<p>and for the <code>cache</code> option, the default value is: "false for <code>dataType</code> '<code>script</code>' and '<code>jsonp</code>'"</p>
|
Character Encoding Trouble - Java <p>I've written a little application that does some text manipulation and writes the output to a file (html, csv, docx, xml) and this all appears to work fine on Mac OS X. On windows however I seem to get character encoding problems and a lot of '"' seems to disappear and be replaced with some weird stuff. Usually the closing '"' out of a pair.</p>
<p>I use a FreeMarker to create my output files and there is a byte[] array and in one case also a ByteArrayStream between reading the templates and writing the output. I assume this is a character encoding problem so if someone could give me advise or point me to some 'Best Practice' resource for dealing with character encoding in java.</p>
<p>Thanks</p>
| <p>There's really only one best practice: be aware that Strings and bytes are two fundamentally different things, and that whenever you convert between them, you are using a character encoding (either implicitly or explicitly), which you need to pay attention to.</p>
<p>Typical problematic spots in the Java API are:</p>
<ul>
<li><code>new String(byte[])</code></li>
<li><code>String.getBytes()</code></li>
<li><code>FileReader, FileWriter</code></li>
</ul>
<p>All of these implicitly use the platform default encoding, which depends on the OS and the user's locale settings. Usually, it's a good idea to avoid this and explicitly declare an encoding in the above cases (which FileReader/Writer unfortunately don't allow, so you have to use an InputStreamReader/Writer).</p>
<p>However, your problems with the quotation marks and your use of a template engine may have a much simpler explanation. What program are you using to write your templates? It sounds like it's one that inserts <a href="http://blogs.msdn.com/oldnewthing/archive/2009/02/25/9443404.aspx" rel="nofollow">"smart quotes"</a>, which are part of the Windows-specific cp1251 encoding but don't exist in the more global ISO-8859-1 encoding.</p>
<p>What you probably need to do is to be aware which encoding your templates are saved in, and configure your template engine to use that encoding when reading in the templates. Also be aware that some texxt files, specifically XML, explicitly declare the encoding in a header, and if that header disagrees with the actual encoding used by the file, you'll invariable run into problems.</p>
|
Ajax Security <p>We have a heavy Ajax dependent application. What are the good ways of making it sure that the request to server side scripts are not coming through standalone programs and are through an actual user sitting on a browser</p>
| <p>There aren't any really. </p>
<p>Any request sent through a browser can be faked up by standalone programs.</p>
<p>At the end of the day does it really matter? If you're worried then make sure requests are authenticated and authorised and your authentication process is good (remember Ajax sends browser cookies - so your "normal" authentication will work just fine). Just remember that, of course, standalone programs can authenticate too.</p>
|
Unit Testing: TypeMocking a singleton <p>I'm using TypeMock Isolater to mock up some objects for some unit tests - attempting to use the AAA api (so the Isolate calls).</p>
<p>I have a straightforward singleton class where you call a static GetInstance(), which then returns an instance of the class. I thought it would be a simple matter of mocking that up, but I'm running into a very frustrating problem ! I can't seem to make GetInstance() return my mocked object correctly with my expected calls set.</p>
<p>I've tried:</p>
<ul>
<li>using MST projects (using the Accessor classes) to assign a mocked object directly to the instance variable (faking the object using Memers.MustSpecifyReturnValues, and Isolate.WhenCalled using WithExactArguments to set expectations), but for some reason the mocked object <em>always</em> returns null (and no exceptions).</li>
<li>Mocking Singleton.GetInstance() to return the mocked object. This returns a mocked object which needs WhenCalled set, but now the Isolate.WhenCalled calls I make seem to do nothing on the fake object - so all calls throw an unexpected call exception.</li>
<li>I've also tried mocking the actual method call (eg Singleton.GetInstance().Test()), which will work for the call to that method, but all other calls to other methods on the singleton return null rather then throw an exception as I want it to (because this seems to automatically mock up all the objects without Members.MustSpecifyReturnValues).</li>
</ul>
<p>All I want is to mock a singleton, and any calls I don't explicitly tell it to expect to throw an exception on. I thought it would be simple, but apparently not ! Sad</p>
<p>Has anyone any idea what I'm doing wrong?</p>
<p>Thanks
James</p>
| <p>I think the simple solution will be to create a fake instance of the singleton class and use SwapNextInstace before the actual class constructor is called:</p>
<pre><code>[TestMethod]
public void SetBhaciorOnSingleton()
{
var fake = Isolate.Fake.Instance<SingletonClass>();
Isolate.WhenCalled(() => fake.SomeFunction()).WillReturn(10);
// Set additional behavior on singleton class
Isolate.Swap.NextInstance<SingletonClass>().With(fake);
// This is where the class constructor is being called
var result = SingletonClass.GetInstace().SomeFunction();
Assert.AreEqual(10, result );
}
</code></pre>
<p>This solution should work with most scenarios unless the singleton class is created before the test.
If you need to set behavior after the class was created just use WhenCalled:</p>
<pre><code>[TestMethod]
public void SetBhaciorOnSingleton()
{
var fake = Isolate.Fake.Instance<SingletonClass>();
Isolate.WhenCalled(() => fake.SomeFunction()).WillReturn(10);
Isolate.WhenCalled(() => SingletonClass.GetInstace()).WillReturn(fake);
var result = SingletonClass.GetInstace().SomeFunction();
Assert.AreEqual(10, result );
}
</code></pre>
|
Converting (void*) to std::vector<unsigned char> <p>I have a <code>(void*)</code> buffer that I need to convert to <code>std::vector<unsigned char></code> before I can pass it on. Unfortunately, my C++ casting skills a little weak. Any suggestions?</p>
| <p>You will need the length of the buffer. Once you do, we can do this:</p>
<pre><code>unsigned char *charBuf = (unsigned char*)voidBuf;
/* create a vector by copying out the contents of charBuf */
std::vector<unsigned char> v(charBuf, charBuf + len);
</code></pre>
<p>Okay, the comment got me started on why I did not use <code>reinterpret_cast</code>:</p>
<blockquote>
<ul>
<li><p>In C++, the C-style cast is a convenience function -- it asks the compiler to choose the safest and most portable form of conversion over the set of available cast operators.</p></li>
<li><p>The <code>reinterpret_cast</code> is implementation defined and should always be the last thing on your mind (and used when you are necessarily doing a non-portable thing knowingly).</p></li>
<li><p>The conversion between (<code>unsigned</code> doesn't change the type) <code>char *</code> and <code>void *</code> is portable (you could actually use <code>static_cast</code> if you are really picky).</p></li>
</ul>
</blockquote>
<p>The problem with the C-style cast is: the added flexibility can cause heartaches when the pointer type changes.</p>
<p><strong>Note:</strong> I agree with the general convention of not casting as much as possible. However, without any source provided, this is the best I could do.</p>
|
Accessing the original HTTP request packet in an IHttpHandler <p>I am trying to write an IHttpHandler that can work with a request for streaming media coming from Windows Media Player/Silverlight. That means responding to a raw HTTP request like this (taken from the protocol document)</p>
<pre><code>"GET /ms/contoso_100_files/0MM0.wmv HTTP/1.0"
"Accept: */*"
"User-Agent: NSPlayer/4.1.0.3925"
"Host: netshow.micro.com"
"Pragma: no-cache,rate=1.000000,stream-time=0,stream-offset=0:0,request-context=1,max-duration=0"
"Pragma: xClientGUID={2200AD50-2C39-46c0-AE0A-2CA76D8C766D}"
</code></pre>
<p>When I land in the ProcessRequest method, the context.Request.Headers collection does not seem to expose the Pragma values. Further, it can never really do it as there are two lines with the same key (Pragma)!</p>
<p>I am assuming that if I can get the original packet I could parse these out manually.</p>
<p>That said, the next thing I want to do with it is construct a secondary request of type HttpWebRequest. That also sports a similiar dictionary which I expect will also not be able to accept the two identical pragma values without one overwriting the other.</p>
<p>Am I missing something?</p>
| <p>The fact that there are <em>no</em> Pragma headers makes me think they might not be getting sent. I suggest you use Fiddler to watch the network traffic to make sure they're being sent to you.</p>
|
paging count error asp.net <p>I have a data list with paging which works fine locally debugging but doesn't work on my deployment server provided by my hosting company.</p>
<pre><code>Line 151: TotalRowCount = pagedData.DataSourceCount;
</code></pre>
<p>I'm using the same remote database for both local and on deployment server.</p>
<p>Error message:</p>
<pre><code>Server Error in '/' Application.
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
Line 149:
Line 150: // Remember the total number of records being paged through across postbacks
Line 151: TotalRowCount = pagedData.DataSourceCount;
Line 152: PrevPage.Visible = !pagedData.IsFirstPage;
Line 153: NextPage.Visible = !pagedData.IsLastPage;
Source File: \\pdc1\sites\t\test.domain.com\public_html\Auctions.aspx.cs Line: 151
Stack Trace:
[NullReferenceException: Object reference not set to an instance of an object.]
Auctions.ItemDataSource_Selected(Object sender, ObjectDataSourceStatusEventArgs e) in \\pdc1\sites\t\test.domain.com\public_html\Auctions.aspx.cs:151
System.Web.UI.WebControls.ObjectDataSourceView.OnSelected(ObjectDataSourceStatusEventArgs e) +95
System.Web.UI.WebControls.ObjectDataSourceView.InvokeMethod(ObjectDataSourceMethod method, Boolean disposeInstance, Object& instance) +432
System.Web.UI.WebControls.ObjectDataSourceView.ExecuteSelect(DataSourceSelectArguments arguments) +1247
System.Web.UI.WebControls.BaseDataList.GetData() +38
System.Web.UI.WebControls.DataList.CreateControlHierarchy(Boolean useDataSource) +153
System.Web.UI.WebControls.BaseDataList.OnDataBinding(EventArgs e) +54
System.Web.UI.WebControls.BaseDataList.DataBind() +55
System.Web.UI.WebControls.BaseDataList.EnsureDataBound() +60
System.Web.UI.WebControls.BaseDataList.CreateChildControls() +69
System.Web.UI.Control.EnsureChildControls() +87
System.Web.UI.Control.PreRenderRecursiveInternal() +44
System.Web.UI.Control.PreRenderRecursiveInternal() +171
System.Web.UI.Control.PreRenderRecursiveInternal() +171
System.Web.UI.Control.PreRenderRecursiveInternal() +171
System.Web.UI.Control.PreRenderRecursiveInternal() +171
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +842
Version Information: Microsoft .NET Framework Version:2.0.50727.3053; ASP.NET Version:2.0.50727.3053
</code></pre>
| <p>This implies the connection to your database from the server isn't working, as the pagedData object is null.</p>
<p>Check you can access your datasource, with the correct identity.</p>
|
Export to .xlsx <p>Could anyone suggest best way to export data to .xlsx format.
1.Dynamically creating sheets.
2.customizing the data in each sheet.
We can't use office web components.</p>
<p>Thanks</p>
| <p>You should have a look at the <a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=C6E744E5-36E9-45F5-8D8C-331DF206E0D0" rel="nofollow">OpenXML SDK 2.0</a>.</p>
<p>Related blog articles: </p>
<ul>
<li><a href="http://blog.stuartwhiteford.com/?p=49" rel="nofollow">Creating an Excel Workbook with the Open XML SDK 2.0</a> by Stuart Whiteford</li>
<li><a href="http://blogs.msdn.com/brian%5Fjones/archive/2008/11/04/document-assembly-solution-for-spreadsheetml.aspx" rel="nofollow">Document Assembly Solution for SpreadsheetML</a> by Brian Jones</li>
</ul>
|
Language for controllers names in ASP.NET MVC <p>Should my controllers names be in my native language or in English? What is the current best practice? And if in English, how do I make sure that the urls stays in my native tongue? </p>
<p>I know that my webapp won't be multilingual and I rather not write a lot of boilerplate.</p>
| <p>The convention in ASP.NET MVC is that controller and action names are the same as the controller and action in the URI except in special cases, like ambiguous overloads. I think it is a good idea to follow that convention, even if it means that the controller and action names will be in your native language and the rest of the code would be in English. If I were asked to debug a web site which displayed in some language I don't understand like Swahili, I would find it considerably easier to find the appropriate controller and action for a certain page if they reflected the Swahili URI than I would if it were translated into English.</p>
<p>Note, however, that most Unicode characters cannot appear in a URI (without <a href="http://en.wikipedia.org/wiki/Punycode" rel="nofollow">Punycode</a>). Only a restricted subset of ASCII characters can appear in the URI. See <a href="http://www.ietf.org/rfc/rfc3986.txt" rel="nofollow">the specification</a> for details.</p>
|
How to change pivot table data source in Excel? <p>I want to change it from one database to another.</p>
<p>There don't appear to be any options to do this on the pivot table context menu</p>
| <p>Just figured it out-click anywhere in the table, then go to the tabs at the top of the page and select Options-from there you'll see a Change Data Source selection.</p>
|
Best way to chop a signature off an email body <p>I am parsing out some emails. Mobile Mail, iPhone and I assume iPod touch append a signature as a separate boundary, making it simple to remove. Not all mail clients do, and just use '--' as a signature delimiter.</p>
<p>I need to chop off the '--' from a string, but only the last occurrence of it.</p>
<p>Sample copy</p>
<pre><code> hello, this is some email copy-- check this out
--
Tom Foolery
</code></pre>
<p>I thougth about splitting on '--', removing the last part, and I would have it, but explode() and split() neither seem to return great values for letting me know if it did anything, in the event there is not a match.</p>
<p>I can not get preg_replace to go across more than one line. I have standardized all line endings to \n</p>
<p>What is the best suggestion to end up with "hello, this is some email copy-- check this out", taking not, there will be cases where there is no signature, and there are of course going to be cases where I can not cover all the cases.</p>
| <p>Actually <a href="http://tools.ietf.org/html/rfc3676#section-4.3" rel="nofollow">correct signature delimiter</a> is <code>"-- \n"</code> (note the space before newline), thus the delimiter regexp should be <code>'^-- $'</code>. Although you might consider using <code>'^--\s*$'</code>, so it'll work with OE, which gets it wrong.</p>
|
A visual view of source control tree and branches <p>Is there any utility that works with either Subversion or (preferably) Team Foundation Server's source control system that shows a visual representation of the source tree? e.g. it shows branches (with labels) splitting off, merging back in and so on.</p>
| <p>You mean like the Revision Graph, which is built in to Tortoise SVN? You can see a sample of its display capabilities <a href="http://tortoisesvn.net/docs/release/TortoiseSVN%5Fen/tsvn-dug-revgraph.html" rel="nofollow">here</a>.</p>
<p><img src="http://tortoisesvn.net/docs/release/TortoiseSVN%5Fen/images/RevisionGraph.png"></p>
|
C#: GridView, Row-By-Row Operations <p>I have a grid view displaying the messages a user has. Each message the user has is being marked whether it has been read or unread as a bit in my database table.</p>
<p>Is there a way how I can change the style of certain rows in my grid view according to whether the messages are read or unread? I wish to display the whole row with an unread message in bold.</p>
| <p>You will need to use the <code>RowDataBound</code> event for such a task. Here is an example:</p>
<pre><code><asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound" >
...
</asp:GridView>
</code></pre>
<p>.</p>
<pre><code>protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
// searching through the rows
if (e.Row.RowType == DataControlRowType.DataRow)
{
bool isnew = (bool)DataBinder.Eval(e.Row.DataItem, "IsNew");
if ( isnew ) e.Row.BackColor = Color.FromName("#FAF7DA"); // is a "new" row
}
}
</code></pre>
<p><hr /></p>
<p>*Reference: <a href="http://blog.devexperience.net/en/5/Change%5Fbackground%5Fcolor%5Fof%5FGridView%27s%5FRows.aspx" rel="nofollow">http://blog.devexperience.net/en/5/Change_background_color_of_GridView's_Rows.aspx</a>*</p>
|
Constrain LINQ2SQL Datacontext to specific SQL Application Role <p>In SQL Server you are able to have application role security, through which you are able to for example give specific permissions that originate from specific applications.</p>
<p>You can execute sp_SetAppRole() to set the application role but was wondering how this could be accomplished when using a LINQ2SQL datacontext with the least amount of friction.</p>
<p>I've seen this link:
<a href="http://social.msdn.microsoft.com/Forums/en-US/linqprojectgeneral/thread/e25e98a6-b0ac-42fc-b70c-2b269a7fa1cb" rel="nofollow">http://social.msdn.microsoft.com/Forums/en-US/linqprojectgeneral/thread/e25e98a6-b0ac-42fc-b70c-2b269a7fa1cb</a> but was hoping for a cleaner approach/</p>
| <p>My conclussions (see below section for the why): </p>
<p>Using SQL application roles doesn't plays well with connection pooling and also shouldn't be used directly in final user apps (only on a business tier). </p>
<p>The SQL alternative would take away a lot of advantages from using linq, as it relies in SPs. </p>
<p>My recommendation: </p>
<p>If you have a business tier/server, do authorization at the application level instead of relying on sql authorization. If you still want to authorize, have an account associated to the business tier application, and associate a normal role to it. </p>
<p>If it is a client app that connects directly to sql. The user will still have the permission to call whatever his(her) identity has access to, and the app password is there. If you are not comfortable with the user having that level of access, you need a business tier. </p>
<p>If you still want to proceed with the approach, turn off connection pooling. To reduce the open/close overhead, open connections explicitly.</p>
<p><hr /></p>
<p>Full explanation/references:</p>
<p>One issue is it doesn't plays well with connection pooling. That is regardless of linq2sql. See at the end of <a href="http://msdn.microsoft.com/en-us/library/8xx3tyca.aspx" rel="nofollow">this</a> in msdn.</p>
<p>There are 2 alternatives since sql server 2005 <a href="http://msdn.microsoft.com/en-us/library/bb669062.aspx" rel="nofollow">(msdn link)</a>, one is also mentioned in the thread you linked to, but it also points out it can go wrong. </p>
<p>Note that its an unsecured option in a 2 tier scenario, like when the application used by the clients connects directly to sql. In those cases the pwd for any application in the client's computer would be exposed in those. Its more secure if it is a business tier the ones that connects, but that's precisely the case where you really want connection pooling.</p>
<p>The another alternative mentioned in my second link to msdn, works well with connection pooling. It is based on stored procedures, and the execute as statement. The execute as is called inside the procedure, and after the procedure is executed the context is reverted. That is great but really would be giving away a lot from what you get with linq2sql by going the sp route. </p>
|
Regular Expressions in C <p>I'm curious, does anybody know a good way to do regular expression matching in C? The only way I can think of is through Flex. Is this the only way or is there a better way?</p>
<p>Thanks!</p>
| <p>Uh ... The best way is to</p>
<pre><code>#include <regex.h>
</code></pre>
<p>That is the POSIX <a href="http://www.osix.net/modules/article/?id=349" rel="nofollow">standard API</a> for regular expressions.</p>
<p>For non-POSIX systems, rolling your own is one alternative, a basic regex engine is not too hard to accomplish. I'm sure there are off-the-shelf solutions too, I haven't neded one.</p>
<p>Come to think of it, I think <a href="http://library.gnome.org/devel/glib/stable/glib-Perl-compatible-regular-expressions.html" rel="nofollow">glib</a> has one.</p>
|
Optimize memory usage of a collection of Strings in Java <p>I have a large number of name - value pairs (approx 100k) that I need to store in some sort of cache (say a hash map) where the value is a string with an average of about 30k bytes in size.</p>
<p>Now I know for a fact that a large number of the values have exactly the same string data. In order to avoid having to allocate the identical string data several times, I would like to somehow reuse a previously allocated string thus consuming less memory. In addition this needs to be reasonably fast. i.e. scanning through all the previously allocated values one-by-one is not an option.</p>
<p>Any recommendations on how I could solve this problem?</p>
| <p>Do <em>not</em> use String.intern (there have been various memory issues related to this through the years). instead, create your own cache, similar to String.intern. basically, you want a Map, where each key maps to itself. then, before caching any string, you "intern" it:</p>
<pre><code>private Map<String,WeakReference<String>> myInternMap = new WeakHashMap<String,,WeakReference<String>>();
public String intern(String value) {
synchronized(myInternMap) {
WeakReference<String> curRef = myInternMap.get(value);
String curValue = ((curRef != null) ? curRef.get() : null);
if(curValue != null) {
return curValue;
}
myInternMap.put(value, new WeakReference<String>(value));
return value;
}
}
</code></pre>
<p>note, you use weakreferences for the keys and values so that you don't keep references for strings which you are no longer using.</p>
|
C# How to exclude generated code from VS2008 code metrics? <p>How can I exclude generated code, like Windows Forms Designer related code, from Visual Studio 2008 code metrics?</p>
<p>I've been digging around but I didn't found any solution. <code>DebuggerHidden</code> and <code>DebuggerNonUserCode</code> have no effect.</p>
| <p>Try the <a href="http://msdn.microsoft.com/en-us/library/system.codedom.compiler.generatedcodeattribute.aspx">GeneratedCodeAttribute</a>.</p>
|
Want to display an error message if the session is closed in rails <p>Hi there i want to display an error message if the session is closed, cause if i log in and and i press the go back at the top of the browser and then press the go forward and try to refresh the page it display an error message that it couldn't find the current user who was in the session and i want to display a page for handling that error message. like your session has expired. </p>
| <p>If I understand you correctly you are looking to do something like this in your login_required function or the like.</p>
<pre><code>cookie_session = request.cookies['my_app_session']
unless cookie_session.blank? && Session.find_by_session_d(cookie_session).blank?
flash[:warning] = "Your session is expired, please login again"
redirect_to new_session_path
end
</code></pre>
<p>This example should be treated as such but it might give you an idea what to do.</p>
|
Crystal Reports Best Practices <p>I don't have much experience managing reports, but I work on an application that works like this:</p>
<p>There is an interface for the users to select a report they want to view from a list of reports. This list is populated by a reports table in the database which holds info like the report name, the file name, and which parameters the report takes. </p>
<p>There are several common parameters in these reports -- they are ranges, or sorting -- so the user might pull up a report about all the widgets numbered 200 through 4000, grouped by Foo.</p>
<p>Right now a person develops a stored procedure, and the report file at the same time. They pass it off to me, and I have to deploy it by running the sproc script in production, and moving the .rpt file to the right directory. I then have to insert a record into the reports table with the name, filename, and parameters. </p>
<p>This is a logistical challenge because there's no great way to keep track of which reports have been deployed onto which systems (just because they are present, doesn't mean they are updated, there are 4 systems total that ideally should match), and there are several points of failure possible:</p>
<p>1) The params in the sproc don't match the params in the .rpt file
2) The params in the reports table don't match the params in the .rpt or sproc
3) The sproc is updated while the .rpt file isn't for whatever reason
4) What happens when a new report needs a parameter that hasn't been coded for in the params page?</p>
<p>It all boils down to the system not being dynamic enough. Like I said, I don't know about reporting, but I have a feeling that the guy doing the reports doesn't either. It seems like there must be a better way to keep the sproc and .rpt file in sync, and to dynamically ask for the parameters it needs through something like Reflection. </p>
<p>How is this normally handled?</p>
| <p>We simply use the default crystal parameter prompting engine. Otherwise, our reporting solution is basically the same as the one you described.</p>
<p>It doesn't make sense to put the parameters into a table. These can be retrieved by loading the ReportDocument and reading the parameters collection. Your prompting engine should look here and then generate the prompts. Otherwise, it's just too much to keep in sync.</p>
|
How do I get the entity framework to stop setting the rowversion field? <p>Im using the Entity Framework and I have a rowversion (timestamp) field on a table to use for concurrency. However, when updating the entity object, it keeps trying to set the rowversion column to null, and I get an error:</p>
<p>The 'VerCol' property on 'LmpDemoRequest' could not be set to a 'null' value. You must set this property to a non-null value of type 'Byte[]'. </p>
<p>I have the VerCol column within the entity definition, but I am unable to remove the "Setter" function.</p>
<p>How do I get the entity framework to stop attempting to set this column?</p>
| <p>You can pass any arbitrary, valid values for the RowVersion fields (DateTime.Now for example). They will be overwritten with the server-generated values.</p>
<p>For future releases of EF, there should be support for "shadow properties", which exist in the model but not in your classes. That feature would be useful in situations such as this.</p>
|
How do I programatically download a file from a sharepoint site? <p>I have a sharepoint site that has an excel spreadsheet that I need to download on a schedulad basis</p>
<p>Is this possible?</p>
| <p>Yes it is possible to download the file from sharepoint.
Once you have the url for the document, it can be downloaded using HttpWebRequest and HttpWebResponse.</p>
<p>attaching a sample code</p>
<pre><code> DownLoadDocument(string strURL, string strFileName)
{
HttpWebRequest request;
HttpWebResponse response = null;
request = (HttpWebRequest)WebRequest.Create(strURL);
request.Credentials = System.Net.CredentialCache.DefaultCredentials;
request.Timeout = 10000;
request.AllowWriteStreamBuffering = false;
response = (HttpWebResponse)request.GetResponse();
Stream s = response.GetResponseStream();
// Write to disk
if (!Directory.Exists(myDownLoads))
{
Directory.CreateDirectory(myDownLoads);
}
string aFilePath = myDownLoads + "\\" + strFileName;
FileStream fs = new FileStream(aFilePath, FileMode.Create);
byte[] read = new byte[256];
int count = s.Read(read, 0, read.Length);
while (count > 0)
{
fs.Write(read, 0, count);
count = s.Read(read, 0, read.Length);
}
// Close everything
fs.Close();
s.Close();
response.Close();
}
</code></pre>
<p>You can also use the GetItem API of Copy service to download a file.</p>
<pre><code> string aFileUrl = mySiteUrl + strFileName;
Copy aCopyService = new Copy();
aCopyService.UseDefaultCredentials = true;
byte[] aFileContents = null;
FieldInformation[] aFieldInfo;
aCopyService.GetItem(aFileUrl, out aFieldInfo, out aFileContents);
</code></pre>
<p>The file can be retrieved as a byte array.</p>
|
How do I group items into subheadings in an ASP.NET gridview control? <p>I'd like to take two tables and populate a gridview with the results:</p>
<p>product
category</p>
<p>I'd like to have the gridview seperated into subheadings by category, rather than as a data field within the product gridview...</p>
<p>Something like:</p>
<p>(categories: food, clothing, shelter)</p>
<pre><code>FOOD
Rice 10s Available <buy now>
Beans 20s Available <buy now>
Chicken 50s Available <buy now>
CLOTHING
Cloak 30s Available <buy now>
Helmet 45s Available <buy now>
Sandals 10s Available <buy now>
SHELTER
Tent 100s Available <buy now>
</code></pre>
<p>Any help would be appreciated!</p>
| <p>You cannot do with the asp.net gridview out of the box. </p>
<p>You could use a repeater and nest a gridview inside the repeater item. Repeater for the categories. .NET 3.0 + use a ListView</p>
<p>You can purchase commerical controls and maybe there are some free ones which are customized to allow this behaviour.</p>
<p>Andrew</p>
|
What's the best way to normalize "time" in PHP? <p>I'm looking for a way to turn user input into normalized data fit for calculation. The input is some length of time, and is coming from Twitter, so it's string only. Ideally I'd love these results:</p>
<p>an hour and a half --> 01:30</p>
<p>27.52 --> 00:28</p>
<p>5:24 --> 05:24</p>
<p>Is this is a particularly difficult thing to do? I could focus on coaching the users on how to create good input, but also don't want to be too strict.</p>
<p>Any suggestions would be great,</p>
<p>Thanks!</p>
| <p>Three things to make it work:</p>
<ol>
<li>regular expressions</li>
<li>fuzzy logic (lots of if/else statements)</li>
<li><a href="http://php.net/strtotime" rel="nofollow">strtotime</a> to normalize to standard unix epoch time (which makes additions/subtractions very easy)</li>
</ol>
<p>Since it's user input and non-deterministic that's the only way. Even then the results won't be 100% reliable and a small margin of error should be acceptable.</p>
|
Can I open a ".pdf" document on a blackberry using java? <p>Can I open a ".pdf" document on a blackberry using java?</p>
<p>If yes, then how?</p>
| <p>theres nothin native in blackberry to load pdf files, but you can achieve that loading google viewer inside your Browser field, that will do the trick! =D!</p>
<pre><code>public ScrLoad()
{
String url = "http://docs.google.com/gview?embedded=true&url=http://prueba.agenciareforma.com/appiphone/android/elnorte.pdf";
add(new BrowserField(url));
}
</code></pre>
<p>Google Docs Viewer
<a href="http://docs.google.com/gview" rel="nofollow">http://docs.google.com/gview</a></p>
|
Serialize in C++ then deserialize in C#? <p>Is there an easy way to serialize data in c++ (either to xml or binary), and then deserialize the data in C#? </p>
<p>I'm working with some remote WINNT machines that won't run .Net. My server app is written entirely in C#, so I want an easy way to share simple data (key value pairs mostly, and maybe some representation of a SQL result set). I figure the best way is going to be to write the data to xml in some predefined format on the client, transfer the xml file to my server, and have a C# wrapper read the xml into a usable c# object.</p>
<p>The client and server are communicating over a tcp connection, and what I really want is to serialize the data in memory on the client, transfer the binary data over the socket to a c# memory stream that I can deserialize into a c# object (eliminating file creation, transfer, etc), but I don't think anything like that exists. Feel free to enlighten me. </p>
<h2>Edit</h2>
<p>I know I can create a struct in the c++ app and define it in c# and transfer data that way, but in my head, that feels like I'm limiting what can be sent. I'd have to set predefined sizes for objects, etc</p>
| <p><a href="http://code.google.com/apis/protocolbuffers/docs/overview.html">Protocol Buffers</a> might be useful to you.</p>
<blockquote>
<p>Protocol buffers are Google's language-neutral, platform-neutral, extensible mechanism for serializing structured data â <strong>think XML, but smaller, faster, and simpler</strong>. You define how you want your data to be structured once, then you can use special generated source code to easily write and read your structured data to and from a variety of data streams and using a variety of languages â Java, C++, or Python.</p>
</blockquote>
<p>.NET ports are available from <a href="http://code.google.com/p/protobuf-net/">Marc Gravell</a> and <a href="http://github.com/jskeet/dotnet-protobufs/tree/master">Jon Skeet</a>.</p>
|
How to implement generic test for RMI connection, J2EE services? <p>I'd like to implement a little test to check connectivity to J2EE services over RMI. It needs to be generic, so that I could just give it a property file with the following properties set in it:</p>
<pre>
java.naming.factory.initial=oracle.j2ee.rmi.RMIInitialContextFactory
java.naming.security.principal=user
java.naming.security.credentials=pass
java.naming.provider.url=ormi://hostname:port/application
</pre>
<p>Checking the port is not sufficient, because other applications could be successfully deployed on the server. I can't assume that all applications in our environment have a default service with default method (like a ping method), which would make it much easier.</p>
<p>Is there a standard test I could perform using the java.naming.provider.url?</p>
| <p>I settled for a method which isn't quite as generic as I would like, but which works.</p>
<p>Because all services are deployed on an Oracle OAS, I can execute opmnctl to get the status of the container and all applications. Not pretty, but it does the job.</p>
|
Why does a binding fire even if the bound property doesn't change? <p>With the code below, I get both the <code>Firing C Binding</code> message and the <code>Firing F Binding</code> message. Why is that? I'm expecting to only receive the <code>Firing C Binding</code> message.</p>
<pre><code>class Program : Form
{
private Label lblC;
private Label lblF;
private Button btnCUp;
private Temp t;
public Program()
{
lblC = new Label();
lblF = new Label();
btnCUp = new Button();
t = new Temp();
lblC.Location = new Point(22, 21);
lblC.Size = new Size(35, 13);
Binding b = new Binding("Text", t, "C");
b.Format += new ConvertEventHandler(CLabelFormat);
lblC.DataBindings.Add(b);
lblF.Location = new Point(108, 21);
lblF.Size = new Size(35, 13);
Binding b2 = new Binding("Text", t, "F");
b2.Format += new ConvertEventHandler(FLabelFormat);
lblF.DataBindings.Add(b2);
btnCUp.Location = new Point(45, 55);
btnCUp.Text = "C Up";
btnCUp.Click += new EventHandler(btnCUp_Click);
this.ClientSize = new Size(165, 113);
this.Controls.Add(lblC);
this.Controls.Add(lblF);
this.Controls.Add(btnCUp);
}
private void CLabelFormat(object sender, ConvertEventArgs cevent)
{
MessageBox.Show("Firing C Binding");
}
private void FLabelFormat(object sender, ConvertEventArgs cevent)
{
MessageBox.Show("Firing F Binding");
}
[STAThread]
public static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Program());
}
private void btnCUp_Click(object sender, EventArgs e)
{
t.incC();
}
}
class Temp : INotifyPropertyChanged
{
private double tempC;
private double tempF;
public event PropertyChangedEventHandler PropertyChanged;
public Temp()
{
tempC = 0;
tempF = ctof(tempC);
}
private void NotifyPropertyChanged(String field)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(field));
}
}
private double ctof(double c)
{
return c * 9.0 / 5.0 + 32;
}
public void incC()
{
++tempC;
tempF = ctof(tempC);
NotifyPropertyChanged("C");
//NotifyPropertyChanged("F");
}
public double C
{
get { return tempC; }
}
public double F
{
get { return tempF; }
}
}
</code></pre>
<p>If I remove the comment in front of <code>NotifyPropertyChanged("F")</code>, then I get four message boxes when I press the button. Two for "Firing C Binding" and two for "Firing F Binding". </p>
<p>How can I modify the code to only get one of each?</p>
<hr>
<p><strong>EDIT:</strong> I've tried to look at the source for Binding (using Reflector) to see what it does when a PropertyChanged event is fired, but couln't find anything. Can anyone provide some insight? I want to confirm that it cares about what field is changed.</p>
<p><strong>EDIT:</strong> Replaced my code with a full compilable example implementation that demonstrates the issue.</p>
| <p>The PropertyChanged event is only firing once, which you can test yourself:</p>
<pre><code>t.PropertyChanged += t_PropertyChanged;
void t_PropertyChanged(object sender, PropertyChangedEventArgs e) {
MessageBox.Show("Property Changed: " + e.PropertyName);
}
</code></pre>
<p>The <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.binding.format.aspx" rel="nofollow">Binding Format</a> event is something else:</p>
<blockquote>
<p>The Format event occurs whenever the Current value of the BindingManagerBase changes, which includes:<br></p>
<ul>
<li>The first time the property is bound.<br></li>
<li>Any time the Position changes.<br></li>
<li>Whenever the data-bound list is sorted or filtered, which is accomplished when a DataView supplies the list.</li>
</ul>
</blockquote>
<p>So it would seem the Format event fires whenever a property changes in the current value.</p>
|
Stack overflow error when using JQuery/ASP.NET for simple ajax chat <p>I am trying to create a simple ajax chat using JQuery and ASP.NET. My code works like this: </p>
<ol>
<li>When the page loads it refreshes the 'chatbox' div with a request to the messages.aspx page, which handles getting new messages from the database and kicks off an auto refresh with the setTimeout().</li>
<li>Whenever the user clicks the send button, it adds the message to the database inside the messages.aspx page_load code. </li>
</ol>
<p>I am getting a stack overflow error right from the start when the timeout starts, and I am not sure what would cause this? Could it be caching? Maybe the code in messages.aspx can't complete running within those 5 seconds? Any help would be appreciated! </p>
<p>Also, I didn't worry about sql injection attacks yet b/c I was just trying to get it working with simple code.</p>
<p>Here's my code:</p>
<p><strong>Client-side:</strong></p>
<pre><code><%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_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>
<script src="jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
refreshChat();
$("#btnSend").click(function() {
addMessage();
});
return false;
});
function refreshChat()
{
$.get("messages.aspx", function(data) {
$("#chatbox").empty();
$("#chatbox").prepend(data);
});
setTimeout(refreshChat(), 5000);
}
function addMessage()
{
$.get("messages.aspx", {usr: $("#usr").val(), msg: $("#msg").val()} );
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="input">
username: <input type="text" name="usr" id="usr" /><br />
message:<br />
<textarea id="msg" name="msg" rows="5" cols="30"></textarea><br /><br />
<input type="button" id="btnSend" name="btnSend" value="Send" />
</div>
<div id="chatbox"></div>
</form>
</body>
</html>
</code></pre>
<p><strong>Server Side:</strong></p>
<pre><code>using System;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.IO;
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;
public partial class messages : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn =
new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=F:\\Chatter\\App_Data\\messages.mdf;Integrated Security=True;User Instance=True");
conn.Open();
string sql;
SqlCommand comm;
if (Request["usr"] != null)
{
string user = Request["usr"].ToString();
string message = Request["msg"].ToString();
sql = "insert into messages (usr, msg, [date]) values ('"
+ user + "', '" + message + "', '" + DateTime.Now + "')";
comm = new SqlCommand(sql, conn);
comm.ExecuteNonQuery();
}
sql = "select top 5 usr, msg from messages order by [date] desc";
comm = new SqlCommand(sql, conn);
SqlDataReader dr = comm.ExecuteReader();
while (dr.Read())
{
Response.Write(dr["usr"].ToString() + ": <br/>" + dr["msg"] + "<br/><br/>");
}
dr.Close();
conn.Close();
}
}
</code></pre>
| <p>Your javascript refreshChat function is recursively calling itself. Change the code to:</p>
<pre><code> function refreshChat()
{
$.get("messages.aspx", function(data) {
$("#chatbox").empty();
$("#chatbox").prepend(data);
});
setTimeout(refreshChat, 5000);
}
</code></pre>
|
Verify value of reference parameter with Moq <p>I just switched to Moq and have run into a problem. I'm testing a method that creates a new instance of a business object, sets the properties of the object from user input values and calls a method (SaveCustomerContact ) to save the new object. The business object is passed as a ref argument because it goes through a remoting layer. I need to test that the object being passed to SaveCustomerContact has all of its properties set as expected, but because it is instantiated as new in the controller method I can't seem to do so.</p>
<pre><code>public void AddContact() {
var contact = new CustomerContact() { CustomerId = m_model.CustomerId };
contact.Name = m_model.CustomerContactName;
contact.PhoneNumber = m_model.PhoneNumber;
contact.FaxNumber = m_model.FaxNumber;
contact.Email = m_model.Email;
contact.ReceiveInvoiceFlag = m_model.ReceiveInvoiceFlag;
contact.ReceiveStatementFlag = m_model.ReceiveStatementFlag;
contact.ReceiveContractFlag = m_model.ReceiveContractFlag;
contact.EmailFlag = m_model.EmailFlag;
contact.FaxFlag = m_model.FaxFlag;
contact.PostalMailFlag = m_model.PostalMailFlag;
contact.CustomerLocationId = m_model.CustomerLocationId;
RemotingHandler.SaveCustomerContact( ref contact );
}
</code></pre>
<p>Here's the test:</p>
<pre><code>[TestMethod()]
public void AddContactTest() {
int customerId = 0;
string name = "a";
var actual = new CustomerContact();
var expected = new CustomerContact() {
CustomerId = customerId,
Name = name
};
model.Setup( m => m.CustomerId ).Returns( customerId );
model.SetupProperty( m => model.CustomerContactName, name );
model.SetupProperty( m => m.PhoneNumber, string.Empty );
model.SetupProperty( m => m.FaxNumber, string.Empty );
model.SetupProperty( m => m.Email, string.Empty );
model.SetupProperty( m => m.ReceiveInvoiceFlag, false );
model.SetupProperty( m => m.ReceiveStatementFlag, false );
model.SetupProperty( m => m.ReceiveContractFlag, false );
model.SetupProperty( m => m.EmailFlag, false );
model.SetupProperty( m => m.FaxFlag, false );
model.SetupProperty( m => m.PostalMailFlag, false );
model.SetupProperty( m => m.CustomerLocationId, 0 );
remote
.Setup( r => r.SaveCustomerContact( ref actual ) )
.Callback( () => Assert.AreEqual( actual, expected ) );
target.AddContact();
}
</code></pre>
<p>This is just the most recent of many attempts to get ahold of that parameter. For reference, the value of actual does not change from its initial (constructed) state.</p>
<p>Moving the Assert.AreEqual(expected, actual) after the target call fails. If I add .Verifiable() to the setup instead of the .CallBack and then call remote.Verify after the target (or, I assume, set the mock to strict) it always fails because the parameter I provide in the test is not the same instance as the one that is created in the controller method.</p>
<p>I'm using Moq 3.0.308.2. Any ideas on how to test this would be appreciated. Thanks!</p>
| <p>I can't offer you an exact solution, but an alternative would be to hide the pass-by-ref semantics behind an adapter, which takes the parameter by value and forwards it to the RemotingHandler. This would be easier to mock, and would remove the "ref" wart from the interface (I am always suspicious of ref parameters :-) )</p>
<p>EDIT:</p>
<p>Or you could use a stub instead of a mock, for example:</p>
<pre><code>public class StubRemotingHandler : IRemotingHandler
{
public CustomerContact savedContact;
public void SaveCustomerContact(ref CustomerContact contact)
{
savedContact = contact;
}
}
</code></pre>
<p>You can now examine the saved object in your test:</p>
<pre><code>IRemotingHandler remote = new StubRemotingHandler();
...
//pass the stub to your object-under-test
...
target.AddContact();
Assert.AreEqual(expected, remote.savedContact);
</code></pre>
<p>You also say in your comment: </p>
<blockquote>
<p>I'd hate to start a precedent of wrapping random bits of the backend so I can write tests more easily</p>
</blockquote>
<p>I think that's <em>exactly</em> the precedent you need to set! If your code isn't testable, you're going to keep struggling to test it. Make it easier to test, and increase your coverage.</p>
|
How do I take screenshots of web pages using ruby and a unix server? <p>I'm trying to programatically create thumbnail images of a large number of web pages that are hosted on my own ruby/rails-based website.</p>
<p>I want to be able to code a stand-alone bit of ruby that looks something like this:</p>
<pre><code>require 'awesome-screenshot-maker'
items.each do |id|
url = "http://foo.com/bar/#{id}"
shooter = AwesomeScreenshotMaker.new(0.2) # thumbnails are 20% of original
shooter.capture(url, "/images/thumbnail-#{id}.png")
end
</code></pre>
<p>I need the awesome-screenshot-maker library (and its dependencies) to be fairly easy to build on Linux, Solaris and Mac OS X. Ideally it will install with a single 'gem install' command.</p>
<p>I've spent the afternoon exploring various options, including <a href="http://www.lilik.it/~mirko/Ruby-GNOME2/moz-snapshooter.rb" rel="nofollow">Moz snap shooter</a>, <a href="http://www.paulhammond.org/webkit2png/" rel="nofollow">webkit2png</a> and <a href="http://github.com/danlucraft/rbwebkitgtk/tree/master" rel="nofollow">rbwebkitgtk</a>. They are all in the right area, but none seem to work on all three platforms.</p>
<p>RMagick looks like a possible option if I'm willing to output PDFs from my rails app (instead of web pages), but that strikes me as hacky. It's also very laborious to get RMagic and imagemagick up and running on Mac OS X.</p>
<p>Does such a library exist that can easily be setup on three platforms?</p>
| <p><a href="http://seleniumhq.org/">Selenium RC</a> has a Ruby interface and can grab a screenshot using <a href="http://release.seleniumhq.org/selenium-remote-control/1.0-beta-2/doc/ruby/classes/Selenium/Client/GeneratedDriver.html#M000220">capture_screenshot(filename,kwargs)</a>.</p>
<p>You'd then have to shrink it to a thumbnail.</p>
|
Who "Killed" my process and why? <p>My application runs as a background process on Linux. It is currently started at the command line in a Terminal window.</p>
<p>Recently a user was executing the application for a while and it died mysteriously. The text:</p>
<blockquote>
<p>Killed</p>
</blockquote>
<p>was on the terminal. This happened two times. I asked if someone at a different Terminal used the kill command to kill the process? No.</p>
<p>Under what conditions would Linux decide to kill my process? I believe the shell displayed "Killed" because the process died after receiving the kill(9) signal. If Linux sent the kill signal should there be a message in a system log somewhere that explains why it was killed?</p>
| <p>If the user or sysadmin did not kill the program the kernel may have. The kernel would only kill a process under exceptional circumstances such as extreme resource starvation (think mem+swap exhaustion).</p>
|
Fake a form submission with C# WebClient <p>I need to call a web and retrieve the resulting data from the model in my asp.net mvc application. When accessed on the web, the form looks like this:</p>
<pre><code><form id="textEntryForm" name="textEntryForm" method="post" action="/project/evaluate_to_pdf">
<textarea id="p" rows="20" name="p" cols="132"/><br/>
<input type="button" value="parse" name="do_parse" onclick="new Ajax.Updater('parsedProject','/project/parse',{asynchronous:true,evalScripts:true,on404:function(e){alert('not found!')},parameters:Form.serialize(this.form)});return false"/>
<input type="button" value="evaluate_to_html" name="do_evaluate_to_html" onclick="new Ajax.Updater('parsedProject','/project/evaluate_to_html',{asynchronous:true,evalScripts:true,on404:function(e){alert('not found!')},parameters:Form.serialize(this.form)});return false"/>
<input type="button" value="evaluate" name="do_evaluate" onclick="new Ajax.Updater('parsedProject','/project/evaluate',{asynchronous:true,evalScripts:true,on404:function(e){alert('not found!')},parameters:Form.serialize(this.form)});return false"/>
<input type="button" value="evaluate to pdf source" name="do_evaluate_to_pdf_source" onclick="new Ajax.Updater('parsedProject','/project/evaluate_to_pdf_source',{asynchronous:true,evalScripts:true,on404:function(e){alert('not found!')},parameters:Form.serialize(this.form)});return false"/>
<input type="submit" id="do_evaluate_to_pdf" value="evaluate_to_pdf" name="do_evaluate_to_pdf"/>
</form>
</code></pre>
<p>I need to pass the data that would be entered into textarea id="p". How do add that in, using a WebClient to connect?</p>
<p>Thanks!</p>
<p><strong>Edit</strong> This isn't for testing purposes, I need to retrieve the data for use in my application.</p>
| <p>I just used this: <a href="http://www.eggheadcafe.com/community/aspnet/2/69261/you-can-use-the-webclient.aspx">http://www.eggheadcafe.com/community/aspnet/2/69261/you-can-use-the-webclient.aspx</a></p>
|
How to freeze rake? <p>I have a rails-app (2.3.2) that I need to install on a server on which rake isn't installed, and on which I haven't got privileges to install gems, so I'd like to freeze the rails gem.</p>
<p>However, I can't figure out how to do that. I've put it in the dependencies in environment.rb, but "rake gems:unpack GEM=rake" has no effect. "rake gems" says rake's a framework gem, not a frozen gem.</p>
<p>How do I make sure rake turns up in my "vendor/gems", and how do I tell capistrano to use that version of rake?</p>
| <p>Freezing the gem itself is fairly straightforward - if Maran's solution won't work for you, you can create an actual gem repository in your vendor directory and then do <code>gem install rake --install-dir /rails_dir/vendor/gems</code>.</p>
<p>The harder part is telling Capistrano which rake to use. Can you post a little more detail on what you want to do with rake and Capistrano? </p>
|
Server disconnects in Java <p>Related posts didn't answer my question.</p>
<p>I have a server which does something like:</p>
<pre><code>EVERY TWO SECONDS DO:
if the inputstream is not null {
if inputStream.available() is 0
{
return
}
print "handling input stream"
handleTheInputStream();
}
</code></pre>
<p>Even after my client disconnects, the server doesn't recognize it through an IOException. The other post said that I would see an End-of-Stream character. However, that is not the case, since after my client disconnects I never see "handling input stream" which indicates that no data is available.</p>
<p>Perhaps something is wrong with the way I currently understand how this works.</p>
<p>Please help.</p>
| <p>Don't use <code>available()</code> - that says whether or not there's <em>currently</em> data available, not whether there <em>will</em> be data available in the future. In other words, it's the wrong tool to use to detect disconnection.</p>
<p>Basically you should call <code>read()</code> (and process the data) until it returns -1, at which point it means the client has disconnected.</p>
|
Unit testing a LINQ2SQL repository <p>I am taking my first steps with MsTest and Moq and would like to unit test a Linq2SQL repository class. The problem is that I do not want the unit tests to permantly modify my development database. </p>
<p>Which would be the best approach for this scenario?</p>
<ul>
<li>Let each test operate on my real development database, but make sure each test cleans up after itself</li>
<li>Create a duplicate of my development database and dbml for the unit test and use that context instead so I can clear the entire database before each test run </li>
<li>Find some elaborate way of mocking the Datacontext (please bear in mind that I am a total Moq noob). </li>
<li>Something completely different? Perhaps something that would automate setting up the database for me before each test run?</li>
</ul>
<p><strong>Edit:</strong> I just learned that MBUnit has a rollback attribute that reverses any database operations run by a test case. I am not particularly attached to MSTest, so could this be an easy answer to my problem?</p>
| <p>I went with mocking/faking the database using some wrapper classes + a fake implementation based on <a href="http://andrewtokeley.net/archive/2008/07/06/mocking-linq-to-sql-datacontext.aspx">http://andrewtokeley.net/archive/2008/07/06/mocking-linq-to-sql-datacontext.aspx</a>. Note that I did end up implementing SubmitChanges logic in my fake data context wrapper to test out the validation logic in my entity's partial class implementation. I think that this was really the only tricky part which differed substantially from Tokeley's implementation.</p>
<p>I'll include my FakeDataContextWrapper implementation below:</p>
<pre><code>public class FakeDataContextWrapper : IDataContextWrapper
{
public DataContext Context
{
get { return null; }
}
private List<object> Added = new List<object>();
private List<object> Deleted = new List<object>();
private readonly IFakeDatabase mockDatabase;
public FakeDataContextWrapper( IFakeDatabase database )
{
mockDatabase = database;
}
protected List<T> InternalTable<T>() where T : class
{
return (List<T>)mockDatabase.Tables[typeof( T )];
}
#region IDataContextWrapper Members
public virtual IQueryable<T> Table<T>() where T : class
{
return mockDatabase.GetTable<T>();
}
public virtual ITable Table( Type type )
{
return new FakeTable( mockDatabase.Tables[type], type );
}
public virtual void DeleteAllOnSubmit<T>( IEnumerable<T> entities ) where T : class
{
foreach (var entity in entities)
{
DeleteOnSubmit( entity );
}
}
public virtual void DeleteOnSubmit<T>( T entity ) where T : class
{
this.Deleted.Add( entity );
}
public virtual void InsertAllOnSubmit<T>( IEnumerable<T> entities ) where T : class
{
foreach (var entity in entities)
{
InsertOnSubmit( entity );
}
}
public virtual void InsertOnSubmit<T>( T entity ) where T : class
{
this.Added.Add( entity );
}
public virtual void SubmitChanges()
{
this.SubmitChanges( ConflictMode.FailOnFirstConflict );
}
public virtual void SubmitChanges( ConflictMode failureMode )
{
try
{
foreach (object obj in this.Added)
{
MethodInfo validator = obj.GetType().GetMethod( "OnValidate", BindingFlags.Instance | BindingFlags.NonPublic );
if (validator != null)
{
validator.Invoke( obj, new object[] { ChangeAction.Insert } );
}
this.mockDatabase.Tables[obj.GetType()].Add( obj );
}
this.Added.Clear();
foreach (object obj in this.Deleted)
{
MethodInfo validator = obj.GetType().GetMethod( "OnValidate", BindingFlags.Instance | BindingFlags.NonPublic );
if (validator != null)
{
validator.Invoke( obj, new object[] { ChangeAction.Delete } );
}
this.mockDatabase.Tables[obj.GetType()].Remove( obj );
}
this.Deleted.Clear();
foreach (KeyValuePair<Type, IList> tablePair in this.mockDatabase.Tables)
{
MethodInfo validator = tablePair.Key.GetMethod( "OnValidate", BindingFlags.Instance | BindingFlags.NonPublic );
if (validator != null)
{
foreach (object obj in tablePair.Value)
{
validator.Invoke( obj, new object[] { ChangeAction.Update } );
}
}
}
}
catch (TargetInvocationException e)
{
throw e.InnerException;
}
}
public void Dispose() { }
#endregion
}
</code></pre>
|
SQL replication - Publication deleted, but log file still growing <p><strong>To preface, I've seen the command to answer this question before, but now I can't find it again, so I'm just looking for the single SQL statement that will solve my problem.</strong></p>
<p>I had two publications on a SQL Server 2000 database at one point, but I've since deleted them. However, my log file is growing, and appears to contain unreplicated transactions, and is growing without end. I've tried this:</p>
<pre><code>EXEC sp_repldone @xactid = NULL, @xact_segno = NULL, @numtrans = 0, @time = 0, @reset = 1
</code></pre>
<p>I get a message that "The database is not published" (and since I've deleted the publication, that makes sense). If I try:</p>
<pre><code>backup log dbname with truncate_only
</code></pre>
<p>I get the message that there are unreplicated transactions in my log, and it won't truncate.</p>
<p><strong>I've seen this before, where no publications existed, but the database was marked as still participating in replication, and I found a single line script to un-flag the database as a source for replication, which immediately resolved my problem. I can't find it now, though, when I need it again - hopefully one of you can shed some light. Thanks!</strong></p>
| <p>I was unable to purge this not-yet-replicated data through any supported method, so I had to forcefully rebuild the log file. It's SQL 2000, so there's an unsupported/undocumented SP to do this:</p>
<pre><code>DBCC REBUILD_LOG('DBName','D:\Log folder\Logfile name.ldf')
</code></pre>
<p>This will create a new, empty logfile for the database and abandon the old one. Note that this will forcefully truncate the current transactions, so make sure you have a backup. The database needs to be in "Emergency Recovery" mode to use this command, as it will not roll back any in-process transactions that have been partially applied to the data, potentially damaging data integrity.</p>
<p>For full details about the process I used, see post 7 from this thread: <a href="http://www.sqlteam.com/forums/topic.asp?TOPIC%5FID=76785" rel="nofollow">http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=76785</a></p>
|
XUL and document.write() <p>I'm attempting to create a simple firefox extension and am stumbling on what I'm allowed to do in a XUL window.</p>
<p>I'd like to use document.write or get a handle on a textarea to collect data and display it when a button is clicked. </p>
<p>Are there any tutorials on how to do this? From what I've been reading, people have suggested opening a new window and writing to it, but my goal is a persistent window at the bottom of the browser.</p>
| <p>I wrote a simple XUL application using xulrunner. Try this : <a href="http://plindenbaum.blogspot.com/2009/02/standalone-xul-application-translating.html" rel="nofollow">http://plindenbaum.blogspot.com/2009/02/standalone-xul-application-translating.html</a></p>
<p>Later when your application will be correctly running you will transform it into an extension.</p>
<p>Hope it helps.</p>
|
PHP: socket listen problem <p>Here is my code:</p>
<pre><code><?php
$host = "127.0.0.1";
$portListen = 1234;
$portSend = 1240;
// create socket
$sSender = socket_create(AF_INET, SOCK_STREAM, 0);
socket_connect($sSender, $host, $portListen);
socket_write($sSender, "test", strlen ("test"));
$sListen = socket_create(AF_INET, SOCK_STREAM, 0);
socket_set_option($sListen, SOL_SOCKET, SO_REUSEADDR, 1);
socket_bind($sListen, $host, $portSend);
socket_listen($sListen,1);
$dataSock = socket_accept($sListen);
echo socket_read($dataSock, 3, PHP_NORMAL_READ);
// close sockets
socket_close($sSender);
socket_close($sListen);
?>
</code></pre>
<p>I send "test" to another application, it receives, and send back "ack". Problem is, I can only do it once. If I refresh, I get the address is already used error. I tried the solutions suggested on <a href="http://my.php.net/manual/en/function.socket-close.php" rel="nofollow">php.net</a> but to no avail. Trying to socket_shutdown() before socket_close() only give me not connected warning, and upon refreshing will give me a never ending loading.</p>
<p>From what I understand the reason socket is not immediately closed is because there is still data in the buffer. But as you can see I explicitly state to listen to only 1 connection. Plus I am only sending 3 characters from my application and reading 3 in this script.</p>
<p>What am I doing wrong?</p>
<p>edit: The reason I'm using 2 sockets is because I cannot listen() after write() which give me socket is already connected error. Skipping listen() and going straight for read() after write() give me invalid argument error.</p>
| <p>I see, after having a few hours sleep and re-analyzing my code and the documentations, I managed to fix everything. You guys are right, 1 socket is indeed enough and the correct way:</p>
<pre><code><?php
$host = "127.0.0.1";
$portListen = 1234;
$sSender = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");
socket_connect($sSender, $host, $portListen) or die("Could not connect\n");
socket_write($sSender, "test", strlen ("test")) or die("Could not write output\n");
echo socket_read($sSender, 3, PHP_NORMAL_READ);
socket_close($sSender);
?>
</code></pre>
<p>So simple!</p>
|
Wiring up WCF client side caching? <p>My application uses client side enterprise caching; I would like to avoid writing code for each and every cacheable call and wondered if there is a solution such that WCF client side calls can be cached, even for async calls.</p>
<p>Can this be done with WCF "behaviour" or some other means? Code examples?</p>
| <p>I did this the other day with Generic Extension methods on the WCF service client (DataServiceClient). It uses Actions and Funcs to pass around the actual ServiceClient calls. The final client usage syntax is a little funky (if you don't like lambdas), but this method does FaultException/Abort wrapping AND caching: </p>
<pre><code>public static class ProxyWrapper
{
// start with a void wrapper, no parameters
public static void Wrap(this DataServiceClient _svc, Action operation)
{
bool success = false;
try
{
_svc.Open();
operation.Invoke();
_svc.Close();
success = true;
}
finally
{
if (!success)
_svc.Abort();
}
}
// next, a void wrapper with one generic parameter
public static void Wrap<T>(this DataServiceClient _svc, Action<T> operation, T p1)
{
bool success = false;
try
{
_svc.Open();
operation.Invoke(p1);
_svc.Close();
success = true;
}
finally
{
if (!success)
_svc.Abort();
}
}
// non-void wrappers also work, but take Func instead of Action
public static TResult Wrap<T, TResult>(this DataServiceClient _svc, Func<T, TResult> operation, T p1)
{
TResult result = default(TResult);
bool success = false;
try
{
_svc.Open();
result = operation.Invoke(p1);
_svc.Close();
success = true;
}
finally
{
if (!success)
_svc.Abort();
}
return result;
}
}
</code></pre>
<p>On the client side, we have to call them like this:</p>
<pre><code> internal static DBUser GetUserData(User u)
{
DataServiceClient _svc = new DataServiceClient();
Func<int, DBUser> fun = (x) => _svc.GetUserById(x);
return _svc.Wrap<int, DBUser>(fun, u.UserId);
}
</code></pre>
<p>See the plan here? Now that we have a generic set of wrappers for WCF calls, we can use the same idea to inject some cacheing. I went "low tech" here, and just started throwing around strings for the cache key name... You could do something more elegant with reflection, no doubt.</p>
<pre><code> public static TResult Cache<TResult>(this DataServiceClient _svc, string key, Func<TResult> operation)
{
TResult result = (TResult)HttpRuntime.Cache.Get(key);
if (result != null)
return result;
bool success = false;
try
{
_svc.Open();
result = operation.Invoke();
_svc.Close();
success = true;
}
finally
{
if (!success)
_svc.Abort();
}
HttpRuntime.Cache.Insert(key, result);
return result;
}
// uncaching is just as easy
public static void Uncache<T>(this DataServiceClient _svc, string key, Action<T> operation, T p1)
{
bool success = false;
try
{
_svc.Open();
operation.Invoke(p1);
_svc.Close();
success = true;
}
finally
{
if (!success)
_svc.Abort();
}
HttpRuntime.Cache.Remove(key);
}
</code></pre>
<p>Now just call Cache on your Reads and Uncache on your Create/Update/Deletes:</p>
<pre><code> // note the parameterless lambda? this was the only tricky part.
public static IEnumerable<DBUser> GetAllDBUsers()
{
DataServiceClient _svc = new DataServiceClient();
Func<DBUser[]> fun = () => _svc.GetAllUsers();
return _svc.Cache<DBUser[]>("AllUsers", fun);
}
</code></pre>
<p>I like this method because I didn't have to recode anything server-side, just my WCF proxy calls (which were admittedly a little brittle / smelly to have scattered about everywhere).</p>
<p>Substitute in your own WCF proxy conventions and standard caching procedures, and you're good to go. It's a lot of work to create all the generic wrapper templates at first too, but i only went up to two parameters and it helps all my caching operations share a single function signature (for now). Let me know if this works for you or if you have any improvements.</p>
|
MagickNet C++ Source Compilation Failure <p>I'm attempting to compile a working copy of the <a href="http://midimick.com/magicknet/" rel="nofollow">MagickNet</a> class library (DLL) using the sources from the ImageMagick and MagickNet libraries.</p>
<p>I was unable to obtain a copy of the MagickNet source files from the creator's homepage as it is currently down, so I was forced to obtain the files and C++ project file from <a href="ftp://133.37.44.6/pub/graphics/ImageMagick/dot-net/" rel="nofollow">here</a>, courtesy of a Google search.</p>
<p>Following the instructions stated <a href="http://www.imagemagick.org/script/install-source.php#windows" rel="nofollow">here</a> and <a href="http://72.14.235.132/search?q=cache%3Ahttp%3A%2F%2Fmidimick.com%2Fmagicknet%2Fstart.html" rel="nofollow">here</a>, I created a project using the "static multi-threaded DLL" option and compiled it, before moving to the MagickNet project file and compiling that as well, after making sure all the paths pointed to the right folders.</p>
<p>Even so, I keep receiving this error upon compilation:</p>
<pre><code>CORE_RL_magick_.lib(nt-base.obj) : error LNK2005: _DllMain@12 already defined in MSVCRT.lib(dllmain.obj)
</code></pre>
<p>I also receive 371 other errors, all of them related to an "unresolved external symbol xxxxxxxx", and a final 372nd error describing that I have "195 unresolved externals".</p>
<p>I managed to solve the DllMain error above by commenting out the DllMain declaration from the nt-base.c source file from the CORE_magick project in the ImageMagick solution, however the 372 other "unresolved externals" errors still remain.</p>
<p>I had performed a (Google) search for people with similar issues, and <a href="http://www.imagemagick.org/discourse-server/viewtopic.php?f=8&t=12585" rel="nofollow">some</a> have said that the author had offered a download of a pre-compiled MagickNet DLL which works 100%, however (as I mentioned earlier) his homepage appears to be inaccessible now.</p>
<p>I'm currently seeking one of these solutions:</p>
<ol>
<li>A solution to my compilation issue, as I may be making a mistake on my part since I'm not familiar with C++ at all,</li>
<li>A link to another MagickNet source files/project zip that is 100% confirmed to compile correctly with the latest version of ImageMagick,</li>
<li>A link to a 100% working precompiled copy of the MagickNet DLL, if anyone kept a copy from the author's homepage. It should be approximately 3MB as it contains the ImageMagick libraries as well.</li>
</ol>
<p>I would really appreciate any one of these solutions, as I desperately require ImageMagick's ability to manipulate and convert images, as well as MagickNet's ease of use. I can provide additional details if you need more information.</p>
<p>Also, I am using Visual Studio 2008 to compile the source files, and the supplied projects convert with no issues at all.</p>
| <p>I was just able to get past this and was successfully able to compile MagickNET against the latest version of ImageMagick. I had to do several things.</p>
<ol>
<li>Configured ImageMagick to use StaticMTDll.</li>
<li>Edited magick-config.h to undefine X11 support.</li>
<li>Removed the CORE_xlib project from the ImageMagick solution.</li>
<li>Clean/Rebuild of ImageMagick</li>
<li><p>Added the following lib files to the linker settings for MagickNet</p>
<p>CORE_DB_bzlib_.lib<br>
CORE_DB_coders_.lib<br>
CORE_DB_jbig_.lib<br>
CORE_DB_jpeg_.lib<br>
CORE_DB_magick_.lib<br>
CORE_DB_png_.lib<br>
CORE_DB_tiff_.lib<br>
CORE_DB_ttf_.lib<br>
CORE_DB_wand_.lib<br>
CORE_DB_wmf_.lib<br>
CORE_DB_zlib_.lib<br>
CORE_DB_libxml_.lib<br>
CORE_DB_jp2_.lib<br>
CORE_DB_lcms_.lib<br>
Ws2_32.lib </p></li>
<li><p>Built MagickNet</p></li>
</ol>
<p>I did have to make updates to MagickNet because methods have been deprecated since the source release on the MagickNet website. I'll try and put a repository online to share the entire solution.</p>
|
ModelState.AddModelError encodes HTML <p>I am noticing a weird issue when using ModelState.AddModelError to validate input on my forms. The output from Html.ValidationMessage is not the true HTML value but it's encoded value and so the CSS style is not applied to the error message.</p>
<p>Example:</p>
<pre><code>private string errorMessage = "<span class=\"negative\">{0}</span><br class=\"hid\" />";
ModelState.AddModelError("title", String.Format(errorMessage, "Tab title is required"));
</code></pre>
<p>The output is shown as:</p>
<pre><code><span class="field-validation-error">&lt;span class=&quot;negative&quot;&gt;URL is Required&lt;/span&gt;&lt;br class=&quot;hid&quot; /&gt;</span>
</code></pre>
<p>This didn't use to be the case with their earlier beta's and I am not sure what approach to take here.</p>
<p>Thanks
Nick</p>
| <p>There is another way to do it, too, without having to create your own extension.</p>
<p>Say for instance we have the following in one of our controllers:</p>
<pre><code>ModelState.AddModelError("Name", "<b>Please Use a Valid Person Name</b>");
</code></pre>
<p>We can then do the following in our view:</p>
<pre><code>@if(Html.ValidationMessageFor(x => x.Name) != null){
@Html.Raw(Html.ValidationMessageFor(x => x.Name).ToString())
}
</code></pre>
<p>The will prevent the error message of <code>'<b>Please Use a Valid Person Name</b>'</code> from being encoded.</p>
|
iPhone UIImageView animation woes <p>I'm having some problems with UIImageView animations. I've created three NSArray objects containing the images and created three methods that take a UIImageView and assigns the new animations to it. It works fantastic calling one of the three methods the first time but doing it another time crashes the simulator and device. Any Ideas?</p>
<pre><code>// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
// set the anims
slowAnimation = [NSArray arrayWithObjects:
[UIImage imageNamed:@"image1.jpg"],
[UIImage imageNamed:@"image2.jpg"],
nil];
defaultAnimation = [NSArray arrayWithObjects:
[UIImage imageNamed:@"image3.jpg"],
[UIImage imageNamed:@"image4.jpg"],
nil];
fastAnimation = [NSArray arrayWithObjects:
[UIImage imageNamed:@"image5.jpg"],
[UIImage imageNamed:@"image6.jpg"],
nil];
// load the default speed - this works once, but when applied a second time it crashes the simulator and device
[self setDefaultAnim:myUIImageViewObject];
[super viewDidLoad];
}
// animation switcher
-(void)setSlowAnim:(UIImageView *)imageView
{
[imageView stopAnimating];
imageView.animationImages = slowAnimation;
imageView.animationDuration = 0.4;
[imageView startAnimating];
}
-(void)setDefaultAnim:(UIImageView *)imageView
{
[imageView stopAnimating];
imageView.animationImages = defaultAnimation;
imageView.animationDuration = 0.4;
[imageView startAnimating];
}
-(void)setFastAnim:(UIImageView *)imageView
{
[imageView stopAnimating];
imageView.animationImages = fastAnimation;
imageView.animationDuration = 0.4;
[imageView startAnimating];
}
</code></pre>
<p>Error in log:</p>
<pre><code>[Session started at 2009-04-06 22:46:54 +0100.]
Loading program into debuggerâ¦
GNU gdb 6.3.50-20050815 (Apple version gdb-962) (Sat Jul 26 08:14:40 UTC 2008)
Copyright 2004 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB. Type "show warranty" for details.
This GDB was configured as "i386-apple-darwin".warning: Unable to read symbols for "/System/Library/Frameworks/UIKit.framework/UIKit" (file not found).
warning: Unable to read symbols from "UIKit" (not yet mapped into memory).
warning: Unable to read symbols for "/System/Library/Frameworks/CoreGraphics.framework/CoreGraphics" (file not found).
warning: Unable to read symbols from "CoreGraphics" (not yet mapped into memory).
Program loaded.
sharedlibrary apply-load-rules all
Attaching to program: `/Users/hello/Library/Application Support/iPhone Simulator/User/Applications/6DB7C45D-1A26-4775-9AE3-C30F3EBC9F83/PlateSpinner.app/PlateSpinner', process 345.
kill
quit
The Debugger has exited with status 0.
</code></pre>
| <p>I think you need to <code>retain</code> the three arrays you create in <code>viewDidLoad</code> -- you never call <code>alloc</code> on them, so you don't have ownership until you call <code>retain</code>.</p>
|
MbUnit: The most elegant way to compare doubles? <p>The code</p>
<pre><code>Assert.AreEqual (9.97320998018748d, observerPosition.CenterLongitude);
</code></pre>
<p>produces</p>
<pre><code>Expected Value & Actual Value : 9.97320998018748
Remark : Both values look the same when formatted but they
are distinct instances.
</code></pre>
<p>What is the most elegant way to compare two doubles for equality in MbUnit 3.0? I know I could round them up myself, but is there some MbUnit construct for this?</p>
<p>UPDATE: I consider my current "workaround" to be non-elegant:</p>
<pre><code>Assert.LessThan(
Math.Abs(9.97320998018748d - observerPosition.CenterLongitude),
0.0000001);
</code></pre>
| <p><a href="http://www.gallio.org/api/html/Overload_MbUnit_Framework_Assert_AreApproximatelyEqual.htm" rel="nofollow"><code>AreApproximatelyEqual</code></a> seems to be the "MbUnit construct for this":</p>
<blockquote>
<p>Verifies that an actual value
approximately equals some expected
value to within a specified delta.</p>
</blockquote>
<p>This seems to be similar to <a href="http://msdn.microsoft.com/en-us/library/ms243458.aspx" rel="nofollow"><code>Assert.AreEqual(double expected, double actual, double delta)</code></a></p>
|
How to get available network drive for mapping? <p>Is there any class or API available in C# to get available network drives or last available drive for mapping? For example "Z:". Something like this:</p>
<pre><code>string mappeddrive = MappDriveUtil.GetLastAvailableMappedDrive(); // utility class
</code></pre>
<p>Can I just scan the local and mapped drives to find out? How to scan all the local and mapped drives already in use if this is the way to find out?</p>
| <p>This is one of those questions that doesn't have a great answer. You can certainly use DriveInfo.GetDrives to enumerate all of the currently available drives. From that you can infer what drives were not mapped. </p>
<p>The problem though is that you can only tell what drives <strong>were</strong> not mapped not are not mapped. In between the call to GetDrives() and the actually mapping of the drive, it's entirely possible for someother program to come along and map the drive you've chosen. Your solution <strong>must</strong> take this possibility into account or it will suffer from reliability problems in this area. </p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.