|
1)A program returns a long string like the strings below, delimited by pipe character, where errorcode, error details, and long reason are stored. Write c# code to get the long code out of the response received.
0|R002|this is not a valid transaction.
1|R003|the card has expired.
2|R004|card code is invalid.
2)table tblcode has codes like the following, objective is to get the next code given the three digits unique code.e.g. Given DEL, NOI, UPA the next code is CDEL0002, CNOI0004, and CUPA0003
CUPA0001
CNOI0001
CUPA0002
CNOI0003
CDEL0001
write a function to achieve this .the function will get input parameter as, city code in 3 characters e.g. DEL,NOI,UPA and should return the next code as per logic above.
"Simplicity carried to the extreme becomes elegance."
-Jon Franklin
|
|
|
|
|
using System;
using System.Collections.Generic;
namespace CodesKata {
class Program {
static void Main(string[] args) {
var dumps = new List<errordump>();
var d1 = new ErrorDump("0|R002|this is not a valid transaction");
var d2 = new ErrorDump("1|R003|the card has expired");
var d3 = new ErrorDump("2|R004|card code is invalid");
var d4 = new ErrorDump("this is an invalid item / 5/ 1Z234J0952435");
dumps.AddRange(new[] {d1, d2, d3, d4});
foreach(var item in dumps) Console.WriteLine(item.LongCode);
Console.ReadLine();
}
}
public class ErrorDump {
private Boolean valid;
private readonly String error = String.Empty;
public ErrorDump(String dump) {
if(dump.Split('|').Length == 3) valid = true;
error = dump;
}
public String LongCode { get { return valid ? error.Split('|')[2] : String.Empty; } }
}
}
</errordump>
"Simplicity carried to the extreme becomes elegance."
-Jon Franklin
|
|
|
|
|
http://www.wotsit.org/
File format info on most files out there.
"Simplicity carried to the extreme becomes elegance."
-Jon Franklin
|
|
|
|
|
From http://binstock.blogspot.com/2008/04/perfecting-oos-small-classes-and-short.html
In The ThoughtWorks Anthology a new book from the Pragmatic Programmers, there is a fascinating essay called “Object Calisthenics” by Jeff Bay. It’s a detailed exercise for perfecting the writing of the small routines that demonstrate characterize good OO implementations. If you have developers who need to improve their ability to write OO routines, I suggest you have a look-see at this essay. I will try to summarize Bay’s approach here.
He suggests writing a 1000-line program with the constraints listed below. These constraints are intended to be excessively restrictive, so as to force developers out of the procedural groove. I guarantee if you apply this technique, their code will move markedly towards object orientation. The restrictions (which should be mercilessly enforced in this exercise) are:
1. Use only one level of indentation per method. If you need more than one level, you need to create a second method and call it from the first. This is one of the most important constraints in the exercise.
2. Don’t use the ‘else’ keyword. Test for a condition with an if-statement and exit the routine if it’s not met. This prevents if-else chaining; and every routine does just one thing. You’re getting the idea.
3. Wrap all primitives and strings. This directly addresses “primitive obsession.” If you want to use an integer, you first have to create a class (even an inner class) to identify it’s true role. So zip codes are an object not an integer, for example. This makes for far clearer and more testable code.
4. Use only one dot per line. This step prevents you from reaching deeply into other objects to get at fields or methods, and thereby conceptually breaking encapsulation.
5. Don’t abbreviate names. This constraint avoids the procedural verbosity that is created by certain forms of redundancy—if you have to type the full name of a method or variable, you’re likely to spend more time thinking about its name. And you’ll avoid having objects called Order with methods entitled shipOrder(). Instead, your code will have more calls such as Order.ship().
6. Keep entities small. This means no more than 50 lines per class and no more than 10 classes per package. The 50 lines per class constraint is crucial. Not only does it force concision and keep classes focused, but it means most classes can fit on a single screen in any editor/IDE.
7. Don’t use any classes with more than two instance variables. This is perhaps the hardest constraint. Bay’s point is that with more than two instance variables, there is almost certainly a reason to subgroup some variables into a separate class.
8. Use first-class collections. In other words, any class that contains a collection should contain no other member variables. The idea is an extension of primitive obsession. If you need a class that’s a subsumes the collection, then write it that way.
9. Don’t use setters, getters, or properties. This is a radical approach to enforcing encapsulation. It also requires implementation of dependency injection approaches and adherence to the maxim “tell, don’t ask.”
Taken together, these rules impose a restrictive encapsulation on developers and force thinking along OO lines. I assert than anyone writing a 1000-line project without violating these rules will rapidly become much better at OO. They can then, if they want, relax the restrictions somewhat. But as Bay points out, there’s no reason to do so. His team has just finished a 100,000-line project within these strictures.
"Simplicity carried to the extreme becomes elegance."
-Jon Franklin
|
|
|
|
|
Don't ask how I found it, but I stumbled upon LOLCODE[^] and decided to revisit some boilerplate code for posters who love the SMS speak. Personally I think the pidgin English code reply is a perfect response to pidgin English question. Maybe these people should choose the language, I think they'd be naturals at it.
HAI
CAN HAS STDIO?
I HAS A VAR
IM IN YR LOOP
UP VAR!!1
VISIBLE VAR
IZ VAR BIGGER THAN 10? KTHXBYE
IM OUTTA YR LOOP
KTHXBYE
HAI
CAN HAS STDIO?
DIAF 2 "Code needs implemented in C#"
KTHXBYE
“It is practically impossible to teach good programming to students that have had a prior exposure to BASIC: as potential programmers they are mentally mutilated beyond hope of regeneration.”
-Edsger Dijkstra
|
|
|
|
|
Design a class that is able to cache the type of an object for use in identity checking in a "choke" type method.
Should be able to avoid FxCop Performance Rule CA1800 Avoid Duplicate casts when possible due to cost.
“It is practically impossible to teach good programming to students that have had a prior exposure to BASIC: as potential programmers they are mentally mutilated beyond hope of regeneration.”
-Edsger Dijkstra
|
|
|
|
|
This code can get around CA1800 regarding duplicate casts, but triggers CA1004 Generic methods should provide type parameter. I deemed CA1004 not applicable because type inference for parameters is not necessary, it's being used for casting purposes. If there is another way to avoid CA1004, then I would like to hear it.
public class TypeCache {
private readonly Type actual;
private Object subject;
public TypeCache(Object cache) {
subject = cache;
actual = cache.GetType();
}
public Boolean IsA(Type proposed) {
return proposed.IsAssignableFrom(actual);
}
public Type CachedType {
get { return actual; }
}
public T Cast<t>() where T : class {
return TypeCheck.Cast<t>(subject);
}
}
public static class TypeCheck {
public static Boolean IsA<t>(Object check) where T : class {
return check.GetType().IsAssignableFrom(typeof(T));
}
public static T Cast<t>(Object subject) where T : class {
return subject as T;
}
}
</t></t></t></t>
“It is practically impossible to teach good programming to students that have had a prior exposure to BASIC: as potential programmers they are mentally mutilated beyond hope of regeneration.”
-Edsger Dijkstra
|
|
|
|
|
Design a synchronization mechanism that all instances of a command type use to ensure that only one instance has execution rights at one time. Assume an asynchronous command with timeout.
“It is practically impossible to teach good programming to students that have had a prior exposure to BASIC: as potential programmers they are mentally mutilated beyond hope of regeneration.”
-Edsger Dijkstra
|
|
|
|
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace SynchroKata {
public partial class Form1 : Form {
SynchroServer serv;
public Form1() {
InitializeComponent();
serv = new SynchroServer(this.lbNumberPending);
}
private void btnAdd_Click(object sender, EventArgs e) {
serv.RunCommand(new SynchroCommand());
}
}
public sealed class SynchroServer {
private Label display;
private Int32 count;
public SynchroServer(Label label) {
display = label;
}
public void RunCommand(SynchroCommand command) {
Console.WriteLine("Command started");
command.OnWorkComplete += new EventHandler(command_OnWorkComplete);
count++;
SetDisplay(count);
ThreadPool.QueueUserWorkItem(new WaitCallback(command.CommandImpl));
}
private void SetDisplay(int cnt) {
lock (this) {
display.Invoke(new MethodInvoker(delegate { display.Text = cnt.ToString(); }));
}
}
void command_OnWorkComplete(object sender, EventArgs e) {
count--;
SetDisplay(count);
((SynchroCommand)sender).OnWorkComplete -= command_OnWorkComplete;
}
}
public sealed class SynchroCommand {
private static Object sLock = new Object();
public void CommandImpl(Object obj) {
lock (sLock) {
Thread.Sleep(3000);
FireOnWorkComplete(this, new EventArgs());
}
}
private Object syncLockA = new Object();
private EventHandler onWorkComplete;
public event EventHandler OnWorkComplete {
add { lock (syncLockA) { onWorkComplete += value; } }
remove { lock (syncLockA) { onWorkComplete -= value; } }
}
private void FireOnWorkComplete(Object sender, EventArgs args) {
if (onWorkComplete != null) { onWorkComplete(sender, args); }
}
}
}
“It is practically impossible to teach good programming to students that have had a prior exposure to BASIC: as potential programmers they are mentally mutilated beyond hope of regeneration.”
-Edsger Dijkstra
|
|
|
|
|
Problem: design a CSV writer for your application.
“It is practically impossible to teach good programming to students that have had a prior exposure to BASIC: as potential programmers they are mentally mutilated beyond hope of regeneration.”
-Edsger Dijkstra
|
|
|
|
|
Didn't get any time to put this one together. Back burner for now. I will come back to it in a little while
“It is practically impossible to teach good programming to students that have had a prior exposure to BASIC: as potential programmers they are mentally mutilated beyond hope of regeneration.”
-Edsger Dijkstra
|
|
|
|
|
Problem: Develop a generic implementation of a status byte/halfword/word/dword.
1) support named flags
2) support changing values
3) initialization with entire value
“It is practically impossible to teach good programming to students that have had a prior exposure to BASIC: as potential programmers they are mentally mutilated beyond hope of regeneration.”
-Edsger Dijkstra
|
|
|
|
|
This problem is turning out to be much more difficult than expected. Problems arising are related to the fact that the enum hides it's underlying type, so it can't use that to constrain the generic type.
public class StatusField<t> where T : struct{
private T template;
private ValueType v;
private StatusField(ValueType initialValue) {
v = initialValue;
template = new T();
}
public Object UnderlyingValue {
get {
return v;
}
set {
v = (ValueType)value;
}
}
public Boolean this[T index] {
get {
if (Enum.IsDefined(typeof(T), index)) {
return false;
} else {
throw new IndexOutOfRangeException("Field is not defined");
}
}
set {
}
}
public static StatusField<t> New(ValueType value) {
return new StatusField<t>(value);
}
}
</t></t></t>
“It is practically impossible to teach good programming to students that have had a prior exposure to BASIC: as potential programmers they are mentally mutilated beyond hope of regeneration.”
-Edsger Dijkstra
|
|
|
|
|
Latest attempt. Putting this on the back burner. I couldn't get the type safety that I wanted, but this is will work.
namespace StatusByteKata {
class Program {
static void Main(string[] args) {
StatusField<alarms> field = StatusField<alarms>.New(Alarms.Battery | Alarms.Motion);
Console.WriteLine(field.UnderlyingValue);
Console.WriteLine(field[Alarms.Battery]);
Console.ReadLine();
}
}
[Flags]
public enum Alarms : byte {
[Description("Motion Alarm")]
Motion = 0x01,
[Description("Fire Alarm")]
Fire = 0x02,
[Description("Temperature Alarm")]
Temperature = 0x04,
[Description("Low Battery Alarm")]
Battery = 0x08,
[Description("Gas Alarm")]
Gas = 0x10,
[Description("Service Request")]
ServiceRequest = 0x20,
[Description("Camera Status")]
Camera = 0x40
}
public class StatusField<T>
where T : struct {
#region Members
private T template;
private ValueType sword;
#endregion
private StatusField(ValueType initialValue) {
template = new T();
if (template is Enum) {
Type t = template.GetType();
if (t.GetCustomAttributes(typeof(FlagsAttribute), false).Length == 0) {
throw new System.InvalidCastException("Requires Enum that defines FlagsAttribute");
}
sword = initialValue;
} else {
throw new System.InvalidCastException("Could not convert generic type");
}
}
public Object UnderlyingValue {
get {
return sword;
}
set {
sword = (ValueType)value;
}
}
public Boolean this[T index] {
get {
if (Enum.IsDefined(typeof(T), index)) {
Object x = Convert.ChangeType(index, typeof(Int64));
Int64 temp1 = (Int64)x;
Object y = Convert.ChangeType(sword, typeof(Int64));
Int64 temp2 = (Int64)y;
return (temp1 & temp2) == temp1;
} else {
throw new IndexOutOfRangeException("Field is not defined");
}
}
set {
if (Enum.IsDefined(typeof(T), index)) {
} else {
throw new IndexOutOfRangeException("Field is not defined");
}
}
}
public static StatusField<T> New(ValueType value) {
return new StatusField<T>(value);
}
}
}
“It is practically impossible to teach good programming to students that have had a prior exposure to BASIC: as potential programmers they are mentally mutilated beyond hope of regeneration.”
-Edsger Dijkstra
modified on Monday, June 9, 2008 1:58 PM
|
|
|
|
|
Devise a method of parsing variable length binary data from a Byte[] array. Returned data must be in List<record> format.
1) Data structures are stacked in the array and have 4*n Bytes length.
2) Data structures start with a 1 byte header uniquely identifying the type of contents.
"Run for your life from any man who tells you that money is evil. That sentence is the leper's bell of an approaching looter." --Ayn Rand
|
|
|
|
|
My solution was as follows:
Create classes for all data types in the byte array, include a property for data length.
Fashion those classes to conform to the Chain Of Responsibility pattern.
Link all Data classes
Pass in the byte array, chain will match the correct type and return the correct object.
Add returned object and add to list.
Repeat until end of byte array.
Solution works.
"Run for your life from any man who tells you that money is evil. That sentence is the leper's bell of an approaching looter." --Ayn Rand
|
|
|
|
|
I stumbled on an article that talked about the importance of writing throw away code on a daily basis. So I spend a little time maybe 30 minutes or so (especially useful for the morning warm up) writing a short little app. I try all sorts of little things with little variations. Basic patterns, drawing, files, etc. I think it would be nice to have a daily Kata for people to do as a challenge. Maybe separate the Katas by function, i.e. File Katas, Serialization Katas, Pattern Katas, Inheritence Katas and so on. I think it would be beneficial to develop code speed and accuracy.
"Run for your life from any man who tells you that money is evil. That sentence is the leper's bell of an approaching looter." --Ayn Rand
|
|
|
|
|
I thought I'd start some boilerplate code for those posters who are having a little more trouble than just C#.
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
namespace NeedsCode
{
class Program
{
static void Main(string[] args)
{
throw new NotImplementedException("The program code needs to be implemented.");
}
}
}
"Run for your life from any man who tells you that money is evil. That sentence is the leper's bell of an approaching looter." --Ayn Rand
modified on Thursday, December 11, 2008 11:33 AM
|
|
|
|
|
I added the disclaimer from HERE[^], with modification of course.
"Simplicity carried to the extreme becomes elegance."
-Jon Franklin
|
|
|
|