Complicated C# for learning purposes - c#

I'm trying to read some of other people's code, both to help me learn C#, and also purely to develop my ability to understand other people's code, but a lot of what I've found online to look at is both very long, and relatively simple. I wonder if anyone could point me to something short but more complex, preferably including less common uses of the language.
(It doesn't need to do anything sensible, so long as it does something. Something entirely pointless, like a C# equivilent of the XSLT Mandelbrot, would be perfectly fine)

Eric Lippert has recently been writing a series on graph colouring on his blog. This may well be something to sink your teeth into as it's a multi-part series that should allow you to work your way from simple to brain-meltingly-ouch as he progresses with explaining graph colouring. =)

I'd recommend looking at the Effective C# books. They'll help you learn more complex uses of the language.

Take a look at the mono source code - many of the BCL classes are implemented and you are sure to learn something :)
There are also many open source .NET projects out there that are not small and simple applications that you can look at.
Here are some off the top of my head:
MonoDevelop - a .NET IDE
nHibernate - an ORM
Pinta - image manipulation a la gimp

Raytracing in one LINQ statement, from Luke Hoban's blog, jumps immediately to mind.

Take a look at the .NET framework assemblies themselves using the .NET Reflector. There is a bunch of really great stuff in there and has helped me a lot during my learning.
Many times I have thought to myself how Microsoft has done certain things in the framework and I was easily able to find the answers right within their source.

Check out Coding4Fun. It's a mix of .Net languages and some (most) of the projects are really cool. XNA Creators Club is pretty cool as well... plenty of samples and it you have an XBox360 or a Zune you can write games for them as well.

How about this?
private Element ReadMemberExpression()
{
var queue = new Queue<Element[]>();
var newDepth = 0;
var argsCount = 0;
_scanner.CreateRestorePoint();
while (true)
{
_scanner.CreateRestorePoint();
{
var a = ReadArguments();
if (a != null)
{
argsCount++;
if (argsCount > newDepth)
{
_scanner.Restore();
break;
}
queue.Enqueue(new[] { default(Element), default(Element), a });
_scanner.DeleteRestorePoint();
continue;
}
}
_scanner.DeleteRestorePoint();
var pe = ReadPrimaryExpression();
if (pe != null)
{
queue.Enqueue(new[] { pe });
continue;
}
var fe = ReadFunctionExpression();
if (fe != null)
{
queue.Enqueue(new[] { fe });
continue;
}
if (_scanner.MatchNext(Grammar.New))
{
newDepth++;
queue.Enqueue(new[] { Grammar.New });
}
else if (_scanner.Match(Grammar.LeftSquareBracket))
{
var e = ReadExpression();
if (e == null)
{
throw new ParseException();
}
if (!_scanner.MatchNext(Grammar.RightSquareBracket))
{
throw new ParseException();
}
queue.Enqueue(new[]{default(Element), Grammar.LeftSquareBracket, e, Grammar.RightSquareBracket});
}
else if (_scanner.Match(Grammar.FullStop))
{
if (!_scanner.MatchNext(ElementType.IdentifierName))
{
throw new ParseException();
}
queue.Enqueue(new[] { default(Element), Grammar.FullStop, _scanner.Current });
}
else
{
_scanner.Unwind();
break;
}
}
if (queue.Count == 0)
{
_scanner.DeleteRestorePoint();
return null;
}
else
{
var element = default(Element);
var children = queue.Dequeue();
while (children[0] == Grammar.New)
{
children = queue.Dequeue();
}
element = new Element(ElementType.MemberExpression, children);
while (queue.Count > 0)
{
children = queue.Dequeue();
if (children.Length == 3 && children[2].Type == ElementType.Arguments)
{
newDepth--;
children[0] = Grammar.New;
children[1] = element;
element = new Element(ElementType.MemberExpression, children);
}
else
{
children[0] = element;
element = new Element(ElementType.MemberExpression, children);
}
}
if (newDepth > 0)
{
_scanner.Restore();
return null;
}
_scanner.DeleteRestorePoint();
return element;
}
}

It's not terribly complex, but may be briefly entertaining -- Mads Torgersen has implemented a fixed-point combinator in C# here:
http://blogs.msdn.com/b/madst/archive/2007/05/11/recursive-lambda-expressions.aspx

This may be an obvious suggestion, but I would checkout the articles on CodeProject.com. You can search for specific articles relevant to C#, and the contributors generally do a great job of explaining their code.
For instance, here is an article on creating a Mandelbrot set in C# (though this may not be as complex as you might be looking for).
Other than that, I would take a peak inside any C# opensource projects you may find via Google.

Related

How to get real time of a midi event

I am reading a midi file with this parser.
But I cannot read the real time.
MidiFile midiFile = new MidiFile("/Jenkins.mid");
var ticksPerQuarterNote = _midiFile.TicksPerQuarterNote;
foreach (MidiTrack track in midiFile.Tracks)
{
foreach (MidiEvent midiEvent in track.MidiEvents)
{
if (midiEvent.MidiEventType != MidiEventType.NoteOn)
continue;
int note = midiEvent.Note;
int time = midiEvent.Time;
}
}
All the formulas I have seen on the internet use the tempo, but I can't find it.
You can use my DryWetMIDI library which does all these calculations for you:
var midiFile = MidiFile.Read("Jenkins.mid");
var tempoMap = midiFile.GetTempoMap();
foreach (var trackChunk in midiFile.GetTrackChunks())
{
foreach (var timedEvent in trackChunk.GetTimedEvents())
{
if (timedEvent.Event.MidiEventType != MidiEventType.NoteOn)
continue;
MetricTimeSpan metricTime = timedEvent.TimeAs<MetricTimeSpan>(tempoMap);
}
}
Here we get metric time (hours/minutes/seconds/ms), but the library provides several other formats you can convert MIDI time to. Please read the article of the library docs to learn more: Time and length.
More than that if you actually want to get notes instead of events, it's super easy with DryWetMIDI:
var notes = midiFile.GetNotes();
You can also use TimeAs method on notes.

Read all users from AD using Novell.Directory.Ldap.NETStandard

I need to read all users from the AD. Here is code that I am using:
using Novell.Directory.Ldap;
using Novell.Directory.Ldap.Controls;
using System.Linq;
namespace LdapTestApp
{
class Program
{
static void Main()
{
LdapConnection ldapConn = new LdapConnection();
ldapConn.SecureSocketLayer = true;
ldapConn.Connect(HOST, PORT);
try
{
var cntRead = 0;
int? cntTotal = null;
var curPage = 0;
ldapConn.Bind(USERNAME, PASSWORD);
do
{
var constraints = new LdapSearchConstraints();
constraints.SetControls(new LdapControl[]
{
new LdapSortControl(new LdapSortKey("sn"), true),
new LdapVirtualListControl("sn=*", 0, 10)
});
ILdapSearchResults searchResults = ldapConn.Search(
"OU=All Users,DC=homecredit,DC=ru",
LdapConnection.ScopeSub,
"(&(objectCategory=person)(objectClass=user))",
null,
false,
constraints
);
while (searchResults.HasMore() && ((cntTotal == null) || (cntRead < cntTotal)))
{
++cntRead;
try
{
LdapEntry entry = searchResults.Next();
}
catch (LdapReferralException)
{
continue;
}
}
++curPage;
cntTotal = GetTotalCount(searchResults as LdapSearchResults);
} while ((cntTotal != null) && (cntRead < cntTotal));
}
finally
{
ldapConn.Disconnect();
}
}
private static int? GetTotalCount(LdapSearchResults results)
{
if (results.ResponseControls != null)
{
var r = (from c in results.ResponseControls
let d = c as LdapVirtualListResponse
where (d != null)
select (LdapVirtualListResponse)c).SingleOrDefault();
if (r != null)
{
return r.ContentCount;
}
}
return null;
}
}
}
I used this question Page LDAP query against AD in .NET Core using Novell LDAP as basis.
Unfortunatelly I get this exception when I am trying to recieve the very first entry:
"Unavailable Critical Extension"
000020EF: SvcErr: DSID-03140594, problem 5010 (UNAVAIL_EXTENSION), data 0
What am I doing wrong?
VLVs are browsing indexes and are not directly related to the possibility or not to browse large numbers of entries (see generic documentation). So even if this control would be activated on your AD, you wouldn't be able to retrieve more than 1000 elements this way :
how VLVs work on AD
MaxPageSize is 1000 by default on AD (see documentation)
So what you can do:
use a specific paged results control, but it seems that the Novell C# LDAP library does not have one
ask you the question: "is this pertinent to look for all the users in a single request?" (your request looks like a batch request: remember that a LDAP server is not designed for the same purposes than a classic database - that can easily return millions of entries - and that's why most of LDAP directories have default size limits around 1000).
The answer is no: review your design, be more specific in your LDAP search filter, your search base, etc.
The answer is yes:
you have a single AD server: ask your administrator to change the MaxPageSize value, but this setting is global and can lead to several side effects (ie. what happens if everybody start to request all the users all the time?)
you have several AD servers: you can configure one for specific "batch like" queries like the one you're trying to do (so large MaxPageSize, large timeouts etc.)
I had to use approach described here:
https://github.com/dsbenghe/Novell.Directory.Ldap.NETStandard/issues/71#issuecomment-420917269
The solution is far from being perfect but at least I am able to move on.
Starting with version 3.5 the library supports Simple Paged Results Control - https://ldapwiki.com/wiki/Simple%20Paged%20Results%20Control - and the usage is as simple as ldapConnection.SearchUsingSimplePaging(searchOptions, pageSize) or ldapConnection.SearchUsingSimplePaging(ldapEntryConverter, searchOptions, pageSize) - see Github repo for more details - https://github.com/dsbenghe/Novell.Directory.Ldap.NETStandard and more specifically use the tests as usage samples.

How to write tests for legacy code and then refactor it?

I have a project with lots of ugly code I've written some time ago. Now I'm trying to make it testable and to use TDD for further development. But every time I'm trying to write unit tests for existing code I'm getting stuck. I just don't know how to test my old code. I can't write any little test. It makes me sick. So can anyone show me what tests to write for function like this to make further refactoring painless:
public void ChangeHealth(UInt16 id, HealthTypes health, FighterCount count)
{
var uc = new FighterCommand {Health = health, KillerId = 1024};
Fighter f;
switch(count)
{
case FighterCount.All:
if (Fight.GetInstance().Status == FightStatuses.Enable)
{
foreach (var u in Fighters.Elements)
uc.AddUnit(u.Id);
}
FightEvents.StatusUnit(null, health);
_sender.SendCommand_AppServer(uc);
break;
case FighterCount.NotEqual:
for (var i = Fighters.Count - 1; i >= 0; i--)
{
f = Fighters.GetUnit(i);
if (health == f.Health) continue;
uc.AddUnit(f.Id);
FightEvents.StatusUnit(f, health);
}
if (uc.UnitCount > 0) _sender.SendCommand_AppServer(uc);
break;
default:
f = Fighters.GetById(id);
uc.AddUnit(f.Id);
FightEvents.StatusUnit(f, health);
_sender.SendCommand_AppServer(uc);
break;
}
}
Take a look at the "golden master" technique by Michael Feathers. The idea is that you throw input at your untestable code, record the output or the state of your program. Then you can refactor and throw the same input and observe the same output or internal state (with the exception of the minor incremental change you've made). Bit by bit the code becomes more testable. Explained in further depth at http://blog.thecodewhisperer.com/2014/09/28/surviving-legacy-code-with-golden-master-and-sampling/
A tool for dumping the state of your application is https://github.com/kbilsted/StatePrinter where you simply can say
var printer = new Stateprinter();
Console.WriteLine( printer.PrintObject( myProgram) );

Depth first search did find solution state in Missionaries and Cannibals problems

I am doing my project on Missionaries and Cannibals using C#. I have used two search algorithms namely breadth first search and depth first search. Using Breadth first search, the program finds the result at level 12 from the root. But using Depth first search, it can not find solution and this hangs my computer. I think it enters a cycle in the graph. So my question is, can't i use Depth first search to solve Missionaries and cannibals problem?
Code for Breadth first search is
public State getSolutionStatesBFS(State StartState, State EndState)
{
State CurState = new State();
ArrayList visited = new ArrayList();
addStateToAgenda(StartState, true);
while (searchAgenda.Count > 0) {
CurState = (State)searchAgenda.Dequeue();
if (CurState.Equals(EndState)) {
break;
} else {
if (!isVisited(CurState, visited))
{
generateSucessors(CurState, true);
visited.Add(CurState);
}
}
}
return CurState;
}
and the code for depth first search is
public State getSolutionStatesDFS(State StartState, State EndState)
{
State CurState = new State();
ArrayList visited = new ArrayList();
addStateToAgenda(StartState, false);
while (searchAgendaS.Count > 0)
{
CurState = (State)searchAgendaS.Pop();
if (CurState.Equals(EndState))
{
break;
}
else
{
if(!isVisited(CurState,visited))
{
generateSucessors(CurState, false);
}
}
}
return CurState;
}
It is hard to tell answer seeing your code. However, based upon my experience: a DFS search does not provide complete solution. There is a good possibility that your code might have got stuck into some infinite loop (which is common with dfs) or (since, you are checking isVisited), there is a possibility that you are not reaching the end goal.
So my question is, can't i use Depth first search to solve Missionaries and cannibals problem?
Yes, it is deffinatly possible, take a look at this site:
http://www.aiai.ed.ac.uk/~gwickler/missionaries.html
With the code given its hard to tell where your issue is.

Conversion OF FIFO code from Java to c#

couple of days ago i posted a topic about fifo programming and how to do it because the topic was a bit broad and vague and lacks coding example, so i followed experts advice and searched for codes and tried a bit of coding. and i knew exactly what i wanted to do
i want to create a DES (Discrete event simulation) for the FIFO (first in first out) scheduling algorithm using the C# as my programming language.
so i searched the net and i couldn't find something really helpful in c# for guidance but i found exactly what i wanted to in java codes. which i will post now
The process of Initialization
Queue q = new Queue();
EventQueue eventq = new EventQueue();
Random rand = new Random();
Distribution interarrivalTimeDist =
new ExponentialDistribution(lambda, rand);
Distribution serviceTimeDist =
new ExponentialDistribution(mu, rand);
double t = 0;
// generate first arrival
eventq.addEvent(new Event(Event.ARRIVAL,
interarrivalTimeDist.nextRandom()));
Main program
while (t < simLength) {
Event e = eventq.nextEvent();
t = e.getTime();
switch (e.getType()) {
case Event.ARRIVAL : {
// handle arrival
}
case Event.DEPARTURE : {
// handle departure
}
}
}
Case of Arrival
case Event.ARRIVAL : {
// schedule next arrival
eventq.addEvent(new Event(Event.ARRIVAL,
t + interarrivalTimeDist.nextRandom()));
double serviceTime =
serviceTimeDist.nextRandom();
q.addCustomer(new Customer(t, serviceTime));
if (q.getSize() == 1) {
eventq.addEvent(new Event(Event.DEPARTURE,
t + serviceTime));
}
break;
}
Case of departure
case Event.DEPARTURE : {
q.removeCustomer(t);
if (q.getSize() > 0) {
double serviceTime =
q.getCustomerAt(0).getServiceTime();
eventq.addEvent(new Event(Event.DEPARTURE,
t + serviceTime));
}
break;
}
any clues or guidance how to convert this code to c#??
and help will help highly appreciated it
PS:- for the experts please show some tolerance if my topic wasn't as professional as you guys thought it will be
thanks
Your question sounds a lot like "how do I program this idea", and isn't a good SO question. You should design a lot about what you want to do, build it in steps, and come here with specific questions you have, not broad ideas or lots of code.
To answer just FIFO, that is a queue. Read about queues and practice with them.

Categories

Resources