How to create an .EXE using .NET Core Console App

In the previous exercise, we learnt how to publish and execute a .NET Core Console App! In case you want to review that exercise, you can access it from here.

In this exercise, we’ll look at a quick way to turn a .DLL to an .EXE. Please note, when you build a .NET Core console app, it compiles the app to a DLL.

Here’s I’ll show you how to create an EXE:

  • Go to the command prompt and navigate to the location where the project is stored
  • Issue the following command: dotnet build -r win10-x64

You’ll find the .EXE in the folder i.e. Win10-x64. See image below:

Hope this was helpful.

Posted in .NET | Comments Off on How to create an .EXE using .NET Core Console App

How to Publish and Execute a .NET Core Console App!

Publishing a .NET Core app is as easy as 1,2,3. Here’s how:

After you have created the console app, make sure you select Release from the Solution Configurations drop-down menu.

  Now right-click on the project node inside Solution Explorer and choose Publish from the menu item. See image below:

Hit Publish, and you are set!

In order to run the app from command prompt, the quick and easy way to navigate to the location where the .dll is stored, you can do the following:

  • Open Windows Explorer
  • Navigate to the DLL file. It’ll be your project Name with a .DLL extension

  • Point your cursor to the start of your drive (see image below) and type cmd followed by space and hit Enter. This neat shortcut will take you straight to the command prompt.

  • In order to run your program, you need to type: dotnet xxx.dll where xxx is your file name

That’s it!

Useful Links (coming soon):

Publishing .NET Core app.
Creating an .EXE in a Console App
Consuming Console App’s DLL externally (using Batch program)
Sending Email blasts using SendGrid
Using Windows Task Scheduler

Happy Consoling 🙂

Posted in .NET | Tagged , | Comments Off on How to Publish and Execute a .NET Core Console App!

How to use .NET Core Console app?

Console apps have been around since .NET’s inception i.e. 2002. Over the years, it has had a bit of a windows dressing with additional APIs, integration with .NET Core and the like.

Let’s look at a simple console app written in .NET Core that simply sends an email using the Net.Mail API.

using System;
using System.Net.Mail;

namespace SMTP
{
    class Program
    {
        static void Main(string[] args)
        {
            SendTestEmail();
            Console.WriteLine("The email was sent successfully!");
            Console.ReadLine();
        }

        private static void SendTestEmail()
        {
            MailMessage mail = new MailMessage("Obi@eOberoi.com", "ooberoi@hotmail.com");
            SmtpClient client = new SmtpClient
            {
                Port = 587,
                DeliveryMethod = SmtpDeliveryMethod.Network,
                UseDefaultCredentials = true,
                Host = "smtp.google.com",
                Credentials = new System.Net.NetworkCredential("Obi@gmail.com", "MyPassword")
            };
            
            mail.Subject = "Testing Console App!";
            mail.Body = "How is it going Obi!";
            client.Send(mail);
        }
        
    }

Links to similar blog posts (coming soon!):

Posted in .NET | Comments Off on How to use .NET Core Console app?

How to combine multiple stored procedures into a single resulset

Let’s say, you have multiple stored procedures each of which is tied to a partial view or View Component in MVC. Now, while this may seem like a logical thing to do, but what if you want the entire payload to return to a single View.

Well, how about combine all the stored procedures and return a single result set. Here’s how in three simple steps.

First, let’s take a look at the diagram below:

The Employee table has the following records:

Following are the three stored procedures that I have created for the purposes of this demo:

CREATE OR ALTER PROCEDURE [dbo].[spGetMinimumSalary]	
	@MinSalaryRange MONEY,
	@MaxSalaryRange MONEY
AS
BEGIN
	SET NOCOUNT ON;
	 
	SELECT
		FirstName, 
		LastName, 
		Gender
	FROM 
		Employee 
	WHERE
		(Salary BETWEEN @MinSalaryRange AND @MaxSalaryRange)
END
CREATE OR ALTER PROCEDURE [dbo].[spGetMedianSalary]	
	@MinSalaryRange MONEY,
	@MaxSalaryRange MONEY
AS
BEGIN	
	SET NOCOUNT ON;
  
	SELECT
		FirstName, 
		LastName, 
		Gender
	FROM 
		Employee 
	WHERE
((Salary > @MinSalaryRange) AND (Salary <= @MaxSalaryRange))
END
CREATE OR ALTER PROCEDURE [dbo].[spGetMaximumSalary]	
	@Salary MONEY	
AS
BEGIN
	SET NOCOUNT ON;
	   
	SELECT
		FirstName, 
		LastName, 
		Gender
	FROM 
		Employee 
	WHERE
		(Salary > @Salary)
END

Now, comes the interesting part. Let's create a temporary table:

CREATE TABLE #TmpSalary 
(
	FirstName NCHAR(25),
	LastName NCHAR(25),
	Gender NCHAR(10)
)

As you can see, the temporary table only has the structure, but no data:

Select * from #TmpSalary

Now, let's insert the records into the temporary table that are returned from executing the stored procedures like so:

INSERT INTO #TmpSalary
EXEC spGetMinimumSalary 0, 50000

INSERT INTO #TmpSalary
EXEC spGetMedianSalary 50000, 75000

INSERT INTO #TmpSalary
EXEC spGetMaximumSalary 75000

Let's view the records now:

Select * from #TmpSalary

There you have it! 🙂

Posted in SQL Server | Comments Off on How to combine multiple stored procedures into a single resulset

How to pass delimited list to a Stored Procedure

Let’s write a Table-valued function below. This can be created by navigating to Functions – Table-Valued Functions inside SQL Management Studio.

Just an FYI, I am using the AdventureWorks database, but this  sample can be used in any situation.

CREATE FUNCTION [dbo].[fn_SplitStateProvinceCode]
(
   @List VARCHAR(MAX),
   @Delimiter CHAR(1)
)
RETURNS TABLE 
AS 
  RETURN ( SELECT Item = CONVERT(varchar(500), Item) FROM
      ( SELECT Item = x.i.value('(./text())[1]', 'varchar(max)')
        FROM ( SELECT [XML] = CONVERT(XML, ''
        + REPLACE(@List, @Delimiter, '') + '').query('.')
          ) AS a CROSS APPLY [XML].nodes('i') AS x(i) ) AS y
      WHERE Item IS NOT NULL
  );

For testing, you can declare a variable and test the statement by passing the @List and delimiter like so. As you can see, in the sample below, the delimiter is ‘,’.

Caution: The delimited string is strictly delimited by a comma and has no space in between province codes.

DECLARE @List VARCHAR(MAX)
SET @List = 'AB,ON,TX,VIC,WA'
SELECT CODES = ITEM FROM dbo.[fn_SplitStateProvinceCode (@List, ',') 

If you wish to write it in a query using the Where clause and using ‘IN’ you can do the following:

DECLARE @List VARCHAR(MAX)
SET @List = 'AB,ON,TX,VIC,WA'
Select * from Person.StateProvince 
WHERE StateProvinceCode IN (Select CODES = ITEM FROM dbo.fn_SplitStateProvinceCode (@List, ','))	

Cheers,

Obi

Posted in SQL Server | Comments Off on How to pass delimited list to a Stored Procedure

Global Query Filters in EF Core 2.0

Global Query Filters are a new addition to the arsenal of features in EF Core 2.0. This also implies that EF core team spearheaded by Diego Vega who are working diligently to bring EF Core at par with its Entity Framework 6.x classic counterpart. Like it or not, its good news for us developers, right?

Well, GQF in short are LINQ query predicates. In other words they are a boolean expression that are typically passed to the LINQ “Where” query operator and applied to Entity Types in the metadata model (usually in OnModelCreating). Such filters are automatically applied to any LINQ queries involving those Entity Types, including Entity Types referenced indirectly, such as through the use of Include or direct navigation property references.

Below is a Snapshot of the database containing two tables i.e. Department & Employee respectively.

GQFContext.cs class

namespace GlobalQueryFilters 
{
    class GQFContext : DbContext
    {
        public DbSet Department { get; set; }
        public DbSet Employee { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer(@"server=Obi-Oberoi; database=Company; Trusted_Connection=True;");
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity().HasQueryFilter(e => !e.IsDeleted);
        }

    }

Department & Employee POCO Classes

using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace GlobalQueryFilters
{
    public class Department
    {
        [Key]
        public int DepartmentID { get; set; }
        public string Name { get; set; }
        public List Employee { get; set; }
    }

    public class Employee
    {
        [Key]
        public int ID { get; set; }
        [ForeignKey("DepartmentID")]
        public int DepartmentID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Gender { get; set; }
        public decimal Salary { get; set; }
        public bool IsDeleted { get; set; }
        public Department Department { get; set; }
    }
}

Program.cs

 
static void Main(string[] args)
        {
            using (var ctx =  new GQFContext())
            {
                var emp = ctx.Employee.ToList();

                foreach (var item in emp.Where(e => e.DepartmentID == 3))
                {
                    Console.WriteLine("Name = {0},{1}", item.FirstName, item.LastName);
                }
                Console.ReadLine();
            }
        }

Notice the two records with the DepartmentID of 3 that are being filtered using the LINQ query above.

Now, let’s try and do something different. Let’s query the records with DepartmentID of 2. In the Employee table, we have at least two records with DepartmentID of 2. See below:

Notice the record for the employee Steve Pound has one of his records marked for deletion. That’s precisely what we intended for when using Global Query Filter which as you can recall from the code snippet below. This code is defined in the GQFContext class where we have specifically filtered the record(s) that are marked for soft deletion  like so:

protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity().HasQueryFilter(e => !e.IsDeleted);
        }

Notice, the record Steve Pound is filtered as a result of Global Query Filter that is defined as a predicate in the “HasQueryFilter” method.

Posted in ORM | Comments Off on Global Query Filters in EF Core 2.0

Difference between Varchar and Nvarchar. When to use what?

To order essay on an author of the essay not only that but safely. Our exchange provides a number of obligations, which guarantee customers that they will receive a high quality and decent work:

each essay is checked by the system Antiplagiat, which ensure that the text was unique;

you made your payment remains “frozen” for the author until the time the student will receive an essay on the order in hand;

real comments and feedback about each expert help to navigate, who to approach and what results to expect.

If you need to order essay on any subject, be sure to contact author of essay on here will execute any order with pleasure and in the shortest time will help you to come to the school with the custom essay uk and best hand.

Other types of work

To the exchange author of essay each day addresses a lot of clients that need professional help. Here  who can do the work of proofreading efficiently and competently. author of essay has such features as:

It employs a lot of specialists who work with different languages. The staff is constantly to big this allows us to assist a lot more often;

The order is carried out only by experienced professionals who have diploma in this field or are the academic staff of the Universities. They thoroughly know their work and can carry out proofreading of articles;

The cost of proofreading text

Exchange author of essay can perform all sorts of work. Proofreading articles, research papers and other assignments is in accordance with all requirements and regulations. As for the cost of proofreading the texts, it may depend on:

Scope of work;

The complexity of the subject;

Deadlines.

For urgent execution, the contractor takes a percentage of the work, as it delays other work and perform an urgent task.

Posted in SQL Server | Leave a comment

EF Core 2.1 Roadmap

A network of casinos no! How so, asks the inquisitive reader, was just saying that though and I myself am about ten seen, and heres to you, “no.” Yes, dear, no. But there is a program — a gaming machine which simulates anything. And roulette, blackjack, and Poker, etc. And the program “personal use”. Ie, you play with her one on one. Of course, at the same time on the server may be at least 100 people. But play you all one of his “table”, i.e. by running this program on your computer. And your situation in no way affects other players as well as their situation, you. Thus, it violated that Golden rule — do not play against the casino. And the player is in this situation — one against the casino (or rather against its gaming machine). And what is the casino going to let him with impunity “stripped” with the help of different gaming systems? Hehe, guys, we casino was built. What would you have “stripped” ? As it is not so…

Pay attention to casino rules. Rights of the player virtually no. Yes, and they cannot be! The fact that even the law gaming situation may not be in dispute. “Well, damn you, buddy! Well, that thing went to!” And everything was your money become our money.

Because the online casino is just slot machine, what prevents you to configure it the way the owner wants it? Indeed, to prove it is absolutely impossible — “we have all accidentally” say the guys in the previews of the entrance.

But only a foolish fisherman going fishing dont take the bait. Sometimes a lot. But since you played “for free”, you do not deserve. And in the soul of the player settles the worm. Yeah, but would I real money, the evening of three hundred would have done a couple of thousand… And it seems to him that he start all over again, the situation will simply repeat itself, but with real money.

Then the player receives a loading dose of bait — “In our casino, if you drive in the game$ 100, get a bonus — another$ 100!” this like online jackpot city casino review on freepokiesland.com To remove them at once is impossible, but to play on. E-my, well, who would refuse! Well, not to swallow this lure of  doubling the money may just very well mentally stable fish. Of which minority.

And thats when the game is already in the money, the adult thing here is to beat the player by using the programmed machine is easier than kindergartners take a toy. You can even give a little and win (and where are you from a submarine go?). Brought$ 100, won another 50, Yes the bonus (non-removable) money hundreds. Come on, buddy, come to us for fifty dollars come from? Well, you Somni, as it was last time — a couple of thousand, easy! Here then is the conversation!

And at some moment a lucky player suddenly stops take. Nonsense, the case, he thinks. On it and casino, then black, then red… no way, man… Maybe for a normal, wooden roulette wheel and case (and even then, Matera dealer can “sector” to throw), and electronic program everything is under control. Then the moneyat stake. And the luckiest game system suddenly stops working!

And she cant work, because it is no longer the game itself. There is a cunning program of the slot machine. The task of which is relatively honest and was not penalized taking money from citizens.

And whats interesting. The machine works on its own, but the player still plays and the role of the dealer. He presses the button “start” and himself throws the ball.

In principle, all these beautiful pictures in the form of a spinning roulette ball rolling (Yes, even with the imitation of the sound) and the loss of any digits — solid props. Well, kind of like the scenery on the stage. If the player will simply announce the number of the dropped numbers, nothing will change.

All of the above allows us to state that real casino to the Internet, alas, no. Have to try your luck in those that are everyones business. I warned, who did not hide I is not guilty.

But in General, can the casino to be in online? Of course you can. But the Internet in this case should be the only method of communication. Implementation is, in my opinion, there are two.

The easiest is simply an organization web camera on a real roulette. Player just (brokered or dealer) bets. And the game can be a lot of players. And the dealer is true and real, real roulette turns and throws the real ball. And the result is visible to all players. In real-time and simultaneously. Yes, it more expensive than to do the slot machine. But this casino and trust more. Its just remote play in a real casino.

The second option is. In principle, the machine is also not very bad. But it is important to do it in a way that would at the same table at the same time playing a few players. And betting players should be visible to other players. This option also has the right to life, and imitation of other players. While, however, it is quite easy to check if in the game will participate in 2-3 pre-collusion between a person. And in any case, the belief that roulette is as much more. Even if your losing, you will see that someone still wins. So the gain is possible?

To play in the current online casino, one-on-one with the shifty program I do not advise.

Posted in ORM | Comments Off on EF Core 2.1 Roadmap

Write a program that prints an average temperatue that is close to Zero

The idea is to get the lowest number that is close to the value zero (irrespective of the negative or positive value) from an array of average temperatures that are supplied like so:

{ 7, 7.9, 10.5, -4, 3, -6, -2, 1, -15, 11.3, 9, -1 }

Solution:
One way is to iterate through an array of numbers and store the lowest number in a temp variable and print it out to a console.

As a side, an Array class provides methods for creating, manipulating, searching arrays which serves as the base class for all arrays in common language runtime typically referred to as CLR. The array data structure contains a contiguous collection of data items that can be accessed by an ordinal index.

I have assigned an arbitrary value of 50 to the temp variable prior to iterating through the array elements, comparing it and assigning the lowest number to the temp variable until it reaches the last element of the array before printing out the number.

public static void GetTemperatureCloseToZero()
        {
            double temp = 50.0; //some arbitrary value
            double diff;
            int target = 0;

            double[] arr = { 7, 7.9, 10.5, -4, 3, -6, -2, 1, -15, 11.3, 9, -1 };

            for (int i = 0; i < arr.Length; i++)
            {
                diff = Math.Abs(Convert.ToDouble(arr[i])) - Convert.ToDouble(target);
                if (diff <= temp)
                {
                    temp = diff;
                }
            }
            Console.WriteLine("The closest value to 0 is: {0}", temp);
            Console.ReadLine();
        }

Alternative Solution:
If you don't want to iterate through the items in an array, you can also use the Sort() method to sort elements in the entire list using the default comparer like so:

       public static void GetTempCloseToZeroSort()
        {
            double[] arr = { 7, 7.9, 10.5, -4, 3, -6, -2, 1, -15, 11.3, 9, -1 };
            List list = new List();

            foreach (var item in arr)
            {
                list.Add(Math.Abs(item));
            }
            list.Sort();
            
            Console.WriteLine("The closest value to 0 is: {0}", list[0]);
            Console.ReadLine();
        }

In both case the code produces the following output:ArrayOut1

I hope this will help those that are just getting into data structures.

Cheers,

Obi

 

Posted in Algorithms & Data Structures | Comments Off on Write a program that prints an average temperatue that is close to Zero

How to check if nested brackets are in the correct logical order

I am starting a series of blog posts on algorithms and data structures with the first one being the easiest!

Q. Write a method that checks if the nested brackets are in the correct logical order. The input string is the following:

“{ [ () {} ] }”

Please note, there can be many interpretations, but here’s how I am attempting to solve this question which may not necessarily be the most efficient solution. Here it goes…

First off, I create a console app and write a function that removes erroneous spaces like so:

 
        public static String FilterErroneousChars(String input)
        {
            int len = input.Length;
            char[] arr = input.ToCharArray();
            String filter = "";
            for (int i = 0; i < len; i++)
            {
                if (arr[i].Equals('(') || arr[i].Equals(')') || arr[i].Equals('[') || arr[i].Equals(']') || arr[i].Equals('{') || arr[i].Equals('}'))
                {
                    filter += arr[i];
                }
            }
            return filter;
        }

Once the function is executed, it'll return a string with no spaces, i.e. "{[(){}]}".

Next, I call the method from Program Main() and pass in the compressed string as input like so:

Then, I check to see if any of the nested pair(s) is equal. If the condition is met, the program replaces the nested brackets with an empty string until there's nothing left.

In the end, I check to see if the length of the string is 0. Once this condition evaluates to True, we know, that the input string is well-formed, else NOT.

I hope, those of you that are new to data structures, you might find this algorithmic exercise useful.

String s = Algorithms.FilterErroneousChars("{ [ () {} ] }");
            while ((s.Length != 0) && (s.Contains("[]") || s.Contains("()") || s.Contains("{}")))
            {
                s = s.Replace("[]", "");
                s = s.Replace("()", "");
                s = s.Replace("{}", "");
            }

            if (s.Length == 0)
            {
                Console.WriteLine("Well Formed");
            }
            else
            {
                Console.WriteLine("Not Well Formed");
            }

Posted in Algorithms & Data Structures | Comments Off on How to check if nested brackets are in the correct logical order