C# Faster way to truncate a string

Very often I found this problem and now I got a solution! I’ve compared some methods and I was decided which one. But I verified time (if you want to know how, read this post) of them and the final solutions are: static string TruncateLongString(string str, int maxLength) { return str.Substring(0, Math.Min(str.Length, maxLength)); } or string TruncateString(string str, int maxLength) { return new string(str.Take(maxLength).ToArray()); } The best solution than even is the second one!

Read More

String to Hex – Hex to String Convert

You can convert a string to hex or vice-versa with this methods. Example for real world; You want set / get some data from URL, but if your data has some special chars (like ^$ %) it’ll be problem… In this case, you can use this methods and convert your data to hex. public string ConvertStringToHex(string asciiString) { string hex = ""; foreach (char c in asciiString) { int tmp = c; hex += String.Format("{0:x2}", (uint)System.Convert.ToUInt32(tmp.ToString())); } return hex; } public string ConvertHexToString(string HexValue) { string StrValue = ""; while…

Read More

Regular expression for UK postcode

I’m looking for an answer to my regular expresssion problem in c#. I’m looking for a match on a specific postcode format and have run into problems. Here you can find my solution with the regex pattern. C# public bool IsPostCode (string postcode) { return ( Regex.IsMatch(postcode, “(^[A-PR-UWYZa-pr-uwyz][0-9][ ]*[0-9][ABD-HJLNP-UW-Zabd-hjlnp-uw-z]{2}$)”) || Regex.IsMatch(postcode, “(^[A-PR-UWYZa-pr-uwyz][0-9][0-9][ ]*[0-9][ABD-HJLNP-UW-Zabd-hjlnp-uw-z]{2}$)”) || Regex.IsMatch(postcode, “(^[A-PR-UWYZa-pr-uwyz][A-HK-Ya-hk-y][0-9][ ]*[0-9][ABD-HJLNP-UW-Zabd-hjlnp-uw-z]{2}$)”) || Regex.IsMatch(postcode, “(^[A-PR-UWYZa-pr-uwyz][A-HK-Ya-hk-y][0-9][0-9][ ]*[0-9][ABD-HJLNP-UW-Zabd-hjlnp-uw-z]{2}$)”) || Regex.IsMatch(postcode, “(^[A-PR-UWYZa-pr-uwyz][0-9][A-HJKS-UWa-hjks-uw][ ]*[0-9][ABD-HJLNP-UW-Zabd-hjlnp-uw-z]{2}$)”) || Regex.IsMatch(postcode, “(^[A-PR-UWYZa-pr-uwyz][A-HK-Ya-hk-y][0-9][A-Za-z][ ]*[0-9][ABD-HJLNP-UW-Zabd-hjlnp-uw-z{2}$)”) || Regex.IsMatch(postcode, “(^[Gg][Ii][Rr][]*0[Aa][Aa]$)”) ); } Visual Basic Public Function IsPostCode(postcode As String) As Boolean Return (Regex.IsMatch(postcode, “(^[A-PR-UWYZa-pr-uwyz][0-9][ ]*[0-9][ABD-HJLNP-UW-Zabd-hjlnp-uw-z]{2}$)”) OrElse Regex.IsMatch(postcode, “(^[A-PR-UWYZa-pr-uwyz][0-9][0-9][…

Read More

OWIN and Facebook: the developers of this app have not set up this app properly for Facebook Login?

Did you received this error when you try to login in your Owin app with Facebook? App Not Set Up: This app is still in development mode, and you don’t have access to it. Switch to a registered test user or ask an app admin for permissions. Solution Go to https://developers.facebook.com/ Click on the My Apps menu on the top bar and select your appThe circle next to your app name is not fully green. When you hover mouse on it, you’ll see a popup saying, "Not available to all…

Read More

ASP.NET MVC Return image dynamically drawn in controller

If you have problem returning dynamically drawn image from controller below informations may help. The task looks easy and should be achieved with this code: public ActionResult Image(string text) { //Create new image Image img = new Bitmap(100, 50); Graphics g = Graphics.FromImage(img); //Do some drawing Font font = new Font("Arial", 24); PointF drawingPoint = new PointF(10, 10); g.DrawString(text, font, Brushes.Black, drawingPoint); //Return Image MemoryStream ms = new MemoryStream(); img.Save(ms, ImageFormat.Png); return new FileStreamResult(ms, "image/png"); }   Unfortunately this won’t work. At least not in .NET 4.0. Perceptive person will…

Read More

ASP.NET MVC OWIN and Microsoft account

Register an app in the Microsot Account Developer Center Go to the Microsoft Account Developer Center and create a new application. After you have registered the application take note of the App ID and App Secret: Install the Nuget Package Install the Nuget Package which contains the Microsoft OAuth provider. Install-Package Microsoft.Owin.Security.MicrosoftAccount Register Provider Locate the file in your project called \App_Start\Startup.Auth.cs. Ensure that you have imported the Owin namespace: using Owin; In the ConfigureAuth method add the following lines of code: app.UseMicrosoftAccountAuthentication( clientId: "Your client ID", clientSecret: "Your client…

Read More

The current type, is an interface and cannot be constructed. Are you missing a type mapping?

You might have missed to register your Interface and class (which implements that inteface) registration in your code. e.g if the error is "The current type, xyznamespace. Imyinterfacename, is an interface and cannot be constructed. Are you missing a type mapping?" Then you must register the class which implements the Imyinterfacename in the UnityConfig class in the Register method. Using the following code as an example using System; using Microsoft.Practices.Unity; using Microsoft.Practices.Unity.Configuration; using PSC.Shorturl.Web.Business; using PSC.Shorturl.Web.Business.Implementations; namespace PSC.Shorturl.Web.App_Start { /// /// Specifies the Unity configuration for the main container. ///…

Read More

How to generate a random password

These code samples demonstrate how to generate a strong random password, which does not contain ambiguous characters (such as [1,l,I] or [O,0]). A strong password must be at least eight characters long and contain a combination of lower- and upper-case letters, numbers, and special characters. /////////////////////////////////////////////////////////////////////////////// // SAMPLE: Generates random password, which complies with the strong password // rules and does not contain ambiguous characters. // // To run this sample, create a new Visual C# project using the Console // Application template and replace the contents of the Class1.cs…

Read More

Using iTextSharp to generate pdf file in asp.net

One of the common requirement of web applications is to provide users a way to download some contents. In case of a report, almost all of the reporting tools have the export to pdf kind of function available. But sometime, it is not a report that needs to be generated in pdf. But it could be simple web page or content of a page or sometimes a plain text needs to be generated in pdf format. There are many third party tools are available for this task. We can import…

Read More

Write C#. Run JavaScript.

Open Source C# to JavaScript Compiler and Frameworks. Run Your App On Any Device Using JavaScript. Use Bridge.NET to build platform independent applications for mobile, web and desktop. Run on iOS, Windows, Mac, Linux and billions of other devices with JavaScript support. Compile your C# code into native JavaScript and deploy on Billions of devices. Try it on bridge.net or fork it on GitHub

Read More

How do I get a Unique Identifier for a Device within Windows 10 Universal?

If you google a bit about this problem, you can’t find a right solution because all people are speaking about Hardware Token. Unfortunately this functionality doesn’t exists for Universal Windows Application. There are at the moment only a way. You have to add the Extension reference “Windows Desktop Extensions for the UWP” or “Windows Mobile Extensions for the UWP“, then you can use the following code: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.Security.ExchangeActiveSyncProvisioning; using Windows.System.Profile; namespace PSC.Code { public sealed class DeviceInfo { private static…

Read More

How to strip all HTML tags and entities and get clear text?

I was encouraged to write this Tip/Trick because of so many questions received for this issue. Suppose you’re having a bunch of HTML strings, but you just want to remove all the HTML tags and want a plain text. You can use Regex to come to the rescue. The Regex I had developed before was more cumbersome, then Chris made a suggestion, so I will now go further with the regex suggested by Chris that is a "\<[^\>]*\>". I have tested it for many cases. It detects all types of…

Read More

Creating reusable HTML components in ASP.NET MVC using Razor

Whilst working on a side project I started to notice I was using a lot of the same HTML to create floating boxes. Whilst these boxes looked the same, the content of them changed quite dramatically; for instance, some of the content boxes contained forms, others contained straight text, like so: <div class="panel"> <div class=panel-inner"> <h2 class="panel-title">Panel Title</h2> <div class="panel-content"> /* Can I pass content to be rendered in here here? */ </div> </div> </div> </div>   As my side project progressed and grew, I found myself making more and…

Read More

ASP.NET MVC 3: Razor’s @: and syntax

Razor minimizes the number of characters and keystrokes required when writing a view template, and enables a fast, fluid coding workflow. Unlike most template syntaxes, you do not need to interrupt your coding to explicitly denote the start and end of server blocks within your HTML. The Razor parser is smart enough to infer this from your code. This enables a compact and expressive syntax which is clean, fast and fun to type. For example, the Razor snippet below can be used to iterate a list of products: When run,…

Read More

Reading and Writing XML in C#

In this article, you will see how to read and write XML documents in Microsoft .NET using C# language.  First, I will discuss XML .NET Framework Library namespace and classes. Then, you will see how to read and write XML documents. In the end of this article, I will show you how to take advantage of ADO.NET and XML .NET model to read and write XML documents from relational databases and vice versa. Introduction to Microsoft .NET XML Namespaces and Classes Before start working with XML document in .NET Framework, It…

Read More

Chart.js Asp.net : Create Pie chart with database jQuery Ajax C#

This article explains using Chart.js in Asp.net C# Web Application we can create a pie chart with database MS SQL server connectivity via jQuery ajax call.  You can also have a look on related article, . Now in this post here we create a pie chart by using chart.js library and bind data from our database MS Sqlserver, with jQuery ajax calling. Here we are creating a pie chart, which shows data from the database (Ms SQL server).  In my database, I have a table which stores data (website traffic…

Read More

Use a reuseIdentifier Where Appropriate

A common mistake in app development is not setting the correct reuseIdentifier for UITableViewCells, for UICollectionViewCells, or even UITableViewHeaderFooterViews. For maximum performance, a table view’€™s data source should generally reuse UITableViewCell objects when it assigns cells to rows in tableView:cellForRowAtIndexPath:. A table view maintains a queue or list of UITableViewCell objects that the data source has marked for reuse.What happens if you don’t use a reuseIdentifier? If you don’t, your table view will configure a brand-new cell each time a row is displayed. This is an expensive operation and will…

Read More