ASP.NET MVC Tips

//Getting a path
var path = HttpContext.Server.MapPath("~/App_Data");
var directory = HttpContext.Server.MapPath("~/Photos");

//RedirectToAction between areas
 return RedirectToAction("ActionMethodName", "ControllerName", new { area = "AreaName" });



//Web.Config template =============================
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
     <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <appSettings>
     <add key="webpages:Version" value="3.0.0.0" />
     <add key="webpages:Enabled" value="false" />
     <add key="ClientValidationEnabled" value="true" />
     <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>
  <system.web>
     <compilation debug="true" targetFramework="4.5" />
     <httpRuntime targetFramework="4.5" />
     <customErrors defaultRedirect="~/DSR/Error" mode="Off">
       <!--<error statusCode="500" redirect="InternalError.htm"/>-->
     </customErrors>
   </system.web>
   <connectionStrings>
     <add name="MyConnectionString" connectionString="Data Source=182.160.99.115\SQLSERVER2008;Initial Catalog=RobiPosMapping;User ID=sa;Password=sqladmin@123" providerName="System.Data.SqlClient" />
     <add name="RobiPosMappingEntities" connectionString="metadata=res://*/DataAccess.RobiPos.csdl|res://*/DataAccess.RobiPos.ssdl|res://*/DataAccess.RobiPos.msl;provider=System.Data.SqlClient;provider connection string="data source=182.160.99.115\SQLSERVER2008;initial catalog=RobiPosMapping;user id=sa;password=sqladmin@123;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
   </connectionStrings>
   <entityFramework>
     <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
 <providers>
 <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
 </providers>
 </entityFramework>
</configuration>

Read Text File in C#

        public string ReadFile(string baseDirectory)
        {           
            System.IO.StreamReader file = new System.IO.StreamReader(FilePath);  //.txt file path   
            string strLogs = String.Empty;   
             
            //Option A: Read the file and display it line by line.
            int counter = 0;
            string line;
            while ((line = file.ReadLine()) != null)
            {
                 Console.WriteLine(line);
                 strLogs += line + Environment.NewLine;
                 counter++;
            }

            //Option B:
            //strLogs = file.ReadToEnd().Replace("\n", "<brk />"); //remove "k" from "brk"
  
            //Option C:
            //strLogs =System.IO.File.ReadAllText(FilePath);

            file.Close();
            return strLogs;
        } 

Custom CultureInfo

using System;
using System.Globalization;

namespace CultureTest
{
    class Program
    {
        static void Main(string[] args)
        {
           Int32 number = 1234565789;
           CultureInfo ci = new CultureInfo("bn-BD-skpaul");
           Console.WriteLine(number.ToString("N",ci));
           DateTime dt = DateTime.Now;
           Console.WriteLine(dt.ToString("d", ci));
           Console.ReadLine();
        }
    }
}

Exception handling technique between class library and other projects

The following two examples generate same StackTrace

//Example - 1 ==========================================
namespace MyLibrary
{
   public class TestClass
    {
       private void DoItNow()
       {
           throw new InvalidOperationException("I am an exception.");
       }

       public void DoSomething()
       {
           DoItNow();
       }
    }
}

//Example - 2 ==========================================
namespace MyLibrary
{
   public class TestClass
    {
       private void DoItNow()
       {
           try
           {
               throw new InvalidOperationException("I am an exception.");
           }
           catch (Exception)
           {
               throw;
           }
       }

       public void DoSomething()
       {
           try
           {
               DoItNow();
           }
           catch (Exception)
           {
               throw;
           }
       }
    }
}

//User project.
namespace DeleteNow
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                MyLibrary.TestClass testClass = new MyLibrary.TestClass();
                testClass.DoSomething();
            }
            catch (Exception Ex)
            {
                Console.WriteLine(Ex.Message);
                Console.WriteLine(Ex.StackTrace);
            }

            Console.ReadLine();

        }
    }
}

IDisposable Member Implementation


    public class SqlFunction: IDisposable
    {
        String connectionString="";
        SqlConnection connection = null; 
        SqlCommand command = null; 
        SqlDataAdapter da = null; 
        SqlTransaction transaction = null;
        Boolean useSqlTransaction = false;

        #region
           //Other code
        #endregion

        #region iDisposable_mthods

            private bool disposed = false;

            public void Dispose()
            {
                CleanUp(true);
                GC.SuppressFinalize(this);
            }

            private void CleanUp(bool disposing)
            {
                // Be sure we have not already been disposed!
                if (!this.disposed)
                {
                    // If disposing equals true, dispose all
                    // managed resources.
                    if (disposing)
                    {
                        // Dispose managed resources.
                        connection.Dispose(); c
                        ommand.Dispose();  
                        da.Dispose(); 
                        transaction.Dispose();
                    }
                    // Clean up unmanaged resources here.
                }
                disposed = true;
            }

            ~SqlFunction()
            {
                CleanUp(false);
            }

        #endregion
    }

RabbitMQ Setup

RabbitMQ Setup

Introduction

Messaging is a technique to solve communication between disparate systems in a reliable and maintainable manner. You can have various platforms that need to communicate with each other: a Windows service, a Java servlet based web service, an MVC web application etc. Messaging aims to integrate these systems so that they can exchange information in a decoupled fashion.

A message bus is probably the most important component in a messaging infrastructure. It is the mechanism that co-ordinates sending and receiving messages in a message queue.

There have been numerous ways to solve messaging in the past: Java Messaging Service, MSMQ, IBM MQ, but they never really became widespread. Messaging systems based on those technologies were complex, expensive, difficult to connect to and in general difficult to work with. Also, they didn’t follow any particular messaging standard; each vendor had their own standards that the customers had to adhere to.

RabbitMQ is a high availability messaging framework which implements the Advanced Message Queue Protocol (AMQP). AMQP is an open standard wire level protocol similar to HTTP. It is also independent of any particular vendor. Here are some key concepts of AMQP:

  • Message broker: the messaging server which applications connect to
  • Exchange: there will be a number of exchanges on the broker which are message routers. A client submits a message to an exchange which will be routed to one or more queues
  • Queue: a store for messages which normally implements the first-in-first-out pattern
  • Binding: a rule that connects the exchange to a queue. The rule also determines which queue the message will be routed to

There are 4 different exchange types:

  • Direct: a client sends a message to a queue for a particular recipient
  • Fan-out: a message is sent to an exchange. The message is then sent to a number of queues which could be bound to that exchange
  • Topic: a message is sent to a number of queues based on some rules
  • Headers: the message headers are inspected and the message is routed based on those headers

RabbitMQ is not the only product that implements AMQP: Windows Azure Service Bus, Apache ActiveMQ, StormMQ are some of the other examples. RabbitMQ and the Azure Service Bus are probably enough for most .NET developers. Note that there are different versions of the protocol and some of these products support them to a various degree.

Installation

RabbitMQ is based on Erlang. There are client libraries for a number of frameworks such as .NET, Java, Ruby etc. We’ll of course be looking at the .NET variant. I’m going to run the installation on Windows 7. By the time you read this post the exact versions of Erlang and RabbitMQ server may be different. Hopefully there won’t be any breaking changes and you’ll be able to complete this tutorial.

Open a web browser and navigate to the RabbitMQ home page. We’ll need to install Erlang first. Click Installation:

Installation link RabbitMQ

…then Windows…:

Windows installation link RabbitMQ

Look for the following link:

Server installation link

This will get you to the Erlang page. Select either the 32 or 64 bit installation package depending on your system…:

Erlang download

This will download an installation package. Go through the installation process accepting the defaults. Then go back to the Windows installation page on the RabbitMQ page and click the following link:

Windows RabbitMQ installer package

Again, go through the installation process and accept the defaults.

RabbitMQ is now available among the installed applications:

RabbitMQ in startup menu

Run the top item, i.e. the RabbitMQ command prompt. Issue the following command:

rabbitmqctl status

You’ll get a series of status messages in JSON format:

RabbitMQ status messages

The fact that we received all this text confirms that the RabbitMQ server is up and running and can receive messages.

Next enter the following command:

rabbitmq-plugins enable rabbitmq_management

This command will enable the management UI for RabbitMQ for easy administration. The answer should say that a number of plugins have been enabled:

RabbitMQ plugins enabled

As the message says we’ll need to restart the server. The following command will stop the server:

rabbitmqctl stop

…and the following will start it:

rabbitmq-service start

In case the command prompt is complaining that the access was denied then you’ll need to run the command prompt as an administrator: right-click, and Run As Administrator from the context menu.

Open a web browser and navigate to the following URL:

http://localhost:15672/

This will open the RabbitMQ management login page. The default username and password is ‘guest’. Click around in the menu a bit. You won’t see much happening yet as there are no queues, no messages, no exchanges etc. Under the Exchanges link you’ll find the 4 exchange types we listed in the introduction.

We’re done with the RabbitMQ server setup.

RabbitMQ in .NET

There are two sets of API to interact with RabbitMQ in .NET: the general .NET library and WCF specific bindings. This binding allows the programmer to interact with the RabbitMQ service as if it were a WCF service.

Open Visual Studio 2012/2013 and create a new Console application. Import the following NuGet package:

RabbitMQ client NuGet

Add the following using statement to Program.cs:

1
using RabbitMQ.Client;

Let’s create a connection to the RabbitMQ server in Main. The ConnectionFactory object will help build an IConnection:

1
2
3
4
5
6
ConnectionFactory connectionFactory = new ConnectionFactory();
connectionFactory.HostName = "localhost";
connectionFactory.UserName = "guest";
connectionFactory.Password = "guest";
 
IConnection connection = connectionFactory.CreateConnection();

An IModel represents a channel to the AMQP server:

1
IModel model = connection.CreateModel();           

From IModel we can access methods to send and receive messages and much more. As we have no channels yet there’s no point in trying to run the available methods on IModel. Let’s return to RabbitMQ and create some queues!

Back in RabbitMQ

There are a couple of ways to create queues and exchanges in RabbitMQ:

  • During run-time: directly in code
  • After deploy: through the administration UI or PowerShell

We’ll look at creating queues and exchanges in the UI and in code. I’ll skip PowerShell as I’m not a big fan of writing commands in command prompts.

Let’s look at the RabbitMQ management console first. Navigate to the admin UI we tested above and log in. Click on the Exchanges tab. Below the table of default exchanges click the Add a new exchange link. Insert the following values:

  • Name: newexchange
  • Type: fanout
  • Durability: durable (meaning messages can be recovered)

Keep the rest unchanged and click Add exchange. The new exchange has been added to the table above.

Next go to the Queues link and click on Add a new queue. Add the following values:

  • Name: newqueue
  • Durability: durable

Keep the rest of the options unchanged and press Add queue. The queue has been added to the list of queues on top. Click on its name in the list, scroll down to “Bindings” and click on it. We’ll bind newexchange to newqueue. Insert ‘newexchange’ in the “From exchange” text box. We’ll keep it as a straight binding so we’ll not provide any routing key. Press ‘Bind’. The new binding will show up in the list of bindings for this queue.

Open a new tab in the web browser and log onto the RabbitMQ management console there as well. Go to the Exchanges tab and click on the name of the exchange we’ve just created, i.e. newexchange. Open the ‘Publish message’ section. We have no routing key, we only want to send a first message. Enter some message in the Payload text box and press Publish message. You should see a popup saying Message published:

Message published popup

Go back to the other window where we set up the queue. You should see that there’s 1 message waiting:

One message waiting in queue

Click on the name of the queue in the table and scroll down to the Get messages section. Open it and press Get Message(s). You should see the message payload you entered in the other browser tab.

Creating queues at runtime

You can achieve all this dynamically in code. Go back to the Console app we started working with. Add the following code to create a new queue:

1
model.QueueDeclare("queueFromVisualStudio", true, false, false, null);     

As you type in the parameters you’ll recognise their names from the form we saw in the management UI.

We create an exchange of type topic:

1
model.ExchangeDeclare("exchangeFromVisualStudio", ExchangeType.Topic);

…and finally bind them specifying a routing key of “superstars”:

1
model.QueueBind("queueFromVisualStudio", "exchangeFromVisualStudio", "superstars");

The routing key means that if the message routing key contains the word “superstars” then it will be routed from exchangeFromVisualStudio to queueFromVisualStudio.

Run the Console app. It should run without exceptions. Go back to the admin UI and check if the exchange and queue have been created. I can see them here:

New queue from Visual Studio

New queue from Visual Studio

The binding has also succeeded:

Queue and exchange bound

Let’s test if this setup works. In the UI navigate to the exchange created through VS and publish a message:

Message from exchange created in VS

Then go to the queue we set up through VS to check if the message has arrived. And it has indeed:

Message arrived through Visual Studio queue

You can perform the same test with a different routing key, such as “music”. The message should not be delivered. Indeed, the popup message should say that the message has not been routed. This means that there’s no queue listening to messages with that routing key.

This concludes our discussion on the basics of messaging with RabbitMQ. We’ll continue with some C# code in the next installment of the series.

View the list of posts on Messaging here.

Return ClosedXML Excel file from ASP.NET MVC controller

<form class="form-horizontal" id="form-create-employee" method="post" action="~/Admin/Home/ExcelReport">
            <input type="text" name="fromdate" placeholder="from date" />
            <input type="text" name="todate" placeholder="to date" />
            <input type="submit" value="Download" class="btn btn-info btn-lg"/>
        </form>
public ActionResult ExcelReport()
        {
            DataTable dtData = new DataTable();
            string fileName = Guid.NewGuid().ToString();
            String reportHeader = "This is a header.";
            try
            {
                String conString = WebConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
                string sql = "";
                using (SqlConnection connection = new SqlConnection(conString))
                {
                    using (SqlCommand command = new SqlCommand(sql, connection))
                    {
                        using (SqlDataAdapter da = new SqlDataAdapter(command))
                        {
                            connection.Open();
                            da.Fill(dtData); connection.Close();
                        }
                    }
                }
 
                //More details- http://closedxml.codeplex.com/
                var MyWorkBook = new XLWorkbook();
                var MyWorkSheet = MyWorkBook.Worksheets.Add("Sheet 1");
                int TotalColumns = dtData.Columns.Count;
 
                //-->headline
                //first row is intentionaly left blank.
                var headLine = MyWorkSheet.Range(MyWorkSheet.Cell(2, 1).Address, MyWorkSheet.Cell(2, TotalColumns).Address);
                headLine.Style.Font.Bold = true;
                headLine.Style.Font.FontSize = 15;
                headLine.Style.Font.FontColor = XLColor.White;
                headLine.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
                headLine.Style.Alignment.Vertical = XLAlignmentVerticalValues.Center;
                headLine.Style.Fill.BackgroundColor = XLColor.FromTheme(XLThemeColor.Accent1, 0.25);
                headLine.Style.Border.TopBorder = XLBorderStyleValues.Medium;
                headLine.Style.Border.BottomBorder = XLBorderStyleValues.Medium;
                headLine.Style.Border.LeftBorder = XLBorderStyleValues.Medium;
                headLine.Style.Border.RightBorder = XLBorderStyleValues.Medium;
 
                headLine.Merge();
                headLine.Value = reportHeader;
                //<-- headline
 
                //--> column settings
                for (int i = 1; i < dtData.Columns.Count + 1; i++)
                {
                    String combinedHeaderText = dtData.Columns[i - 1].ColumnName.ToString();
                    string separatedColumnHeader = "";
                    foreach (char letter in combinedHeaderText)
                    {
                        if (Char.IsUpper(letter) && separatedColumnHeader.Length > 0)
                            separatedColumnHeader += " " + letter;
                        else
                            separatedColumnHeader += letter;
                    }
                    MyWorkSheet.Cell(4, i).Value = separatedColumnHeader;
                    MyWorkSheet.Cell(4, i).Style.Alignment.WrapText = true;
                }
 
                var columnRange = MyWorkSheet.Range(MyWorkSheet.Cell(4, 1).Address, MyWorkSheet.Cell(4, TotalColumns).Address);
                columnRange.Style.Font.Bold = true;
                columnRange.Style.Font.FontSize = 10;
                columnRange.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
                columnRange.Style.Alignment.Vertical = XLAlignmentVerticalValues.Center;
                columnRange.Style.Fill.BackgroundColor = XLColor.FromArgb(171, 195, 223); 
                columnRange.Style.Border.TopBorder = XLBorderStyleValues.Thin;
                columnRange.Style.Border.BottomBorder = XLBorderStyleValues.Thin;
                columnRange.Style.Border.LeftBorder = XLBorderStyleValues.Thin;
                columnRange.Style.Border.RightBorder = XLBorderStyleValues.Thin;
                //<-- column settings
 
                //--> row data & settings
                for (int i = 0; i < dtData.Rows.Count; i++)
                {
                    DataRow row = dtData.Rows[i];
                    for (int j = 0; j < dtData.Columns.Count; j++)
                    {
                        MyWorkSheet.Cell(i + 5, j + 1).Value = row[j].ToString();
                    }
                }
 
                var dataRowRange = MyWorkSheet.Range(MyWorkSheet.Cell(5, 1).Address, MyWorkSheet.Cell(dtData.Rows.Count + 4, TotalColumns).Address);
                dataRowRange.Style.Font.Bold = false;
                dataRowRange.Style.Font.FontSize = 10;
                dataRowRange.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
                dataRowRange.Style.Alignment.Vertical = XLAlignmentVerticalValues.Center;
                dataRowRange.Style.Fill.BackgroundColor = XLColor.FromArgb(219,229,241);
                dataRowRange.Style.Border.TopBorder = XLBorderStyleValues.Thin;
                dataRowRange.Style.Border.BottomBorder = XLBorderStyleValues.Thin;
                dataRowRange.Style.Border.LeftBorder = XLBorderStyleValues.Thin;
                dataRowRange.Style.Border.RightBorder = XLBorderStyleValues.Thin;
                //<-- row data & settings
 
                // Prepare the response
                Response.Clear();
                Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                Response.AddHeader("content-disposition", "attachment;filename=\""+ reportHeader +".xlsx\"");
 
                // Flush the workbook to the Response.OutputStream
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    MyWorkBook.SaveAs(memoryStream);
                    memoryStream.WriteTo(Response.OutputStream);
                    memoryStream.Close();
                }
 
                Response.End();
                return View();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


Create ClosedXML Excel

using ClosedXML;
using ClosedXML.Excel;
using System.IO;
        private void button1_Click(object sender, EventArgs e)
        {
            var workbook = new XLWorkbook();
            var ws = workbook.Worksheets.Add("Merge Cells");

            DateTime fromDate = new DateTime(2015, 03, 20);
            DateTime toDate = new DateTime(2015, 03, 30);
            Int32 columnPosition = 2;
            for (DateTime date = fromDate; date <= toDate; date = date.AddDays(1))
            {
                var range = ws.Range(ws.Cell(1, columnPosition).Address, ws.Cell(1, columnPosition+1).Address);
                range.Cell(1, 1).Value = date.ToString("yyyy-MM-dd");
                range.Merge();
                range.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
                range.Style.Fill.BackgroundColor = XLColor.Almond;

                var firstCell = ws.Cell(2, columnPosition);
                firstCell.Value = "1st"; firstCell.Style.Fill.BackgroundColor = XLColor.Amethyst;
                var secondCell = ws.Cell(2, columnPosition + 1);
                secondCell.Value = "2nd"; secondCell.Style.Fill.BackgroundColor = XLColor.Amethyst;

                columnPosition += 2;
              
            }

          
            workbook.SaveAs("MergeCells.xlsx");
        }

Full Page Web Modal

<style>
#displaybox {
	z-index: 10000;
	filter: alpha(opacity=50); /*older IE*/
	filter:progid:DXImageTransform.Microsoft.Alpha(opacity=50); /* IE */
	-moz-opacity: .50; /*older Mozilla*/
	-khtml-opacity: 0.5;   /*older Safari*/
	opacity: 0.5;   /*supported by current Mozilla, Safari, and Opera*/
	background-color:#000000;
	position:fixed; top:0px; left:0px; width:100%; height:100%; text-align:center; vertical-align:middle;
}
</style>

function clicker(){
	var thediv=document.getElementById('displaybox');
	if(thediv.style.display == "none"){
		thediv.style.display = "";
		thediv.innerHTML = "<a href='#' onclick='return clicker();'>CLOSE WINDOW</a>";
	}else{
		thediv.style.display = "none";
		thediv.innerHTML = '';
	}
	return false;
}

The hidden displaybox div
<div id="displaybox" style="display: none;"></div>


A link that will execute and return the clicker javascript function onclick: 
<a href='#' onclick='return clicker();'>Open Window</a>

Original Source of this article is here