Showing posts with label Development. Show all posts
Showing posts with label Development. Show all posts

Friday, June 22, 2018

Dotnet Core console app with NLOG in Visual Studio Code

In this post I am going to create simple minimalistic dotnet core console application and integrate it with nlog.



Let's create a folder for our project. I am going to name it nlog_console.



$mkdir nlog_console
$cd nlog_console



Now we create dotnet core console app project and if you have Visual Studio Code installed run the second command below.



$dotnet new console
$code . &



Now lets add nlog package to a project.



$dotnet add package nlog



This will add the following code to our project file.



<ItemGroup>
<PackageReference Include="nlog" Version="4.5.6" />
</ItemGroup>



Nlog framework requires configuration file 'nlog.config' to specify logger tagerts and rules. We can copy paste the sample nlog.config file from this github page or use one below.



xml version="1.0" encoding="utf-8" ?>

<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xsi:schemaLocation="NLog NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true"
internalLogFile="console-example-internal.log"
internalLogLevel="Info" >



<targets>

<target xsi:type="File" name="file"
fileName="console-example.log"
layout="${date}|${level:uppercase=true}|${message} ${exception}|${logger}|${all-event-properties}" />
<target xsi:type="Console" name="console"
layout="${date}|${level:uppercase=true}|${message} ${exception}|${logger}|${all-event-properties}" />
</targets>


<rules>
<logger name="*" minlevel="Trace" writeTo="file,console" />

</rules>
</nlog>



'nlog.config' file need to be copied to destination directory during project build. To achieve it add the code below to a project file.



<ItemGroup>
<None Include="nlog.config" CopyToOutputDirectory="Always" />
<ItemGroup>



Now we need to add actual logging code to a program. Copy paste the Program class code below.



using System;

namespace dotnetcore_nlog
{
class Program
{
private static NLog.Logger log = NLog.LogManager.GetCurrentClassLogger();
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
log.Trace("Loggin trace.");
}
}
}



To build and run our console app run code below or add launch.json config to Visual Studio Code.



$dotnet build
$dotnet run



You should see the following output and log file created in the same directory as our console app.



2018/06/19 18:48:13.130|TRACE|Loggin trace. |nlog_console.Program|


References:





0

Monday, August 14, 2017

Displaying assemblies used by the application process


Today I am going to show how to print out assemblies used by the running application. This information may be useful for logs and can be collected on application/service start.







Below is a snippet of the console application that prints out information to console.



using System;
using System.Diagnostics;

namespace ConsoleApplication
{
public class Program
{
public static void Main(string[] args)
{
Process oProcess = Process.GetCurrentProcess( );

Console.WriteLine( string.Format( "Process: {0} ({1})",
oProcess.ProcessName, oProcess.Id ) );
Console.WriteLine( );
Console.WriteLine( "MODULES:" );
Console.WriteLine( "________" );

foreach ( ProcessModule oModule in oProcess.Modules )
{
Console.WriteLine( string.Format( "{0} ({1})",
oModule.ModuleName, oModule.FileName ) );
}
}
}
}

0

Friday, March 31, 2017

VB.NET - Validating InputBox

If you are working with the system that still uses InputBox control from Microsoft.VisualBasic then you may get a situation where the input needs to be validated. InputBox control does not allow any validation checks and in ideal case needs to be replaced with custom WinForms dialog box. This post will show a simple way of validating InputBox by creating InputBoxValidated function and using IStringValidator interface.



Public Class InputBoxValidated
Public Function InputBoxValidated _
(
prompt As String,
title As String,
Optional stringValidator As IStringValidator = Nothing,
Optional validationMessage As String = ""
) As String
Dim value As String _
= Microsoft.VisualBasic.Interaction.InputBox(prompt, title)

' If the cancel button wasn't pressed
' And IStringValidator is passed with validation message
If Not value = String.Empty AndAlso stringValidator IsNot Nothing _
AndAlso Not String.IsNullOrEmpty(validationMessage) Then
If Not stringValidator.Validate(value) Then
MessageBox.Show(validationMessage, Application.ProductName)
value = InputBoxValidated(
prompt, title, stringValidator, validationMessage)
End If
End If

Return value
End Function
End Class




As you can see InputBoxValidated function uses IStringValidator interface that can implement any kind of string validations and criteria.



Public Interface IStringValidator
Function Validate(value As String) As Boolean
End Interface



Below is an example of StringValidator class that implements IStringValidator interface and makes use of StringValidator from System.Configuration.



Public Class StringValidator
Implements IStringValidator

Public Sub New(maxLength As Integer, invalidCharacters As String)
Me.MaxLength = maxLength
Me.InvalidCharacters = invalidCharacters
End Sub

Public Property MaxLength As Integer
Public Property InvalidCharacters As String
Public Function Validate(value As String) _
As Boolean Implements IStringValidator.Validate
Dim valid As Boolean = True

Try
Dim stringValidator As _
New System.Configuration.StringValidator _
(0, MaxLength, InvalidCharacters)
If stringValidator.CanValidate(value.GetType()) Then
stringValidator.Validate(value)
Else
valid = False
End If
Catch ex As ArgumentException
valid = False
End Try

Return valid
End Function
End Class




References:










0

Monday, December 5, 2016

Reading appsettings.json in .Net Core Console Application under Linux

Recently I was looking at how to load and use appsettings.json file in .Net Core Console application. Many resources on .Net forums and sites were descripting use of appsettings.json file in ASP.NET Core web App, but very little described appsettings with .Net Core Console app. I managed to created sample .Net Core app with the minimum required libraries. Creation of this sample program I am going to describe here. Let's call our App "appsettings".

$mkdir appsettings
$cd appsettings
$dotnet new
$dotnet restore

Now create appsettings.json file:

{
"AppSettings": {
"Date": "1900-01-01"
}
}

Date is the setting I am interested in loading from AppSettings section.



Edit project.json file to include "Microsoft.Extensions.Configuration.UserSecrets": "1.1.0" in dependencies section. This is the only extra library we need in order to use ConfigurationBuilder functions.

{
"version": "1.0.0-*",
"buildOptions": {
"debugType": "portable",
"emitEntryPoint": true,
"outputName": "AppSettings"
},
"dependencies": {},
"frameworks": {
"netcoreapp1.0": {
"dependencies": {
"Microsoft.NETCore.App": {
"type": "platform",
"version": "1.1.0"
},
"Microsoft.Extensions.Configuration.UserSecrets": "1.1.0"
},
"imports": "dnxcore50"
}
}
}

Now lets edit the Program.cs file. We are going to load the Date setting and display it in Console. Don't forget to include "using Microsoft.Extensions.Configuration;"

using System;
using System.IO;
using Microsoft.Extensions.Configuration;

namespace ConsoleApplication
{
public class Program
{
public static string AppSettingsFile = "appsettings.json";
public static string AppSettingsSection = "AppSettings";
public static string DateSetting = "Date";

public static void Main(string[] args)
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(Program.AppSettingsFile, optional: true,
reloadOnChange: true);

var
config = builder.Build();
var appSettings = config.GetSection(Program.AppSettingsSection);
string dateString = appSettings[Program.DateSetting];
Console.WriteLine("Date:" + dateString);
}
}
}

That is pretty much all. Now let's build and run it.

$dotnet build
$dotnet run
Date:1900-01-01

0

Monday, November 14, 2016

xUnit Theory test ClassData with complex type

xUnit.net is a powerful, free, open source, unit testing tool for the .NET Framework. xUnit uses different notation to NUnit or MSUnit to specify test with parameters. Here I am going to show how to use Theory ClassData with complex type.



I have a sample class Plant, which has function 'bool IsEqual(Plant plant);'. We will create a Theory test for it.


[Theory]
[ClassData(typeof(IsEqualTestData))]
public void IsEqual(Plant plant1, Plant plant2, bool expectedResult)
{
Assert.Equal(expectedResult, plant1.IsEqual(plant2));
}


Class IsEqualTestData is a ClassData used with complex type Plant. It generates a list of arrays of 3 objects Plant1, Plant2, and ExpectedResult boolean.



private
class IsEqualTestData : IEnumerable<object[]>
{
private readonly List<object[]> _data = new List<object[]>
{
new object[]
{
new Plant()
{
Name = PlantTester.PlantName1,
Description = PlantTester.PlantDescription1
},
new Plant()
{
Name = PlantTester.PlantName2,
Description = PlantTester.PlantDescription2
},
false
},
new object[]
{
new Plant() { Name = PlantTester.PlantName1 },
new Plant() { Name = PlantTester.PlantName1 },
true
},
new object[]
{
new Plant()
{
Name = PlantTester.PlantName1,
Description = PlantTester.PlantDescription1
},
new Plant()
{
Name = PlantTester.PlantName2,
Description = PlantTester.PlantDescription1
},
true
}
};

public IEnumerator<object[]> GetEnumerator()
{
return _data.GetEnumerator();
}

IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}


When running in xUnit it will report result of running each entry in the test.



If you are using Visual Studio you can download snippet file from github repository.




Reference:


xUnit_ClassData.snippet

Using dotnet watch test for continuous testing with .NET Core and XUnit.net - Scott Hanselman
0

Wednesday, April 27, 2011

Scripting Support in the .Net Applications

I was reviewing integrating Scripting Support into .Net Applications. In the current .Net Frameworks from version 1.0 to 4.0 Microsoft provided the following namespaces for enabling Scripting support.

  • Microsoft.JScript
  • MSScriptControl
  • Microsoft.VisualBasic.Vsa (obsolete)
  • Microsoft.Vsa (obsolete)

The last two Microsoft.VisualBasic.Vsa and Microsoft.Vsa are now obsolete as Microsoft is stopping their support for VB6.

In Visual Studio 2010 Microsoft extended their support for JScripts by adding debugging capability and making developer’s work easier.

MSScriptControl is an ActivX Windows Scripting Control can be used to handle VBScripts and JScripts by specifying ScriptControl.Language property as “VBScript" or “JScript”. For more information on the .Net Scripting Support follow references below.

References

JScript on MSDN
Windows Scripting
Script Happens .NET

0

Saturday, April 16, 2011

Install Joomla! 1.6 on IIS 7

In the previous post Joomla! Installing XAMPP on Vista I described installation of the XAMPP package for Windows 7 and Vista. XAMPP package installs Apache web server, MySQL database, phpMyAdmin, FileZilla FTP Server and many more. With XAMPP it is really easy to install and configure Joomla!.

In this post I will show how to install Joomla! 1.6 on IIS7 on Vista or Windows 7.  I will be performing installation on Windows 7 with no IIS installed. We will install PHP support for IIS 7, MySQL database (I will not be covering installation of Joomla! with SQL Server just yet), phpMyAdmin for maintaining databases.

In my first attempts. I tried to install Joomla! using Windows Platform installer from Microsoft/web site, which did not work completely. Installer did not install properly IIS, failed to register PHP with IIS 7, did not configure MySQL and I got mixed up with credentials for Joomla! and MySQL. My decision was to start over and  install all required components manually.

Before we begin

In my explanations of the steps below I will assume that you are familiar with installation of basic windows components. I will only note most important points of the installation. If you require detailed explanation of the some of the installs I will provide reference section with links to sites with more detailed steps.

Install IIS 7

In this step we will perform basic installation of IIS 7. Open Control Panel>Programs>Program and Features>Turn Windows Features on or off.

image

Navigate to Internet Information Services and make sure you tick it first. It will select all required modules to run IIS7. Then expand tree to navigate to Application Development Features and tick CGI. I will be also doing ASP.NET development so I ticked ASP.NET Development and this also selected .Net Extensibility and other required modules. If you do not need any of the .Net features, don’t tick it. CGI component is needed to use FastCGI module of the PHP package, which we will be installing in the step below. Click OK.

image

When installation is complete open http://localhost to see if it installed OK. You should see similar screen to one below.

image

Installing PHP support for IIS7

Now we are going to install PHP support for IIS 7. Download latest PHP windows package from php.net site.

image

Now follow installation Wizard steps.

image

In the Web Server Setup select IIS FastCGI module. Click Next.

image

I selected to install all items including Register *.php to open automatically with PHP.

image

Click Finish.

I would also suggest installing PHP Manager for IIS package. It will add PHP configuration module into IIS Console.

image

This is an example PHP configuration screen. I find it is handy when you need to do some tweaks to PHP configuration.

image

Copy Joomla! CMS files to ISS 7

In this step we are going to copy Joomla! package files into C:\inetpub\wwwroot folder and create JoomlaDev Web Application to see if we can run PHP web sites. Configuration of Joomla! site will be done after completing of the MySQL database server installation. Download Joomla! CMS package from the joomla.org site. Unzip it and copy folder to ISS7 directory C:\inetpub\wwwroot. I named folder as JoomlaDev. Open IIS Management Console. Right click Default Web Site and select Add Application.

image

Enter fields as shown above if you are using the same names. Click OK.

image

JoomlaDev Application is created. Use Browse to open the site. If everything OK you should see the screen below.

Image[46]

Install MySQL on Windows 7 or Vista

Congratulations if you got that far, but don’t get too excited as we got a little be more work to do. Now we are going to install MySQL server. I am not going to cover using Joomla! with SQL Server here. This can be a topic for future posts. We need to  download, install and configure MySQL database and phpMyAdmin package for managing databases. Get MySQL Community Server from mysql.com site. PhpMyAdmin can be downloaded from phpmyadmin.net site.

image

Run MySQL Installation Wizard.

image

Run through wizard steps and click Install at the end.

image

Leave Launch the MySQL Instance Configuration Wizard tick box on and click Finish.

image

This will open MySQL Server Instance Configuration Wizard.

image

We will go through the Detailed Configuration steps. Click Next.

image

This is a Development Machine, so this option is what we need.

image

Leave as it is on Multifunctional Database and click next.

image

Installation Path as a location for database files will be fine.

image

I do not expect a lot of connection during development work, but I like to have more options at hand so I selected Online Transaction Processing Option. You can select what is more suitable in your case.

image

All looking good. Tick Add firewall exception for this port to enable access for phpMyAdmin. phpMyAdmin uses TCP/IP connection by default. If you are worried about security you can setup phpMyAdmin to use socket connection. It is possible in our case to use socket as we are installing MySQL server on the same machine as IIS 7 web server.

image

I am developing website in English and Russian Languages so the second option is the best one for me. Click Next.

image

We will set our Database Instance Name as MySQL. I like to perform some commands in the command prompt so I also ticked Include Bin Directory in the Windows PATH.

image

Enter a password for root. This is a development database and will not be accessed outside development machine. So I did not ticked Enable root access from remote machine or Create An Anonymous Account. For build and testing servers I will use a different installation of MySQL and IIS 7. Click Next.

image

Excellent! Click Execute when you are ready.

image

We are done! Click Finish.

Install and Configure phpMyAdmin

Installation of MySQL Server is done. Now we are going to configure phpMyAdmin package, which will help us to manage MySQL Databases. If you haven’t downloaded phpMyAdmin from previous step download it from phpmyadmin.net site. Unzip package and copy it to C:\inetpub\wwwroot directory. Open IIS 7 Management Console and create new web application in a similar way how we created web application for our Joomla! install.

image

I named folder and Web Application as phpMyAdmin. After clicking OK use browse to open http://localhost/phpMyAdmin/. You will get the screen below.

image 

Enter root as username and your root password, Click Go.

image

I got in! I was really impressed that without any additional configuration phpMyAdmin detected local MySQL Server and the setup is done!

Conclusion

Congratulations ones more time on the going through this rather lengthy post. Don’t get disappointed that you do not see Joomla! configuration steps here. There are very easy and straightforward. I am planning to post Joomla! configuration steps in the future post. This and the other posts will be part of the Creating Joomla! Development Environment series. Don’t forget to check out some references for more information.

References

0

Saturday, January 15, 2011

Creating project code coverage with PartCover and NUnit

Since my last posts ‘Integrating PartCover with Visual Studio 2005’ and ‘Integrating PartCover with Visual Studio 2008’ a lot of things changed and improved. PartCover project got itself a new home and now targeting .Net 4.0 Framework. NUnit testing framework also made a lot of improvements. In this post I am going to show how to run code coverage for a test project with NUnit console runner and PartCover browser. I will base it on my EnvMan project.


Getting PartCover and Nunit to run


First of all you need to download and install PartCover from Github project server. After installation you will find PartCover browser manual and PartCover console manual, which are very useful for understanding of rules creation and PartCover parameters.

Start PartCover Browser.

image

Select File>Run Target. It will open ‘Run Target Settings Window’

image


Click Browse buttons to select nunit-console.exe  and working directory for running NUnit. Working arguments should have “/noshadow” and a full path with the test project name or NUnit project name. “/noshadow” will make NUnit not to create shadow copies of the files and will allow PartCover to load source files in the browser. In EnvMan project I have NUnit project file which has two assemblies in it. In the rules window enter


+[*EnvMan*]*


which means (+) add rule where include any assembly which has EnvMan in its name and any namespace in these assemblies. After this you can click start to run tests. Don’t forget to save xml configuration file for future use.


Inspecting code coverage


Congratulations! You can now inspect the results by using Views>View Coverage Details.

image
0

Tuesday, May 4, 2010

Joomla! Internet Resources

I started to work with Joomla! Content Management System. There were few reasons why I  choose Joomla! out of many popular systems. One of them is it’s popularity and availability of learning material, templates, extensions and easy to setup and use. Below I listed links to some of these resources.

Joomla! in Russian

Joomla.ru – Russian translation for Joomla!
Joomla! Russian Portal
Languages - Joomla! Extensions Directory – Select Russian Language Extensions

Joomla! Extensions

JoomGallery - is a gallery component completely integrated into Joomla.

Joomla! Internet Resources

Joomla 1.5 Tutorial: Why use Joomla 1.5? Building a simple website with Joomla
Joomla Developer’s Toolbox | Smashing Magazine
JoomlaJunkie - Free and commercial Joomla templates club
Best of Joomla! The #1 joomla templates, resources and extensions
Joomla24 - More Than 2700 Free Joomla CMS Templates
Design for Joomla - Joomla Templates, Joomla Extensions for the Joomla CMS
Joomla 1.5 Blog and Free Joomla 1.5 Templates
Joomla! Downloads - Free Joomla Templates
Free Joomla Templates, Themes and Styles - themesBase.com
Free Joomla Templates - Joomla Themes
Joomla Shine – Free Joomla Templates
Joomlashack – Free Joomla Templates
Free Joomla templates themes

References

List of content management systems – Wikipedia
Top 12 Free Content Management Systems (CMS) | Spyre Studios
Top 10 Most Usable Content Management Systems - Nettuts+

0

Tuesday, September 1, 2009

Joomla! Installing XAMPP on Vista

Currently I am working on installing Joomla! content management system and as a first step it requires to install XAMPP package. After some time of tweaking I finally managed to install and run XAMPP package on Vista. XAMPP installation completed fine and basic configuration steps made no problems. All services except Apache started.

image 

Turned out that service was unable to start, because Apache process had no access to “C:\Program Files\xampp” directory. I decided to give SYSTEM account access to it and run Apache, MySql and FileZilla as windows services. To give access to SYSTEM account open properties of the directory and Security Tab.

image

Check that it has full access rights assigned. If not, use Edit button to assign access rights.

After trying to start Apache service again it still was failing to start. Apache log in C:\Program Files\xampp\apache\logs\error.log showed the following error.

“(OS 10013)An attempt was made to access a socket in a way forbidden by its access permissions.  : make_sock: could not bind to address [::]:80”

This error happens when some process already uses port 80. My solution was to change “C:\Program Files\xampp\apache\conf\httpd.conf” file and set port to something else like 8080 or any other number. Edit lines “Listen 80” and “ServerName localhost:80” to be  “Listen 8080” and “ServerName localhost:8080”. Start Apache service. Success!

The next step will be to install Joomla! I will publish another post if there will be problems that required solution during install.

0

Saturday, August 22, 2009

ASP.NET Grid View Hidden Column Binding Problem

When I was using Grid View in my Web Application I run into problem where hidden column would not bind data. After searching I found a simple solution to this problem. Let’s have a look at example. We have a table called Person with columns ID, FirstName, Surname. In our page we want to show only FirstName and Surname columns and have ID column loaded but hidden.

For a Grid View component create RowCreated event handler with the code:

protected void GvRowCreated(object sender, GridViewRowEventArgs e)
{
    // Hide ID Column
    e.Row.Cells[0].Visible = false;
}

The code above will hide all cells in column Cells[0], which is ID column. If Grid View has paging enabled we need to check e.Row.RowType == DataControlRowType.DataRow to hide only Cells that contain data.

0

Monday, July 6, 2009

CSS References and Tools

Every web designer and developer knows how powerful Cascading Style Sheets are and how much they can save in HTML coding.

I put together several links to CSS tutorials, samples and Internet resources.

CSS Books

CSS Tutorials

CSS Templates and Samples

Web Designer Tools

  • Rounded Graphics for CSS Box Corners - Cornershop

Resources

0

Monday, June 29, 2009

Free ASP.NET Learning Resources

In this post I would like to put together a list of ASP.NET learning resources.

Basic ASP.NET Walkthroughs

Advanced ASP.NET Walkthroughs

Visual Web Developer

ASP.NET Settings Schema – Reference for ASP.NET configuration section schema

ASP.NET Deployment

Additional Resources

ASP.NET FAQ's: Part I, Part II

ASP.NET MVC - is a free and fully supported Microsoft framework for building web applications that use a model-view-controller pattern.

Building a Great Ajax application from Scratch by Brad Abrams : AjaxWorld Talk

Web Deployment Projects - provide additional functionality to build and deploy Web sites and Web applications in Visual Studio 2008.

0

Tuesday, June 2, 2009

Free Windows Software Development Tools

Here is a list of free development tools I found useful and also popular in Software Development.
Large Text File Viewer - this program was designed for viewing large (>1GB) text files.

KompoZer - is a complete web authoring system that combines web file management and easy-to-use WYSIWYG web page editing.

UMLet - is an open-source UML tool with a simple user interface.

OpenProj - is a free, open source desktop alternative to Microsoft Project. It's available on Linux, Unix, Mac or Windows.

WinSCP - free SFTP and FTP client for Windows.

VMWare Server – run other operating systems on the same computer.

Microsoft SQL Server Management Studio Express - is a free, easy-to-use graphical management tool for managing SQL Server 2005 Express Edition and SQL Server 2005 Express Edition with Advanced Services.

Liquid XML Studio Free - XML Developers Toolkit and IDE.

ToDoList - A simple but effective way to keep on top of your tasks.

Microsoft Visual Studio


Visual Studio 2005 Express Edition - Easy way to start development with Microsoft tools.

Visual Studio 2008 Express Edition - Easy way to start development with Microsoft tools.

Subversion Tools


TortoiseSVN - A Subversion client, implemented as a windows shell extension.

Commit Monitor - is a small tool to monitor Subversion repositories for new commits.

SVN (Subversion) - version control system that is a compelling replacement for CVS in the open source community.

SVN Notifier - is a simple and useful tool to monitor your Subversion project repository for changes.

0