|
|
General posts about working with .NET C#...
“Open source OpenInviterTM (Open InviterTM) is a free import contacts (addressbook) script from email providers like Mail2World, Grafitti, Web.de, Aussiemail, Mail.in, Uk2, Clevergo, Canoe, LinkedIn, Inbox.com, FastMail, Pochta, India, GMail, Bigstring, Yahoo!, Evite, YouTube, Mail.ru, MSN, O2, OperaMail, Hushmail, AOL, IndiaTimes, Freemail, 5Fm, Live/Hotmail, Meta, Care2, Azet, Mail.com, Bordermail, Zapakmail, Lycos, Walla, Nz11, Popstarmail, Atlas, Inet, GMX.net, Doramail, KataMail, Libero, Techemail, Netaddress, Abv, Mynet.com, Yandex, Wp.pt, Rambler, Virgilio, Gawab, Terra, Sapo.pt, Kids, Apropo, Rediff, Interia or social portals like Bookcrossing, Xuqa, Kincafe, NetLog, Livejournal, Lovento, Orkut, Brazencareerist, Skyrock, Konnects, Plazes, Xing, Bebo, Perfspot, Faces, Xanga, Multiply, Flickr, Plurk, Friendfeed, Vimeo, Mydogspace, Famiva, Fdcareer, Hi5, Flixster, Plaxo, Vkontakte, Meinvz, Friendster, Tagged, Hyves, Ning, Mycatspace, MySpace, Koolro, Mevio, Last.fm, Motortopia, Facebook, Flingr, Eons, Cyworld, Badoo, Twitter. This contacts importer script is integrating with content management systems (aka CMS) like Drupal, phpizabi, Social Engine, Dating Pro, SimpleMachines Forum (SMF), PunBB, jamit job, PHPMELODY, Boonex Dolphin, myBB, nowFire, JamRoom, symfony, RoundCube, Vwebmail, PhpBB, joovili, Wordpress, vBulletin, Atmail5, Buddy Zone, phpFoX, Joomla, Joomla1.0. Open Inviter is written in PHP 5 (no database required but cURL or wget required) and running on any webserver (tested on Apache) offering advanced tell a friend features. OpenInviterTM is a free self hosted solution that does not use a third party gateway (or API) to import contacts.” http://openinviter.com/ Now…if only I had a PHP to C# converter…
|
|
|
Everybody who tries PowerShell has a conniption fit with the escape character and the comparison methods… Here’s the official answer (by Bruce Payette): Let’s talk about the most contentious design decision in the PowerShell language. And the winner is: why the heck did we not use the conventional symbols for comparison like “>”, “>=”, “<”, “<=”, “==”, and “!=” ? My, this was a touchy issue. The answer is that the “>” and “<” characters are used for output redirection. Since PowerShell is a shell and all shell languages in the last 30 years have used “>” and “<” for I/O redirection, people expected that PowerShell should do the same. During the first public beta of PowerShell, this topic generated discussions that went on for months. We looked at a variety of alternatives, such as modal parsing where sometimes “>” meant greater-than and sometimes it meant redirection. We looked at alternative character sequences for the operators like “:>” or “->”, either for redirection or comparison. We did usability tests and held focus groups, and in the end, settled on what we had started with. The redirection operators are “>” and “<”, and the comparison operators are taken from the UNIX test(1) command. We expect that, since these operators have a 30-year pedigree, they are adequate and appropriate to use in PowerShell. (We also expect that people will continue to complain about this decision, though hopefully not for 30 more years.) As I only know only one (1) user who uses Powershell, even though it fits a true need, I’ll propose that it was…the wrong design choice. At the very least, offer a ‘mode’ switch, maybe like @USETRADITIONALSYMBOLS=true. Grr.
|
I’ve been looking at providing Authenticated RSS Feeds…and the architecture – beyond the fact that it is not implemented widely – has not inspired much confidence in me. But the alternate – providing RSS feeds with a private Url (eg: an Uri with a user specific private token) is even worse: Another reason as to why it’s not a good idea: The website I work on offers custom RSS feeds based on keywords for registered users. That’s great if you have an RSS reader that runs on your desktop, but in Bloglines [et all], it has the unintended consequence that all these custom feeds become discoverable. It’s not so much a privacy problem, it’s more a gunking up the bloglines feed search problem. Link: http://techcrunch.com/2006/08/01/bloglines-will-block-your-feed-from-search/
|
|
|
Consistency. The key to not wasting time chasing down the cause… I came across the following last friday, buried down in the help docs of some assembly we’re using: If ContentTransferEncoding = MailFormat.QuotedPrintable, the body of the email will automatically be encoded to quoted-printable format. All other encoding schemes are left up to the user of the component. Now…why on earth only implement one of the 7 or so that were offered? Someone didn’t raise a hand and say “Excuse me… I see more problems than solutions with that implementation…can we have another 3-5 days to implement the other encoding solutions on the fly??!” Penny wise, pound foolish.
|
Aha…Just spend this morning fighting with iTextSharp, getting it to merge the output from the ibex4 FO Document converter with the output of Aspose’s Word Doc to PDF converter. The are several little quirks that are not show stoppers, but can cause one to lose time. For example, the classes do not implement IDispose so you can’t use the handy using(){…} syntax to ensure everything is tidy when you leave. The second is that it is finicky with the way one opens documents – if you don’t explicitly say so, it closes the underlying stream, and later gives you an annoyingly sparse error message. That said…what a great open source project (iTextSharp)! In case this helps: //Can't believe that none of these classes are disposable!
//And...after much head scratching, the following order is
//important (Open(), after CloseStream=false)
//or you'll end up with errors later when you
//outputPDFDocument.NewPage()
//as it will report that the document is closed (even
//when its property says it's open) because
the the underlying stream is closed...
Document outputPDFDocument = new Document();
PdfWriter pdfWriter = PdfWriter.GetInstance(outputPDFDocument, outputStream);
pdfWriter.CloseStream = false;
outputPDFDocument.Open();
using (MemoryStream memoryStream = new MemoryStream()){
//...
//Make the document…whatever it is…into the memory stream
//...
this.SerializedEntityDocumentGenerator.Generate(memoryStream);
//Rewind it:
memoryStream.Position = 0;
PdfReader pdfReader = new PdfReader(memoryStream);
pdfReader.ConsolidateNamedDestinations();
for (int pageNumber = 1; pageNumber <= pdfReader.NumberOfPages; pageNumber++){
//create new page on output document:
outputPDFDocument.NewPage();
PdfImportedPage importedPage =
pdfWriter.GetImportedPage(pdfReader, pageNumber);
pdfWriter.DirectContent.AddTemplate(importedPage, 0, 0);
}
pdfReader.Close();
}//~memoryStream
outputPDFDocument.Close();
pdfWriter.Close(); //note that this does not close stream ...
Links:
http://itextsharp.sourceforge.net/
|
"If you really need that kind of privacy, the reality is that search engines - including Google - do retain this information for some time and it's important, for example, that we are all subject in the United States to the Patriot Act and it is possible that all that information could be made available to the authorities." "If you have something that you don't want anyone to know, maybe you shouldn't be doing it in the first place," he said. Eric Schmidt (CEO of Google) http://www.theregister.co.uk/2009/12/11/dotzler_on_schmidtt/
|
|
|
|
|
I ran into [an unnamed tester] who went on and on about needing more typeless/fast/script languages… My response: a compiled language IS a unit test: one bloody big very comprehensive unit test. It’s the first check actually: it checks all those loose bits you’ve left through out your code while coding ‘fast’, and tells you about them. Up front.
|
Ah!…those interesting Quirks… static void Main() { try { Console.WriteLine(DateTime.Now); Console.WriteLine(DateTime.Now.ToUniversalTime()); Console.WriteLine(DateTime.MinValue); Console.WriteLine(DateTime.MinValue.ToUniversalTime());
Console.ReadLine(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } }
Gives:
------ S:\STUDIES\XAct.Study.UtcOfDateTimeMinValue.exe 1/10/2009 5:03:06 p.m. 1/10/2009 4:03:06 a.m. 1/01/0001 12:00:00 a.m. 1/01/0001 12:00:00 a.m. ------ Process returned 0
|
Here’s a list of best coding practices that i think are practical, and easily implementable. This post is hopefully a continuing work in progress …I’ve found that over time, I’ve developed a standard set of rules, that made sense to me. Sometimes, I bump into points of view that differ from mine, causing me to rethink my position… And sometimes my position changes…hence the updates to this post… Secondly, and this is a valid point to bring up…yes, all this extra work doesn’t happen for free… I’ve found that, pulling out the stops, documenting everything, creating unit tests for everything, adding validation, etc., adds about 50% of time to the estimated completion date. Bummer. On the other hand, I could scrap it all, write untested undocumented code… but I honestly don’t see the long term benefit for that. It just means I have to work a little longer, and read less email during work hours to get it done :-) Finally, a quick note about the colors I used: - The BLUE comments are points that, while pontificating from my soapbox, I notice I could bear with improving myself…
- The RED COMMENTS Issues that I still wonder about, and that I haven’t put to bed …and wouldn’t mind feedback on.
Read More »
|
In general, I find IsSubClassOf more rememberable…but IsAssignableFrom() generally ends up being more useful for tests. The reason for this is that IsSubClassOf doesn’t return true if A == A. This makes perfect sense…but I often want to test whether a class is of type A, or a subclass of A… In which case, the only way to test this succinctly is to use IsAssignableFrom – which is just about the same thing as IsSubClassOf, but reversed… The following results will demonstrate this better: class A { }
class B : A {}
class Program {
static void Main() {
Console.WriteLine(typeof(B).IsSubclassOf(typeof(A)));
Console.WriteLine(typeof(B).IsSubclassOf(typeof(B)));
Console.WriteLine("-----");
Console.WriteLine(typeof(A).IsAssignableFrom(typeof(A)));
Console.WriteLine(typeof(A).IsAssignableFrom(typeof(B)));
Console.WriteLine(typeof(B).IsAssignableFrom(typeof(A)));
Console.WriteLine(typeof(B).IsAssignableFrom(typeof(B)));
Console.WriteLine("-----");
Console.WriteLine(typeof(A).IsAssignableFrom(typeof(string)));
Console.WriteLine(typeof(int).IsAssignableFrom(typeof(string)));
Console.WriteLine(typeof(string).IsAssignableFrom(typeof(int)));
Console.WriteLine(typeof(double).IsAssignableFrom(typeof(int)));
Console.WriteLine(typeof(int).IsAssignableFrom(typeof(double)));
Console.ReadLine();
}
}
which returns:
------ E:\XActStudy\Scripts\script.IsSubClass.exe
True
False
-----
True
True
False
True
-----
False
False
False
False
False
------ Process returned 0
|
Not sure where to file this, but here’s an elegant trick to avoid a whole bunch of if/else statements when get the next position in a list of items: static void Main() {
try {
int[] items = new int[3];
for (int i=0;i<10;i++){
Console.WriteLine(
string.Format(
"Next Item: {0}",
(i+1) % items.Length
)
);
}
Console.ReadLine();
}
catch (Exception ex) {
Console.WriteLine(ex.ToString());
}
}
returns
------ E:\XActStudy\Scripts\script.AutoRotateNextPosition.exe
Next Item: 1
Next Item: 2
Next Item: 0
Next Item: 1
Next Item: 2
Next Item: 0
Next Item: 1
Next Item: 2
Next Item: 0
Next Item: 1
------ Process returned 0
And it nearly works as neatly when requesting the next position in the negative direction:
(just watch out for position 0….)
static void Main() {
try {
int[] items = new int[3];
for (int i=0;i<10;i++){
Console.WriteLine(
string.Format(
"Previous Item: {0}",
(i-1) % items.Length
)
);
}
Console.ReadLine();
}
catch (Exception ex) {
Console.WriteLine(ex.ToString());
}
}
------ E:\XActStudy\Scripts\script.AutoRotateNextPosition.exe
Next Item: -1
Next Item: 0
Next Item: 1
Next Item: 2
Next Item: 0
Next Item: 1
Next Item: 2
Next Item: 0
Next Item: 1
Next Item: 2
------ Process returned 0
|
I’ve always known that the formula for Fib(n) is Fn = Fn−1 + Fn−2 And always found its recursive nature a bit wasteful – actually: O(LOG2(n)). I’d seen cached recursive solutions like this one, which arguably improves things… A definite improvement is the (O(n)) solution private static int fibC(int n) {
if (n <= 1){return n;}
int a = 0;
int b = 1;
int c = 1;
for(int i = 2 ; i <= n ; i++) {
c = a + b;
a = b;
b = c;
}
return c;
}
and O(log n) solution found here.
But today, If found out about Binet’s Formula, which was used to write this:
static Int64 fibD(int n){
double phi = (1 + Math.Sqrt(5))/2;
double negPhi = (1 - Math.Sqrt(5)) / 2;
double r = (Math.Pow(phi, n) - Math.Pow(negPhi, n)) / Math.Sqrt(5);
return (Int64)r;
}
Which may simply be O(1).
Note:
The normal 4-byte integer can only contain values in range [-2^31,2^31-1] and we can only get actual nth Fibonacci number up to n = 46.
Hence the use of Int64.
http://en.wikipedia.org/wiki/Fibonacci_number
http://m3rlinez.blogspot.com/2007/07/blog-post.html
http://www.mcs.surrey.ac.uk/Personal/R.Knott/Fibonacci/fibFormula.html
|
I bet you didn’t expect that when you were using the ‘new’ method without the base class being marked as ‘virtual’: using System;
namespace QuickSharp {
class Plane {
public int Engines {
get {return 1;}
}
public virtual double TopSpeed {
get {return 300.0;}
}
}//Class:End
class Jet : Plane {
public new int Engines {
get {return 2;}
}
public override double TopSpeed {
get {return 900.0D;}
}
}//Class:End
class Program {
static void Main() {
Plane plane = new Jet();
Console.WriteLine("Plane: {0} [{1}]",
plane.TopSpeed, plane.Engines);
Jet jet = new Jet();
Console.WriteLine("Jet: {0} [{1}]",
jet.TopSpeed, jet.Engines);
Console.ReadLine();
}
}//Class:End
}
Results:
------ E:\XActStudy\Scripts\script.EnheritenceExample.exe
Plane top speed: 900 [1]
jet's top speed: 900 [2]
------ Process returned -532459699
|
Here’s a succinct post that covers the basics. | | constant | logarithmic | linear | | quadratic | cubic | | n | O(1) | O(log N) | O(N) | O(N log N) | O(N2) | O(N3) | | 1 | 1 | 1 | 1 | 1 | 1 | 1 | | 2 | 1 | 1 | 2 | 2 | 4 | 8 | | 4 | 1 | 2 | 4 | 8 | 16 | 64 | | 8 | 1 | 3 | 8 | 24 | 64 | 512 | | 16 | 1 | 4 | 16 | 64 | 256 | 4,096 | | 1,024 | 1 | 10 | 1,024 | 10,240 | 1,048,576 | 1,073,741,824 | | 1,048,576 | 1 | 20 | 1,048,576 | 20,971,520 | 1012 | 1016 |
|
|
|
I read so many posts and articles (the last one was an MSDN document, actually) where the following are gotten wrong that I started to not be so sure of which was which, and had to double check. So here: void foo(int a, char b); //a and b are parameters
int main()
{
foo(5, 'a'); //5 and 'a' are arguments
return 0;
}
|
I just came "Beginning C# 2008 By Christian Gross" Take a look at the 4 or 5 pages, starting with page 249, to get an a feel for the book. If the rest of the book is this dense with information, it's probably a must read book. Take a quick look here. The pages mentioned are a must read if you are trying to figure out order-of-execution issues such as in Spreadsheets. [ADDENDUM] It appears...that not everybody liked this book. In fact...the reviews were scathing! http://www.amazon.com/Beginning-C-2008-Novice-Professional/dp/1590598695 Yet..I am intrigued...The above problem...is not typically found in most intro-to-code books. So any book that deviates from the same-old-learn-just-enough-to-frustrate-yourself standard formulas of most code books deserves...attention... So I might just go and pick this one up before I write it off. Night. PS: When I get it, supposedly the source code can be found at: http://www.devspace.com/~christianhgross/files/Beg inningCSharp.zip
|
If this is true...and it works...and the economy remains bad enough that people decide its time to switch... Oh Hell. Startup Founders turn android into desktop OS Far more penetration power than Macs ...which is bound to hardware sales...this could spell real real trouble over the next 36 months.
|
I'm ...kicking myself for missing this until now... How long since this has been available, and I didn't see it before?!? This means that the code that it autogenerates is no longer the impossible to work with internal class: [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute(
"Microsoft.VisualStudio.Editors.SettingsDesigner. SettingsSingleFileGenerator", "9.0.0.0")
]
internal sealed partial class Settings :
global::System.Configuration.ApplicationSettingsBase {
...
}
Tell me this was added in VisualStudio 2008, and was not available in Visual Studio 2005 (I no longer have it installed so not easy to check how long I've been a gormless blind git and missed this...)
PS: Thank you! Thank you! Thank you, MS, for adding it, if you added it in Visual Studio 2008. This drove me batty no-end a year or so ago...
|
Interesting: Performance In terms of raw performance, the .NET Remoting plumbing provides the fastest communication when you use the TCP channel and the binary formatter. In almost all the tests that we carried out to compare the relative performance of ASP.NET Web services and .NET Remoting, ASP.NET Web services outperformed .NET Remoting endpoints that used the SOAP formatter with either the HTTP or the TCP channel. More interestingly, ASP.NET and .NET Remoting endpoints that used the binary formatter and the HTTP channel were very similar in performance. (See Performance Comparison: .NET Remoting vs. ASP.NET Web Services for more details.) Links:
|
I'm starting to really love QuickSharp (by Steve Walker) which is a very light IDE for coding .NET. Its the right mid-point between CSScript (missing an editor) and Visual Studio (too heavy of an editor). Especially that there's a new version out (1.3) available at http://sourceforge.net/projects/quicksharp/ But I just ran into a spot of trouble getting a SourceTrace to work...nothing was coming out, whereas the same code worked fine in Visual Studio. The Trace Flag Its easy to forget after a while that Tracing only works in Visual Studio, because Visual Studio sets the TRACE flag for both Debug and Release builds, by default. Whereas with QuickSharp, out of the box, has no flags defined for the compiler...including TRACE.
Easy Fix It's a small gotcha...but the good news is that QuickSharp is becoming very configurable, and you can easily solve this, as demonstrated in the image below (click to enlarge): 
|
|
|