Randomly rearrange a string in .NET C#

Say you’d like to randomly rearrange the contents of a string, i.e. put the constituent characters into new, random positions. The following method can help you with that using a combination of LINQ and Random:

private static string RearrangeString(string startingPoint)
{
	Random num = new Random();
	string rand = new string(startingPoint.
		OrderBy(s => (num.Next(2) % 2) == 0).ToArray());
	return rand;
}

Let’s test it with my name:

string myName = "Andras Nemes";
string myNewName = RearrangeString(myName);

So my new name can be something like “drsNeeAna ms” or “AdaNmesnrs e” or even “ArsNmenda es”, I haven’t decided yet.

Filip Ekberg drew my attention to the following alternative solution:

string rand = new string(startingPoint.OrderBy(x => Guid.NewGuid()).ToArray());

View the list of posts on LINQ here.

Convert a dynamic type to a concrete object in .NET C#

Dynamic objects in C# let us work with objects without compile time error checking in .NET. They are instead checked during execution. As a consequence we can’t use IntelliSense while writing the code to see what properties and functions an object has.

Consider the following Dog class:

public class Dog
{
	public string Name { get; }
	public string Type { get;}
	public int Age { get; }

	public Dog(string name, string type, int age)
	{
		Name = name;
		Type = type;
		Age = age;
	}
}

Read more of this post

Introduction to ASP.NET Core part 10: the details page and more on view models

Introduction

In the previous post we looked more closely at routing in .NET Core MVC. There are two ways two declare the routing rules: imperatively via Startup.cs or declaratively in the controllers using attributes. The routing rules can be distributed with this solution. General routing rules like the Default route can be placed in Startup.cs, whereas controller and action method specific rules can be declared in the controllers directly.

In this post we’ll continue building on our demo application. We’ll add a details page for the books and we’ll also see our first Razor HTML helper method in action.

Read more of this post

Embedded functions in F#

F# allows us to declare a function within a function. The embedded function will only be visible within the encasing function. Indentation is important in this case as the embedded function can also span multiple rows.

Consider the following function:

let calculate x = 
    printfn "Your input parameter was %i" x
    let embedded y z = 
        printfn "%s" "Running the embedded function"
        let a = (x + y) * 2
        x + y + a
    let finalRet = embedded 5 4
    printfn "The result is %i" (finalRet)
    finalRet

let calculateRes = calculate 5

Read more of this post

Function composition in F#

F# lets us build new functions that consists of other functions using the composition operators >> and <<. The direction of the arrows determines how the individual constituent functions are linked.

Consider the following simple functions:

let incrementByOne x = x + 1
let triple x = x * 3
let halve x = x / 2
let double x = x * 2

A common feature of each function is that each accepts a single parameter and has a return value. The input and return types are also identical. These functions are good candidates for function composition.

Here’s how to do it:

Read more of this post

Introduction to ASP.NET Core part 9: MVC continued with routing

Introduction

In the previous post we continued our exploration of MVC in ASP.NET Core. We discussed how a controller action can return various response types that implement the IActionResult interface. The are many return types to choose from and many of them map to a standard HTTP status code like 200 OK, 201 Created etc. There are other response types such as ObjectResult that serialises the provided object using a serialiser which usually defaults to JSON. Finally we saw how to connect a controller action with a view that accepts an object. The view can use the injected object to render dynamic HTML. The default view file type in .NET Core is a Razor view with the cshtml file extension. We can mix HTML and C#-like syntax in a cshtml file. So we have managed to connect the various parts of the MVC pattern in our demo application: a URL is routed to a controller and an action method, the action method builds a model which is injected into a view and the view uses the model to build the final HTML that’s sent back to the user.

In this post we’ll take another look at routing.

Read more of this post

Flatten sequences with the C# LINQ SelectMany operator

Suppose that we have an object with a collection of other objects, like a customer with order items. Then we can also have a sequence of customers where each customer will have her own list of orders. It happens that we want to analyse all orders regardless of the customer, like how many of product A have been sold. There are several options to collect all orders from all customers and place them into one unified collection for further analysis.

The C# SelectMany operator has been specifically designed to extract collections of objects and flatten those collections into one. This post will provide a couple of examples to demonstrate its usage.

Read more of this post

Introduction to ASP.NET Core part 8: MVC continued with controller actions and our first view

Introduction

In the previous post we started looking into MVC in .NET Core. We added a new library through NuGet and wired up the MVC middleware in Startup.cs. Routing is about mapping parts of the requested URL to a controller and an action. The controller is a normal C# class which most often derives from the Controller base class. The action is a C# function that returns some type of response to the HTTP request. The action can have 0, 1 or more parameters that must match the query parameters of the URL otherwise the routing engine won’t find it. We also wrote our first controller called the HomeController and the first action called Index which corresponds to the /home/index URL. We also discussed the basics of routing and added a very basic convention based route to Startup.cs.

Read more of this post

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

ARCHIVED: Bite-size insight on Cyber Security for the not too technical.