instruction
stringlengths 0
30k
⌀ |
---|
|.net|database|transactions|com+| |
I did some tests a while ago and never figured out how to make this work.
The ingredients:
- COM+ transactional object (developed in VB6)
- .Net web application (with transaction) in IIS that...
makes a call to the COM+ component
updates a row in a SQL database
Testing:
Run the .Net application and force an exception.
Result:
The update made from the .Net application rolls back.
The update made by the COM+ object does not roll back.
If I call the COM+ object from an old ASP page the rollback works.
I know some people may be thinking "what?! COM+ and .Net you must be out of your mind!", but there are some places in this world where there still are a lot of COM+ components. I was just curious if someone ever faced this and if you figured out how to make this work. |
Request.Url will return you the [Uri][1] of the request. Once you have that, you can retrieve pretty much anything you want. To get the protocol, call the [Scheme][2] property.
Sample:
Uri url = Request.Url;
string protocol = url.Scheme;
Hope this helps.
[1]: http://msdn.microsoft.com/en-us/library/system.uri.aspx
[2]: http://msdn.microsoft.com/en-us/library/system.uri.scheme.aspx
|
Why does sqlite3-ruby-1.2.2 not work on OS X? |
|ruby|ruby-on-rails|sqlite|rubyonrails| |
I am running OS X 10.5, Ruby 1.8.6, Rails 2.1, and sqlite3-ruby 1.2.2 and I get the following error when trying to rake db:migrate on an app that works find connected to MySQL.
> rake aborted!
no such file to load -- sqlite3/database |
|ruby|ruby-on-rails|sqlite| |
Textual versus Graphical Programming Languages |
|graphicallanguage|labview|robotics|highschool| |
I am part of a high school robotics team, and there is some debate about which language to use to program our robot. We are choosing between C (or maybe C++) and LabVIEW. There are pros for each language.
C(++):
- Widely used
- Good preparation for the future (most programming positions require text-based programmers.)
- We can expand upon our C codebase from last year
- Allows us to better understand what our robot is doing.
LabVIEW
- Easier to visualize program flow (blocks and wires, instead of lines of code)
- Easier to teach (Supposedly...)
- "The future of programming is graphical." (Think so?)
- Closer to the Robolab background that some new members may have.
- Don't need to intimately know what's going on. Simply tell the module to find the red ball, don't need to know how.
This is a very difficult decision for us, and we've been debating for a while. Based on those pros for each language, and on the experience you've got, **what do you think the better option is?** Keep in mind that we aren't necessarily going for pure efficiency. We also hope to prepare our programmers for a future in programming.
Also:
- **Do you think that graphical languages such as LabVEIW are the future of programming?**
- **Is a graphical language easier to learn than a textual language?** I think that they should be about equally challenging to learn.
- Seeing as we are partailly rooted in helping people learn, **how much should we rely on prewritten modules, and how much should we try to write on our own?** ("Good programmers write good code, great programmers copy great code." But isn't it worth being a good programmer, first?)
Thanks for the advice! |
|labview|highschool|robotics|graphical-language| |
I am part of a high school robotics team, and there is some debate about which language to use to program our robot. We are choosing between C (or maybe C++) and LabVIEW. There are pros for each language.
C(++):
- Widely used
- Good preparation for the future (most programming positions require text-based programmers.)
- We can expand upon our C codebase from last year
- Allows us to better understand what our robot is doing.
LabVIEW
- Easier to visualize program flow (blocks and wires, instead of lines of code)
- Easier to teach (Supposedly...)
- "The future of programming is graphical." (Think so?)
- Closer to the Robolab background that some new members may have.
- Don't need to intimately know what's going on. Simply tell the module to find the red ball, don't need to know how.
This is a very difficult decision for us, and we've been debating for a while. Based on those pros for each language, and on the experience you've got, **what do you think the better option is?** Keep in mind that we aren't necessarily going for pure efficiency. We also hope to prepare our programmers for a future in programming.
Also:
- **Do you think that graphical languages such as LabVEIW are the future of programming?**
- **Is a graphical language easier to learn than a textual language?** I think that they should be about equally challenging to learn.
- Seeing as we are partailly rooted in helping people learn, **how much should we rely on prewritten modules, and how much should we try to write on our own?** ("Good programmers write good code, great programmers copy great code." But isn't it worth being a good programmer, first?)
Thanks for the advice!
|
Audio player on Windows Mobile |
|windows-mobile| |
I'm trying to develop specialized audio player for windows mobile devices (Professional ones). And I've ran into the problem an once.
There no compressed audio APIs on WM or I was unable to found house in documentation. Yes there are WM6 Sound API but it cannot even pause playback or seek to specified position. There are allways Windows Media Player on WM device but I've not found it APIs documentation.
So the question is: Is there simple way to play, pause, forward, rewind, getting playback position and getting audio file length on *compressed* audio of several popular formats? Any library? platform APIs? Anything? |
I don’t know “Avast”, but in Kaspersky if the configuration is set to high almost every installer fires an alarm (iTunes, Windows Update, everything) especially if the installer modify some registry key or open a port.
If avast checks for behavior and your program open a port probably that’s be the cause. |
Rebuild the setup file, check the exact file size.
Check the exact file size of the "suspected" setup file.
If the source code hasn't changed and the two file sizes are different, there's a pretty good chance it got contaminated in transit.
I'd do that as a bit of a sanity check first. |
ILMerge and Web Resources |
|c#|asp.net|ilmerge|webresource| |
We're attemtping to merge our DLL's into one for deployment, thus ILMerge. Almost everything seems to work great. We have a couple web controls that use `ClientScript.RegisterClientScriptResource` and these are 404-ing after the merge (These worked before the merge).
For example one of our controls would look like
namespace Company.WebControls
{
public class ControlA: CompositeControl, INamingContainer
{
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
this.Page.ClientScript.RegisterClientScriptResource(typeof(ControlA), "Company.WebControls.ControlA.js");
}
}
}
It would be located in Project WebControls, assembly Company.WebControls. Underneath would be ControlA.cs and ControlA.js. ControlA.js is marked as an embedded resource. In the AssemblyInfo.cs I include the following:
[assembly: System.Web.UI.WebResource("Company.WebControls.ControlA.js", "application/x-javascript")]
After this is merged into CompanyA.dll, what is the proper way to reference this web resource? The ILMerge command line is as follows (from the bin directory after the build): `"C:\Program Files\Microsoft\ILMerge\ILMerge.exe" /keyfile:../../CompanySK.snk /wildcards:True /copyattrs:True /out:Company.dll Company.*.dll`
Thanks in advance! |
You could use the Mutex class, but you will soon find out that you will need to implement the code to pass the arguments and such yourself. Well, I learned a trick when programming in WinForms when I read Chris Sell's book. This trick uses logic that is already available to us in the framework. I don't know about you, but when I learn about stuff I can reuse in the framework, that is usually the route I take instead of reinventing the wheel. Unless of course it doesn't do everything I want.
When I got into WPF, I came up with a way to use that same code, but in a WPF application. This solution should meet your needs based off your question.
First, we need to create our application class. In this class we are going override the OnStartup event and create a method called Activate, which will be used later.
public class SingleInstanceApplication : System.Windows.Application
{
protected override void OnStartup(System.Windows.StartupEventArgs e)
{
// Call the OnStartup event on our base class
base.OnStartup(e);
// Create our MainWindow and show it
MainWindow window = new MainWindow();
window.Show();
}
public void Activate()
{
// Reactivate the main window
MainWindow.Activate();
}
}
Second, we will need to create a class that can manage our instances. Before we go through that, we are actually going to reuse some code that is in the Microsoft.VisualBasic assembly. Since, I am using C# in this example, I had to make a reference to the assembly. If you are using VB.NET, you don't have to do anything. The class we are going to use is WindowsFormsApplicationBase and inherit our instance manager off of it and then leverage properties and events to handle the single instancing.
public class SingleInstanceManager : Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase
{
private SingleInstanceApplication _application;
private System.Collections.ObjectModel.ReadOnlyCollection<string> _commandLine;
public SingleInstanceManager()
{
IsSingleInstance = true;
}
protected override bool OnStartup(Microsoft.VisualBasic.ApplicationServices.StartupEventArgs eventArgs)
{
// First time _application is launched
_commandLine = eventArgs.CommandLine;
_application = new SingleInstanceApplication();
_application.Run();
return false;
}
protected override void OnStartupNextInstance(StartupNextInstanceEventArgs eventArgs)
{
// Subsequent launches
base.OnStartupNextInstance(eventArgs);
_commandLine = eventArgs.CommandLine;
_application.Activate();
}
}
Basically, we are using the VB bits to detect single instance's and process accordingly. OnStartup will be fired when the first instance loads. OnStartupNextInstance is fired when the application is re-run again. As you can see, I can get to what was passed on the command line through the event arguments. I set the value to an instance field. You could parse the command line here, or you could pass it to your application through the constructor and the call to the Activate method.
Third, it's time to create our EntryPoint. Instead of newing up the application like you would normally do, we are going to take advantage of our SingleInstanceManager.
public class EntryPoint
{
[STAThread]
public static void Main(string[] args)
{
SingleInstanceManager manager = new SingleInstanceManager();
manager.Run(args);
}
}
Well, I hope you are able to follow everything and be able take this implementation and make it your own.
|
You could use the Mutex class, but you will soon find out that you will need to implement the code to pass the arguments and such yourself. Well, I learned a trick when programming in WinForms when I read Chris Sell's book. This trick uses logic that is already available to us in the framework. I don't know about you, but when I learn about stuff I can reuse in the framework, that is usually the route I take instead of reinventing the wheel. Unless of course it doesn't do everything I want.
When I got into WPF, I came up with a way to use that same code, but in a WPF application. This solution should meet your needs based off your question.
First, we need to create our application class. In this class we are going override the OnStartup event and create a method called Activate, which will be used later.
public class SingleInstanceApplication : System.Windows.Application
{
protected override void OnStartup(System.Windows.StartupEventArgs e)
{
// Call the OnStartup event on our base class
base.OnStartup(e);
// Create our MainWindow and show it
MainWindow window = new MainWindow();
window.Show();
}
public void Activate()
{
// Reactivate the main window
MainWindow.Activate();
}
}
Second, we will need to create a class that can manage our instances. Before we go through that, we are actually going to reuse some code that is in the Microsoft.VisualBasic assembly. Since, I am using C# in this example, I had to make a reference to the assembly. If you are using VB.NET, you don't have to do anything. The class we are going to use is WindowsFormsApplicationBase and inherit our instance manager off of it and then leverage properties and events to handle the single instancing.
public class SingleInstanceManager : Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase
{
private SingleInstanceApplication _application;
private System.Collections.ObjectModel.ReadOnlyCollection<string> _commandLine;
public SingleInstanceManager()
{
IsSingleInstance = true;
}
protected override bool OnStartup(Microsoft.VisualBasic.ApplicationServices.StartupEventArgs eventArgs)
{
// First time _application is launched
_commandLine = eventArgs.CommandLine;
_application = new SingleInstanceApplication();
_application.Run();
return false;
}
protected override void OnStartupNextInstance(StartupNextInstanceEventArgs eventArgs)
{
// Subsequent launches
base.OnStartupNextInstance(eventArgs);
_commandLine = eventArgs.CommandLine;
_application.Activate();
}
}
Basically, we are using the VB bits to detect single instance's and process accordingly. OnStartup will be fired when the first instance loads. OnStartupNextInstance is fired when the application is re-run again. As you can see, I can get to what was passed on the command line through the event arguments. I set the value to an instance field. You could parse the command line here, or you could pass it to your application through the constructor and the call to the Activate method.
Third, it's time to create our EntryPoint. Instead of newing up the application like you would normally do, we are going to take advantage of our SingleInstanceManager.
public class EntryPoint
{
[STAThread]
public static void Main(string[] args)
{
SingleInstanceManager manager = new SingleInstanceManager();
manager.Run(args);
}
}
Well, I hope you are able to follow everything and be able use this implementation and make it your own.
|
You could use the Mutex class, but you will soon find out that you will need to implement the code to pass the arguments and such yourself. Well, I learned a trick when programming in WinForms when I read [Chris Sell's book][1]. This trick uses logic that is already available to us in the framework. I don't know about you, but when I learn about stuff I can reuse in the framework, that is usually the route I take instead of reinventing the wheel. Unless of course it doesn't do everything I want.
When I got into WPF, I came up with a way to use that same code, but in a WPF application. This solution should meet your needs based off your question.
First, we need to create our application class. In this class we are going override the OnStartup event and create a method called Activate, which will be used later.
public class SingleInstanceApplication : System.Windows.Application
{
protected override void OnStartup(System.Windows.StartupEventArgs e)
{
// Call the OnStartup event on our base class
base.OnStartup(e);
// Create our MainWindow and show it
MainWindow window = new MainWindow();
window.Show();
}
public void Activate()
{
// Reactivate the main window
MainWindow.Activate();
}
}
Second, we will need to create a class that can manage our instances. Before we go through that, we are actually going to reuse some code that is in the Microsoft.VisualBasic assembly. Since, I am using C# in this example, I had to make a reference to the assembly. If you are using VB.NET, you don't have to do anything. The class we are going to use is WindowsFormsApplicationBase and inherit our instance manager off of it and then leverage properties and events to handle the single instancing.
public class SingleInstanceManager : Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase
{
private SingleInstanceApplication _application;
private System.Collections.ObjectModel.ReadOnlyCollection<string> _commandLine;
public SingleInstanceManager()
{
IsSingleInstance = true;
}
protected override bool OnStartup(Microsoft.VisualBasic.ApplicationServices.StartupEventArgs eventArgs)
{
// First time _application is launched
_commandLine = eventArgs.CommandLine;
_application = new SingleInstanceApplication();
_application.Run();
return false;
}
protected override void OnStartupNextInstance(StartupNextInstanceEventArgs eventArgs)
{
// Subsequent launches
base.OnStartupNextInstance(eventArgs);
_commandLine = eventArgs.CommandLine;
_application.Activate();
}
}
Basically, we are using the VB bits to detect single instance's and process accordingly. OnStartup will be fired when the first instance loads. OnStartupNextInstance is fired when the application is re-run again. As you can see, I can get to what was passed on the command line through the event arguments. I set the value to an instance field. You could parse the command line here, or you could pass it to your application through the constructor and the call to the Activate method.
Third, it's time to create our EntryPoint. Instead of newing up the application like you would normally do, we are going to take advantage of our SingleInstanceManager.
public class EntryPoint
{
[STAThread]
public static void Main(string[] args)
{
SingleInstanceManager manager = new SingleInstanceManager();
manager.Run(args);
}
}
Well, I hope you are able to follow everything and be able use this implementation and make it your own.
[1]: http://www.sellsbrothers.com/writing/wfbook/ |
I was able to do it on using KeyPress event.
Here's the code example:
Private Sub SingleLineTextBox_ KeyPress(ByRef KeyAscii As Integer)
If KeyAscii = 10 _
or KeyAscii = 13 Then
'10 -> Ctrl-Enter. AKA ^J or ctrl-j
'13 -> Enter. AKA ^M or ctrl-m
KeyAscii = 0 'clear the the KeyPress
End If
End Sub |
I'm looking for a way to delete a file which is locked by another process using C#. I suspect the method must be able to find which process is locking the file (perhaps by tracking the handles, although im not sure how to do this in c#) then close that process before been able to complete the file delete using File.Delete()
Many thanks |
|c#|filesystems| |
.NET Multi Dimensional Array Printing |
|c#|.net|arrays| |
Let's say I have a .NET Array of n number of dimensions. I would like to foreach through the elements and print out something like:
[0, 0, 0] = 2
[0, 0, 1] = 32
And so on. I could write a loop using some the Rank and dimension functions to come up with the indices. Is there a built in function instead? |
Solving a linear equation |
|math|linear|solving| |
I need to programmatically solve a system of linear equations in C, Objective C, or (if needed) C++.
Here's an example of the equations:
-44.3940 = a * 50.0 + b * 37.0 + tx
-45.3049 = a * 43.0 + b * 39.0 + tx
-44.9594 = a * 52.0 + b * 41.0 + tx
From this, I'd like to get the best approximation for a, b, and tx. |
|math|system|linear-equation| |
Have you tried calling .SaveOrUpdateCopy()?
Failing that, you may have to identify and .Evict() the existing object before Attaching (.Update()) your "new" object. |
Have you tried calling .SaveOrUpdateCopy()?
It should work in all instances, if there is an entity by the same id in the session or if there is no entity at all. This is basically the catch-all method, as it converts a transient object into a persistent one (Save), updates the object if it is existing (Update) or even handles if the entity is a copy of an already existing object (Copy).
Failing that, you may have to identify and .Evict() the existing object before Attaching (.Update()) your "new" object.
This should be easy enough to do:
IPersistable entity = Whatever(); // This is the object we're trying to update
// (IPersistable has an id field)
session.Evict(session.Get(entity.GetType(), entity.Id));
session.SaveOrUpdate(entity);
Although the above code could probably do with some null checking for the .Get() call. |
Can I add an event listener to a databinding action in Flex? |
|apache-flex| |
I have a ComboBox that I bind to a standard HTTPService, I would like to add an event listener so that I can run some code after the ComboBox is populated from the data provider.
How can I do this?
|
|apache-flex|data-binding| |
Exception handling: Contract vs Exceptional approach |
|exception| |
I know two approaches to Exception handling, lets have a look at them.
1. Contract approach.
When a method does not do what it says it will do in the method header, it will throw an exception. Thus the method "promises" that it will do the operation, and if it fails for some reason, it will throw an exception.
2. Exceptional approach.
Only throw exceptions when something truly weird happens. You should not use exceptions when you can resolve the situation with normal control flow (If statements). You don't use Exceptions for control flow, as you might in the contract approach.
Lets use both approaches in different cases:
We have a Customer class that has a method called OrderProduct.
contract approach:
class Customer
{
public void OrderProduct(Product product)
{
if((m_credit - product.Price) < 0)
throw new NoCreditException("Not enough credit!");
// do stuff
}
}
exceptional approach:
class Customer
{
public bool OrderProduct(Product product)
{
if((m_credit - product.Price) < 0)
return false;
// do stuff
return true;
}
}
if !(customer.OrderProduct(product))
Console.WriteLine("Not enough credit!");
else
// go on with your life
Here I prefer the exceptional approach, as it is not truly Exceptional that a customer has no money assuming he did not win the lottery.
But here is a situation I err on the contract style.
Exceptional:
class CarController
{
// returns null if car creation failed.
public Car CreateCar(string model)
{
// something went wrong, wrong model
return null;
}
}
When I call a method called CreateCar, I damn wel expect a Car instance and some lousy null pointer, which can ravage my running code a dozen lines later. Thus I prefer contract to this one:
class CarController
{
public Car CreateCar(string model)
{
// something went wrong, wrong model
throw new CarModelNotKnownException("Model unkown");
return new Car();
}
}
Which do style do you use? What do you think is best general approach to Exceptions?
|
When setting cookies manually, use the following parameter syntax to the [header()][1] function:
header( "Set-Cookie: name=value; httpOnly" );
However, if you have PHP **5.2.0** or greater, then you can use the [setcookie()][2] and [setrawcookie()][3] functions. Simply set the 7th parameter to true, as per the syntax
bool setcookie( $name, $value, $expire, $path, $domain, $secure, $httponly )
bool setrawcookie( $name, $value, $expire, $path, $domain, $secure, $httponly )
(function syntax simplified for brevity). Enter NULL for parameters you wish to remain as default.
Please note that versions of PHP before 5.2.0 do have the setcookie functions, but the httpOnly parameter was not yet introduced.
[1]: http://uk.php.net/manual/en/function.header.php
[2]: http://uk.php.net/setcookie
[3]: http://uk.php.net/manual/en/function.setrawcookie.php |
When setting cookies manually, use the following parameter syntax to the [header()][1] function:
header( "Set-Cookie: name=value; httpOnly" );
However, if you have PHP **5.2.0** or greater, then you can use the [setcookie()][2] and [setrawcookie()][3] functions. Simply set the 7th parameter to true, as per the syntax
setcookie( $name, $value, $expire, $path, $domain, $secure, $httponly )
setrawcookie( $name, $value, $expire, $path, $domain, $secure, $httponly )
(function syntax simplified for brevity). Enter NULL for parameters you wish to remain as default.
Please note that versions of PHP before 5.2.0 do have the setcookie functions, but the httpOnly parameter was not yet introduced.
[1]: http://uk.php.net/manual/en/function.header.php
[2]: http://uk.php.net/setcookie
[3]: http://uk.php.net/manual/en/function.setrawcookie.php |
I agree with Pat. At this point in the game, writing your own code to deal with cross-browser compatibility given the available Javascript frameworks doesn't make a lot of sense. There's a framework for nearly any taste (some really quite tiny) and they've focused on really abstracting out all of the differences between the browsers. They're doing WAY more testing of it than you're likely to.
Something like jQuery or Yahoo's YUI (think how many people hit the Yahoo Javascript in a day and the variety of browsers) is just way more road-tested than any snippet you or I come up with. |
ASP.NET is "stateless" but it maintains state using Sessions. You can use them by default just using the Session[] keyword.
Look at [http://msdn.microsoft.com/en-us/library/ms972429.aspx][1] for some details from Microsoft.
[1]: http://msdn.microsoft.com/en-us/library/ms972429.aspx |
Call a RegisterType method with the type, and constrain it using generics. Then, instead of walking assemblies to find ITest implementors, just store them and create from there.
void RegisterType<T>() where T:ITest, new() {
}
|
Communication between between pages |
|asp.net| |
I want to enable an user to be able to communicate with other users through a site. I know that ASP.net is stateless, but what can I use for this synced communication? Java servlets?
Thank you |
Is this a file you created and added to the project or did it mysteriously show up?
You can maybe check your .csproj file and see how it is being referenced (it should be a simple xml file and you can search for CSC97.tmp).
Perhaps post the information you find so we can have more details to help solve your problem |
If you're using SQL Server 2005, you could use the FOR XML PATH command.
SELECT [VehicleID]
, [Name]
, (SELECT CAST(City + ', ' AS VARCHAR(MAX)) FROM [Location] WHERE (VehicleID = Vehicle.VehicleID) FOR XML PATH ('')) AS Locations
FROM [Vehicle]
It's a lot easier than using a cursor, and seems to work fairly well. |
As others have stated, the best performance comes from the bottom one since you are just rethrowing an existing object. The middle one is least correct because it looses the stack.
I personally use custom exceptions if I want to decouple certain dependencies in code. For example, I have a method that loads data from an XML file. This can go wrong in many different ways.
It could fail to read from the disk (FileIOException), the user could try to access it from somewhere where they are not allowed (SecurityException), the file could be corrupt (XmlParseException), data could be in the wrong format (DeserialisationException).
In this case, so its easier for the calling class to make sense of all this, all these exceptions rethrow a single custom exception (FileOperationException) so that means the caller does not need references to System.IO or System.Xml, but can still access what error occurred through an enum and any important information.
As stated, don't try to micro-optimize something like this, the act of throwing an exception at all is the slowest thing that occurs here. The best improvement to make is to try avoiding an exception at all.
<code><pre>
public bool Load(filepath)
{
if (File.Exists(filepath)) //Avoid throwing by checking state
{
//Wrap anyways in case something changes between check and operation
try { .... }
catch (IOException ioFault) { .... }
catch (OtherException otherFault) { .... }
return true; //Inform caller of success
}
else { return false; } //Inform caller of failure due to state
}
</pre></code> |
As others have stated, the best performance comes from the bottom one since you are just rethrowing an existing object. The middle one is least correct because it looses the stack.
I personally use custom exceptions if I want to decouple certain dependencies in code. For example, I have a method that loads data from an XML file. This can go wrong in many different ways.
It could fail to read from the disk (FileIOException), the user could try to access it from somewhere where they are not allowed (SecurityException), the file could be corrupt (XmlParseException), data could be in the wrong format (DeserialisationException).
In this case, so its easier for the calling class to make sense of all this, all these exceptions rethrow a single custom exception (FileOperationException) so that means the caller does not need references to System.IO or System.Xml, but can still access what error occurred through an enum and any important information.
As stated, don't try to micro-optimize something like this, the act of throwing an exception at all is the slowest thing that occurs here. The best improvement to make is to try avoiding an exception at all.
<pre><code>public bool Load(string filepath)
{
if (File.Exists(filepath)) //Avoid throwing by checking state
{
//Wrap anyways in case something changes between check and operation
try { .... }
catch (IOException ioFault) { .... }
catch (OtherException otherFault) { .... }
return true; //Inform caller of success
}
else { return false; } //Inform caller of failure due to state
}</code></pre> |
You could use the excellent <a href="http://www.codeplex.com/umbrella">Umbrella library</a>:
using nVentive.Umbrella.Extensions.Calendar;
DateTime beginning = DateTime.Now.BeginningOfWeek();
However, they *do* seem to have stored Monday as the first day of the week (see the property `nVentive.Umbrella.Extensions.Calendar.DefaultDateTimeCalendarExtensions.WeekBeginsOn`), so that previous localized solution is a bit better. Unfortunate.
**Edit**: looking closer at the question, it looks like Umbrella might actually work for that too:
// Or DateTime.Now.PreviousDay(DayOfWeek.Monday)
DateTime monday = DateTime.Now.PreviousMonday();
DateTime sunday = DateTime.Now.PreviousSunday();
Although it's worth noting that if you ask for the previous Monday on a Monday, it'll give you seven days back. But this is also true if you use `BeginningOfWeek`, which seems like a bug :(. |
+1 Verdana -- agree with pauldoo
A variable width font for coding is probably not to everyone's taste but I really like Verdana's legibility with ClearType. |
What is a good maintainability index using Visual Studio 2008 code analysis? |
|visual-studio|code-analysis| |
My company recently purchased TFS and I have started looking into the code analysis tools to help drive up code quality and noticed a good looking metric "maintainability index". Is anyone using this metric for code reviews/checkins/etc? If so, what is an acceptable index for developers to work toward? |
Parallelize Bash Script |
|bash| |
Lets say I have a loop in bash:
for foo in `some-command`
do
do-something $foo
done
`do-something` is cpu bound and I have a nice shiny 4 core processor. I'd like to be able to run up to 4 `do-something`'s at once.
The naive approach seems to be:
for foo in `some-command`
do
do-something $foo &
done
This will run *all* `do-something`s at once, but there are a couple downsides, mainly that do-something may also have some significant I/O which performing *all* at once might slow down a bit. The other problem is that this code block returns immediately, so no way to do other work when all the `do-something`s are finished.
How would you write this loop so there are always X `do-something`s running at once? |
Why not just do all the work in C# instead of using batch files?
I was bored so i wrote this real quick, it's just an outline of how I would do it since I don't know what the command line switches do or the file paths.
using System;
using System.IO;
using System.Text;
using System.Security;
using System.Diagnostics;
namespace asdf
{
class StackoverflowQuestion
{
private const string MSBUILD = @"path\to\msbuild.exe";
private const string BMAIL = @"path\to\bmail.exe";
private const string WORKING_DIR = @"path\to\working_directory";
private string stdout;
private Process p;
public void DoWork()
{
// build project
StartProcess(MSBUILD, "myproject.csproj /t:Build", true);
}
public void StartProcess(string file, string args, bool redirectStdout)
{
SecureString password = new SecureString();
foreach (char c in "mypassword".ToCharArray())
password.AppendChar(c);
ProcessStartInfo psi = new ProcessStartInfo();
p = new Process();
psi.WindowStyle = ProcessWindowStyle.Hidden;
psi.WorkingDirectory = WORKING_DIR;
psi.FileName = file;
psi.UseShellExecute = false;
psi.RedirectStandardOutput = redirectStdout;
psi.UserName = "builder";
psi.Password = password;
p.StartInfo = psi;
p.EnableRaisingEvents = true;
p.Exited += new EventHandler(p_Exited);
p.Start();
if (redirectStdout)
{
stdout = p.StandardOutput.ReadToEnd();
}
}
void p_Exited(object sender, EventArgs e)
{
if (p.ExitCode != 0)
{
// failed
StringBuilder args = new StringBuilder();
args.Append("-s k2smtpout.secureserver.net ");
args.Append("-f build@example.com ");
args.Append("-t josh@example.com ");
args.Append("-a \"Build failed.\" ");
args.AppendFormat("-m {0} -h", stdout);
// send email
StartProcess(BMAIL, args.ToString(), false);
}
}
}
} |
I have made the switch, since you pointed out it will be the preferred way for microsoft shops. The switch was pretty trivial and as Mike pointed out it ships with the webform view engine as the default, but like Mike also said you can still take advantage of the views you wrote in brail and nvelocity with the [MvcContrib][1] project. ASP.NET MVC, doesn't tie you to a direct ViewEngine, you can use any ViewEngine you want. I don't necessarily think this is a difference.
The biggest difference I found was grouping my controllers and views. In MonoRail you could do this easily with the ControllerDetails attribute, I was able to easily get around this limitation by coding my own, but wish the functionality was built in. I did it by creating my own ViewLocator and creating a ActionFilterAttribute.
[1]: http://www.mvccontrib.org |
Read the code of other (good) javascript apps and see how they handle things. But I start out with a file per class. But once its ready for production, I would combine the files into one large file and minify.
The only reason, I would not combine the files, is if I didn't need all the files on all the pages. |
Boxed values are [data structures](http://en.wikipedia.org/wiki/Data_structure) that are minimal wrappers around [primitive types](http://en.wikipedia.org/wiki/Primitive_type)*. Boxed values are typically stored as pointers to objects on [the heap](http://en.wikipedia.org/wiki/Dynamic_memory_allocation).
Thus, boxed values use more memory and take at minimum two memory lookups to access: once to get the pointer, and another to follow that pointer to the primitive. Obviously this isn't the kind of thing you want in your inner loops. On the other hand, boxed values typically play better with other types in the system. Since they are first-class data structures in the language, they have the expected metadata and structure that other data structures have.
In Java and Haskell generic collections can't contain unboxed values. Generic collections in .NET can hold unboxed values with no penalties. Where Java's generics are only used for compile-time type checking, .NET will [generate specific classes for each generic type instantiated at run time](http://msdn.microsoft.com/en-us/library/f4a6ta2h.aspx).
Java and Haskell have unboxed arrays, but they're distinctly less convenient than the other collections. However, when peak performance is needed it's worth a little inconvenience to avoid the overhead of boxing and unboxing.
\* For this discussion, a primitive value is any that can be stored on [the call stack](http://en.wikipedia.org/wiki/Call_stack), rather than stored as a pointer to a value on the heap. Frequently that's just the machine types (ints, floats, etc), structs, and sometimes static sized arrays. .NET-land calls them value types (as opposed to reference types). Java folks call them primitive types. Haskellions just call them unboxed.
\** I'm also focusing on Java, Haskell, and C# in this answer, because that's what I know. For what it's worth, Python, Ruby, and Javascript all have exclusively boxed values. This is also known as the "Everything is an object" approach. |
Quick followup question - can you use the "runas" command from an MSBuild script? If so, wouldn't you be able to simply impersonate another user with runas /user:dsfsdf /password:dfdf sc.exe ... (or similiar - I haven't researched the command-line options)? |
The best answer I have ever heard about using the provided type aliases in C# comes from Jeffrey Richter in his book [CLR Via C#][1]. Here are his 3 reasons:
> - I've seen a number of developers confused, not knowing whether to use **string** or **String** in their code. Because in C# the string (a keyword) maps exactly to System.String (an FCL type), there is no difference and either can be used.
- In C#, **long** maps to **System.Int64**, but in a different programming language, **long** could map to an **Int16** or **Int32**. In fact, C==/CLI does in fact treat long as an **Int32**. Someone reading source code in one language could easily misinterpret the code's intention if he or she were used to programming in a different programming language. In fact, most languages won't even treat **long** as a keyword and won't compile code that uses it.
- The FCL has many methods that have type names as part of their method names. For example, the BinaryReader type offers methods such as ReadBoolean, ReadInt32, ReadSingle, and so on, and the System.Convert type offers methods such as ToBoolean, ToInt32, ToSingle, and so on. Although it's legal to write the following code, the line with float feels very unnatural to me, and it's not obvious that the line is correct:
BinaryReader br = new BinaryReader(...);
float val = br.ReadSingle(); // Ok, but feels unnatural
Single val = br.ReadSingle(); // OK and feels good
So there you have it. I think these are all really good points. I however, don't find myself using Jeffrey's advice in my own code. Maybe I am too stuck in my C# world but I end up trying to make my code look like the framework code.
[1]: http://www.amazon.com/CLR-via-Second-Pro-Developer/dp/0735621632/ref=pd_bbs_sr_1?ie=UTF8&s=books&qid=1218840666&sr=8-1 |
The best answer I have ever heard about using the provided type aliases in C# comes from Jeffrey Richter in his book [CLR Via C#][1]. Here are his 3 reasons:
> - I've seen a number of developers confused, not knowing whether to use **string** or **String** in their code. Because in C# the string (a keyword) maps exactly to System.String (an FCL type), there is no difference and either can be used.
- In C#, **long** maps to **System.Int64**, but in a different programming language, **long** could map to an **Int16** or **Int32**. In fact, C==/CLI does in fact treat long as an **Int32**. Someone reading source code in one language could easily misinterpret the code's intention if he or she were used to programming in a different programming language. In fact, most languages won't even treat **long** as a keyword and won't compile code that uses it.
- The FCL has many methods that have type names as part of their method names. For example, the **BinaryReader** type offers methods such as **ReadBoolean**, **ReadInt32**, **ReadSingle**, and so on, and the **System.Convert** type offers methods such as **ToBoolean**, **ToInt32**, **ToSingle**, and so on. Although it's legal to write the following code, the line with float feels very unnatural to me, and it's not obvious that the line is correct:
BinaryReader br = new BinaryReader(...);
float val = br.ReadSingle(); // Ok, but feels unnatural
Single val = br.ReadSingle(); // OK and feels good
So there you have it. I think these are all really good points. I however, don't find myself using Jeffrey's advice in my own code. Maybe I am too stuck in my C# world but I end up trying to make my code look like the framework code.
[1]: http://www.amazon.com/CLR-via-Second-Pro-Developer/dp/0735621632/ref=pd_bbs_sr_1?ie=UTF8&s=books&qid=1218840666&sr=8-1 |
Best solution is to let IIS do it.
[IIS6 Compression](http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/502ef631-3695-4616-b268-cbe7cf1351ce.mspx?mfr=true) - most likely you need to [specify file types to be compressed](http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/502ef631-3695-4616-b268-cbe7cf1351ce.mspx?mfr=true) like .jpg, .png, .gif types, etc.
Caching will come from making sure that the correct headers are being sent to the client from code, and i believe there is a setting you can set in IIS that enables it for static content, but i'm not sure on that one. |
Has anybody used Google Performance Tools? |
|c++|c|performance|multithreading|malloc| |
Looking for feedback on :
<http://code.google.com/p/google-perftools/wiki/GooglePerformanceTools> |
|performance|multithreading|malloc| |
+1 for TextMate on OSX.
See also answers to [this question][1]. I [recommend][2] trying NetBeans if you're on Windows.
[1]: http://stackoverflow.com/questions/16064/what-ide-to-use-for-developing-in-ruby-on-rails-on-windows#16086
[2]: http://stackoverflow.com/questions/16064/what-ide-to-use-for-developing-in-ruby-on-rails-on-windows#16086 |
Understanding Pointers |
|c++|c| |
Why are pointers such a leading factor of confusion for many new, and even old, college level students in the C/C++ language? Are there any tools or thought processes that helped you understand how pointers work at the variable, function, and beyond level?
What are some good practice things that can be done to bring somebody to the level of, "Ah-hah, I got it," without getting them bogged down in the overall concept? Basically, drill like scenarios. |
|pointers|schools| |
When I first saw this, I thought "Great question! Neat answer, danb!"
After a little thought, I'm not so sure this is a good idea. It's a little like generating event handlers for all controls in an ASP.NET page, or generating CRUD procedures for all tables in a database. I think it's better to create them as needed for two reasons:
1. Less clutter from empty style declarations
2. Less temptation to misuse (or underuse) CSS by writing everything at the class level rather than using descendant selectors like (#navigation ul li a). |
use System.Xml.Linq.XElement and SetValue method. This will format the text (assuming a string), but also allows you to set xml as the value. |
Crystal Reports by [Business Objects][1] seems to be a popular choice.
I never wrote any reports in it myself, but other's in my team who did sometimes struggled getting the more complex reports to work.
It also might be a bit pricey, depending on your budget.
[1]: http://businessobjects.com |
Crystal Reports by [Business Objects][1] seems to be a popular choice.
I never wrote any reports in it myself, but others in my team who did sometimes struggled getting the more complex reports to work.
It also might be a bit pricey, depending on your budget.
[1]: http://businessobjects.com |
Is there any chance you could move from ASP to ASP.Net? Or are you looking at keeping it in classic ASP, but just cleaning it up. If at all possible, I would recommend moving as much as possible moving to .Net. It looks like you may be rewriting/reorganizing a lot of code anyway, so moving to .Net may not be a lot of extra effort.
|
Batch code indenters and beautifiers |
|codingstyle| |
Does anyone here know of good batch file code indenters or beautifiers?
Specifically for PHP, JS and SGML-languages.
Preferably with options as to style. |
|coding-style| |
php: access array value on the fly |
|php|arrays| |
in php, i often need to map a variable using an array ... but i can not seem to be able to do this in a one liner. c.f. example:
// the following results in an error:
echo array('a','b','c')[$key];
// this works, using an unnecessary variable:
$variable = array('a','b','c');
echo $variable[$key];
this is a minor problem, but it keeps bugging every once in a while ... i don't like the fact, that i use a variable for nothing ;) |
|php|arrays|codingstyle| |
|php|arrays|coding-style| |
Do you name controls on forms using the same convention as a private variable? |
|user-interface|oop|codingstyle| |
For some reason I never see this done. Is there a reason why not? For instance I like _blah for private variables, and at least in Windows Forms controls are by default private member variables, but I can't remember ever seeing them named that way. In the case that I am creating/storing control objects in local variables within a member function, it is especially useful to have some visual distinction. |
|user-interface|oop|coding-style| |
Similar to the above, but I think the best version is (slightly modified) from "perldoc -f readdir":
opendir(DIR, $somedir) || die "can't opendir $somedir: $!";
@dots = grep { (!/^\./) && -f "$somedir/$_" } readdir(DIR);
closedir DIR;
|
You can use a file system watcher to check when the file has been changed. It only becomes "changed" after whichever program had the file previously closes the file. I know you asked for C#, but my VB.Net is much better. Hope you or someone else can translate.
It tries to open the file, if it isn't available, it adds a watcher, and waits for the file to be changed. After the file is changed, it tries to open again. It throws an exception if it waits more than 120 seconds, because you may get caught in a situation where the file is never released. Also, I decided to add a timeout of waiting for the file change of 5 seconds, in case of the small possibility that the file was closed prior to the actual file watcher being created.
Public Sub WriteToFile(ByVal Path As String, ByVal FileName As String, ByVal Data() As Byte)
Dim FileOpen As Boolean
Dim File As System.IO.FileStream = Nothing
Dim StartTime As DateTime
Dim MaxWaitSeconds As Integer = 120
StartTime = DateTime.Now
FileOpen = False
Do
Try
File = New System.IO.FileStream(FilePath & FileName, IO.FileMode.Append)
FileOpen = True
Catch ex As Exception
If DateTime.Now.Subtract(StartTime).TotalSeconds > MaxWaitSeconds Then
Throw New Exception("Waited more than " & MaxWaitSeconds & " To Open File.")
Else
Dim FileWatch As System.IO.FileSystemWatcher
FileWatch = New System.IO.FileSystemWatcher(FilePath, FileName)
FileWatch.WaitForChanged(IO.WatcherChangeTypes.Changed,5000)
End If
FileOpen = False
End Try
Loop While Not FileOpen
If FileOpen Then
File.Write(Data, 0, Data.Length)
File.Close()
End If
End Sub |
function declaration isn't a prototype |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.