Click here to Skip to main content
Click here to Skip to main content
Go to top

Making some parts of programming easier - Mad Library

, 18 Jun 2012
Rate this:
Please Sign up or sign in to vote.
Sometimes you want to end your project fastly and as easy as is possible. Say hello to Mad Library.

But you can also find currently supported latest release on CodePlex website. CodePlex website: Mad Library 

I'm not planning to put here sourcecode, because it's being actualized regularly.  

Introduction    

This article is about how to make some part of project programming done faster than before with usage of Mad Library. Mad Library is interested in more 'zones' of programming. Sometimes, this library can help you.

About   

Mad Library is a free Open Source .NET Framework library which provides many accelerations to normal programming with preprogrammed functions.

Global reasons for use

  • Mad Library is mostly documented library which makes programming faster
  • Mad Library is fastly developed and it’s interested in things that are hardly programmable or too expensive for time.
  • Mad Library holds and develops own fast communication protocols, HTML managers, CSS managers and more usable things which are needed every day.

Specific reasons for use

  • Managing
    • Simple user holding, comparing, verifying, sorting…
    • Simple item managing (similar to functions enumerated upper)
    • Simple product managing (—||—)
  • Mathematics
    • Simple fractions use in code
    • Usable percentage calculator
    • Simple proportionality calculating and holding
  • Networking
    • Usable client communication manager and request + response manager
    • Simple clear HTTP protocol request and response holders, managers, parsers and builders
    • Own communication protocol for simple client<->server communication
    • Peer to peer communicator
    • Bases for servers and web servers
  • Text
    • Random text generator
    • Refactoring builder
  • Web
    • Simple CSS document, CSS style, CSS property and CSS group managing and holding types
    • HTML document, HTML element, HTML attribute and more web document managing and holding types.
    • Web file, web directory, web site and web page support (with recursive searching, getting by HTTP call path, etc.)
  • Others
    • Collection managing
    • Building and parsing interfaces
    • Program properties

… and there are also another loads of smaller not specified functions for help and effectivity in programming. 

Usage examples 

Global 

Mad Library also contains unclassified functions which are also usable in more sections of programming. Some of them are in examples which are written here.

Program properties

.NET framework provides more automatically and unautomatically generated properties which are usable for programmer. Mad Library also offers you attribute tagging. ProgramPropertyAttributte serves for setting custom properties of program when you don’t want or you don’t have time for own attributes. Example is missing because program properties are attributes. ProgramPropertyAttributte is documented, so you can read comments written for it in source code.

Collection

Collections such as List or Dictionary are often used in code. Mad Library offers you Collection<> class for storing and managing reference types with public implicit constructor. Example of usage: 

Collection<MyType> col = new Collection<MyType>();
col.Add(new MyType("BCD"));
col.Add(new MyType("ABC"));
col.Add(new MyType("CDE"));
col.Add(new MyType("1T"));
IOrderedEnumerable<MyType> ocol = col.OrderBy(t => t.Name);
col.InsertAt(0, new MyType("ZABC"));
col.InsertAt(col.Count - 1, new MyType("XYZ"));
foreach (MyType mt in col)
    Console.WriteLine(mt.Name);
Console.WriteLine("===============");
foreach (MyType t in ocol)
    Console.WriteLine(t.Name);

Console.Read(); 

IBuildable and IParsable

Mad Library is systematical. Most of data and information holding types are deriving from this interface, so when you’re working with some HTML or CSS elements or properties, or when you’re working with requests and responses, you can use functions of these interfaces for parsing string into it or for building string from it. This small example shows you how can you these interfaces for managing communicating data types.

HttpResponse resp = new HttpResponse();
IParsable ip = resp as IParsable;
ip.Parse("HTTP/1.1 200 OK\r\nOPTIONS\r\n\r\nDATADATA\r\n\r\n");

Console.WriteLine((resp as IBuildable).Build());
Console.Read(); 

Managing

Managing is one just one small bit helpful part of Mad Library which is available for derivation and for next use.

1.1 Items

Managing of items can help you when you will try to make small application with  should manage many kinds of items.

Item first = new Item(1, "First test item."); //Creates new item
Item second = new Item(2); //Creates new item
second.Name = "A second one."; //Sets name of second to 'A second one.'
Items i = new Items(first, second); //Creates new item collection.
i.Sort(ItemsSort.Name); //Sorts created collection by item name.
foreach (Item a in i) //Enumerates sorted collection.
    Console.WriteLine(a.Name); //Prints name of enumerated item. 

1.2 Products

Our product management is primary targeted for derivation. 

Product first = new Product(99991, "First product.", 200.5);
Product second = new Product(99992, "Another product.", 200.5000001);
Products collection = new Products(first, second);
collection.SetProductsCategory(new ProductCategory("Beer", "Our best beers."));
foreach (Product p in collection)
    Console.WriteLine(p.Category); 

1.3 Users

User management is based on User class and it’s created for fast use. 

User first = new User("User2", "TestTest", "test@test.test");
User second = new User("User1", "Test", "test@test.test");
Users col = new Users(first, second);
col.Sort(SortConfiguration.Username);
Console.WriteLine(first.VerifyUser("User1", "TestTest"));
Console.WriteLine(first.CompareUsers(second));
foreach (User u in col)
    Console.WriteLine(u.Email); 

1.4 Persons 

Persons ready in last check in. You can see them (with documentation) on codeplex. 

Mathematics

Mathematics are in Mad Library targeted for now on fractions, proportionalities and percentage.

2.1 Fractions

Fractions are frequently missing in code when you need to use some mathematical or physical equations and you need to be precise. Mad Library offers you Fraction class which is documented and prepared for normal use. Operators are set for basic mathematical operations and and conversions.

Fraction f = new Fraction(10, 20);
f += new Fraction(1, 2);
f /= new Fraction(1, 2);
f *= new Fraction(15, 20);
double res = f;
Console.WriteLine(res);
Console.Read(); 

2.2 Direct proportionality

Sometimes you need to use direct proportionality in your code. Direct proportionality is simpler than inverse and it seems like you don’t need to use some external codes for it in your project. But Mad Library is sure that you sometimes needed use some equations or functions that are really simple but later you found out that you spent lot of time when you were working on it. So down in this part of document is written example of that, what Mad Library offers you in this problematic.

DirectProportionality proportionality = new DirectProportionality(3);
double x = proportionality.GetX(36);
double y = proportionality.GetY(x);
double coefficient = MadLibrary.Math.DirectProportionality.GetCoefficient(x, y);
Console.WriteLine(proportionality.Coefficient == coefficient); 

2.3 Inverse proportionality

As it’s written higher in this document, in programming are sometimes occurring some easy problems about which you now how to easily solve them, but you must spent lot of time when you’re working on it. Inverse proportionality is bit more difficult than direct, but for computer it’s almost same. Mad Library offers you solution for this kind of proportionality.

InverseProportionality prop = new InverseProportionality(10);
double x = prop.GetX(10);
double y = prop.GetY(x);
double coefficient = MadLibrary.Math.InverseProportionality.GetCoefficient(x, y);
Console.WriteLine(coefficient == prop.Coefficient); 

2.4 Percentage

Calculation of percentage is also simple and it’s also missing in .NET 4.5 library.

Percentage percentage = new Percentage(500, 50);
Console.WriteLine(percentage.Value);
double bas = percentage.GetBase(50);
double val = percentage.GetValue(bas);
Console.WriteLine(percentage == MadLibrary.Math.Percentage.GetPercentage(bas, val)); 

Networking

Mad Library offers you very usable part of itself which is named Networking. Networking is primary targeted on Client<->Server communication, but it also contains P2P communication functions and communication by more protocols, eg. HTTP (builders of HTTP request and HTTP response), NODA, …

3.1 Client–Server communication

Client – Server communication is many times simple, but from experiences you certainly know that you must spend lot of time when you’re working on it. Sometimes, when you’re creating application which is primary based on Client - Server communication you must program your own code because you have some special functions, methods or properties which you must do. But sometimes you’re using this kind of communication only for small operations, or this kind of communications is not so important part of your application. Then you can use preprogrammed options of Mad Library.

Code:

Communicator cm = new Communicator(new Requester(new IPEndPoint(IPAddress.Loopback, 1025)));
cm.RequestData = new MadLibrary.Net.Client.Request("GIVE ME RESPONSE");
ExampleServer srv = new ExampleServer();
srv.Start();
cm.Open();
cm.Request();
Console.WriteLine(cm.ResponseData);
cm.Close();
srv.End();
Console.Read();  

ExampleServer:

public class ExampleServer : Server
{
    public ExampleServer()
        : base(1025)
    { 
            
    }
    public override void Process(Socket client)
    {
        byte[] data = new byte[5];
        client.Receive(data);
        client.Send(data);
    }
} 

3.2 HTTP

HTTP protocol is mostly used protocol in the world. It’s our daily part. Daily part of professional programmers and also daily part of normal users. So these utterance is reason why was build HTTP manager in Mad Library. For now, we have just holders, builders and parsers in Mad Library, but these types are compatible with Request and Response classes in Client-Server communication by the operators (for now implicit). By these conversions you can send HTTP requests and get HTTP responses by the communicator and server. Down is written example about few functions of HTTP in Mad Libraries.

HttpRequest request = new HttpRequest();
request.Method = "GET";
request.HttpVersion = "1.1";
request.Options.Add("User-Agent", "unknown");
request.RequestedFile = "index.html";
request.Data.Add("variable", "value");
Console.WriteLine(request.Build());

HttpResponse resp = new HttpResponse();
resp.HttpVersion = "1.1";
resp.Content = "";
resp.Options.Add("Server", "this one");
resp.StatusCode = 200;
resp.StatusMessage = "OK";
Console.WriteLine(resp.Build());

Console.Read(); 

3.3 NDMP

More about NDMP.

Code: 

ServiceListener<ExampleService> listener = new ServiceListener<ExampleService>(1025);
listener.Start();
Client client = new Client(new IPEndPoint(IPAddress.Loopback, 1025));
client.Connect();
MadLibrary.Net.Ndmp.Response resp = client.Select("wWwWwWw");
client.Disconnect();
Console.WriteLine(resp.ToString());
Console.Read(); 

ExampleService:

public class ExampleService : Service
{
    public ExampleService() : base()
    { 
            
    }
    public ExampleService(IPEndPoint client)
        : base(client)
    { 
            
    }
    public override Response ProcessClient(Request request)
    {
        return base.ProcessClient(request);
    }
} 

3.4 Peer-to-Peer

Peer-to-Peer communication is also important part of network communication and programming. Mad Library offers you classes which can hold P2P communication information and which can manage/mediate that kind of communication. So here is example:

Peerer p = new Peerer(new PeererInfo(1025, System.Net.IPAddress.Loopback));
new Thread(new ThreadStart(() =>
{
    Thread.Sleep(100);
    p.Connect();
    new Thread(new ThreadStart(() => { Console.WriteLine(p.Receive(3)); })).Start();
    p.Send("LOL");
    Thread.Sleep(100);
})).Start();
Console.ReadLine(); 

Text

We’re communicating everyday.

We’re using our mouth and tongue to create speech. We’re using our fingers and hands to write informations, contracts and create masterpieces or farces.

But why we must strain ourselves? We can use computers!

4.1 Random text generation 

Mad Library offers you ways and means to make your existence as programmer easier by random text generator. Here is small example of usage. 

RandomText rt = new RandomText(SupportedCharacters.All, CharacterCase.Lower, 10);
rt.Generate();
Console.WriteLine(rt.GeneratedText);

string gtedText = MadLibrary.Text.RandomText.Generate(SupportedCharacters.Classic, CharacterCase.Alternative, 15, false);
Console.WriteLine(gtedText);

Console.Read(); 

4.2  Formatting

Formatting is not ready yet. We're planning to make Wikipedia formatting parser and BBCodes. 

Web 

As it’s written somewhere here, web sites, web files, HTTP protocol and all about and above it is being used and developed daily. Web is for now large and important part of Mad Library. It contains managing of web files, web directories, web pages, web sites, HTML documents, CSS files, etc. and it works good. Out web “toolkit” (Big Grin | <img src=) is simple and usable. It’s not based on .NET’s System.Xml, it’s our own creation. 

5.1 HTML

HTML is markup language for web pages which are being transferred by HTTP protocol. It’s similar to XML and by the years it started to be more freely in writing and it changed in a lot things. There where added new tags which are now supported by most of modern web browsers. Mad Library is primary and mostly working with classic XHTML 1.0 Strict, so when you’re trying to parse some strings or files into HTML classes in library, be sure that your strings and files are complying basic important rules of that version. So here is small example of that what you can do with HTML in Mad Library. 

HtmlDocument doc = new HtmlDocument(); //creating new HTML document
HtmlElement html = new HtmlElement("html", ElementType.Compound); //creating root element
html.Elements.Add(new HtmlElement("head", ElementType.Compound));
HtmlElement body = new HtmlElement("body", ElementType.Compound);
html.Elements.Add(body);
HtmlElement div = new HtmlElement("div", ElementType.Compound);
div.InnerText = "HELLO WORLD!";
div.Attributes.Add(new HtmlAttribute("style", "background-color: red;color: black;font-weight: bold;"));
body.Elements.Add(div);
doc.Elements.Add(html);
doc.Save("C:\\Web\\index.html"); 

Output:

<html>

  <head>
  
  </head>
  <body>
  
    <div style="background-color: red;color: black;font-weight: bold;">
    HELLO WORLD!
    </div>
  </body>
</html> 

5.2 CSS

CSS is style sheet language which is being daily used by web designers. It’s often used with markup languages and it has simple syntax with simple rules. For now, lastest version of CSS is CSS 3.0 with more delicate and harder functions for making web page more beautiful. Mad Library contains simple small parser and builder for this language, so you can use it and you don’t have to code all parsing processes. Down is small example of CSS management in Mad Library. 

CssDocument doc = new CssDocument();
CssStyle style = new CssStyle(new CssGroup("div", CssGroupType.Element));
style.Properties.Add(new CssProperty("background-color", "black"), 
    new CssProperty("color", "white"));
CssStyle hover = new CssStyle(new CssGroup[]{new CssGroup("div", CssGroupType.Element)}, 
    new CssGroup("hover", CssGroupType.PseudoClass));
hover.Properties.Add(new CssProperty("background-color", "white"), 
    new CssProperty("color", "black"));
doc.Styles.Add(style, hover);
doc.Save("C:\\Web\\main.css"); 

Output: 

div
{
  background-color<span class="code-none"><span class="code-none">: black<span class="code-none"><span class="code-none">;
  color<span class="code-none"><span class="code-none">: white<span class="code-none"><span class="code-none">;
<span class="code-none"><span class="code-none">}

div:hover
<span class="code-none"><span class="code-none">{
  background-color<span class="code-none"><span class="code-none">: white<span class="code-none"><span class="code-none">;
  color<span class="code-none"><span class="code-none">: black<span class="code-none"><span class="code-none">;
<span class="code-none"><span class="code-none">}</span></</span></span></span></span>span></</span>span></</span></span></span></span></span>span></</span>

5.3 Web pages, sites, directories and files

All web documents specified in Mad Library are derived from WebFile class which contains basic properties common for this kind of documents. There’s also WebDirectory which loads files of web pages by HTTP call path with WebPage class. And there’s also WebSite class which is usable for management of some portal or some portfolio, simply – for web site management. Here’s a small example:

HtmlDocument doc = new HtmlDocument("index");
CssDocument css = new CssDocument("main");
WebDirectory directory = new WebDirectory("Web", doc, css);
WebPage page = new WebPage(doc, css);
WebSite site = new WebSite(directory, "C:\\Web");
CssDocument ncss = site.GetStyles("main.css");
Console.WriteLine(css.Name == ncss.Name); 

Output:

True

These examples are showing only small parts of functions which are in Mad Library. To be informed about new releases you can follow us on CodePlex. Thank you for reading. 

Just small note: please don't be frightened when you'll see some grammatical mistakes. 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

FrewCen

United States United States
No Biography provided

Comments and Discussions

 
General[My vote of 1] Thoughts PinpremiumPIEBALDconsult23-Jul-14 8:56 
GeneralMy vote of 1 Pinmemberknakker000118-Jun-12 4:52 
GeneralMy vote of 5 Pinmemberfredatcodeproject18-Jun-12 1:53 
Question[My vote of 2] Why? PinmemberJohn Brett17-Jun-12 20:45 
GeneralMy vote of 2 Pinmemberervegter17-Jun-12 13:05 
GeneralRe: My vote of 2 PinmemberKlaus Luedenscheidt17-Jun-12 17:31 
GeneralRe: My vote of 2 Pinmemberervegter17-Jun-12 18:56 
GeneralRe: My vote of 2 PinmemberKlaus Luedenscheidt18-Jun-12 17:14 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140905.1 | Last Updated 18 Jun 2012
Article Copyright 2012 by FrewCen
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid