Uncategorized

MongoDB Installation in Windows 8.1

1.Just go to MongoDB Download Center And download like the below picture.

MongoDb

2.Click and Start Installation.

Mongo Install Starts

Mongo Install Starts

3.Do the Complete Installation.

Mongo Complete

Mongo Complete

4.Go to the installed Directory and try to run Mongo Server mongod.exe , You will get exception like below.

Mongo Server mongod.exe

Mongo Server mongod.exe

5.Run the below command in terminal to create those Directories

mkdir c:\data\db
mkdir c:\data\log

6. Now try to run Mongo Server mongod.exe on terminal

C:\Program Files\MongoDB\Server\3.0\bin\mongod.exe

Depending on the security level of your system, Windows may pop up a Security Alert dialog box about blocking “some features” of C:\mongodb\bin\mongod.exe from communicating on networks. All users should select Private Networks, such as my home or work network and click Allow access.

Allow

7.Now run Mongo Client mongo.exe on another terminal

C:\Program Files\MongoDB\Server\3.0\bin\mongo.exe

Mongo Server Client

Mongo Server Client

MongoDB successfully installed.

Now lets install MongoDB as a Windows Service.

8. Now run the 3 below commands in Terminal.

echo logpath=c:\data\log\mongod.log> "C:\Program Files\MongoDB\Server\3.0\mongod.cfg"

echo dbpath=c:\data\db>> "C:\Program Files\MongoDB\Server\3.0\mongod.cfg"

sc.exe create MongoDB binPath= "\"C:\Program Files\MongoDB\Server\3.0\bin\mongod.exe\" --service --config=\"C:\Program Files\MongoDB\Server\3.0\mongod.cfg\"" DisplayName= "MongoDB" start= "auto"

Your Service is ready now.

To get mongo as CLI , add this to Environment Variable.

Mongo CLI

Mongo CLI

Standard
Uncategorized

Node : Express app with Swig

Today , I will write about a Template Engine for Express App.

And This is Swig – A simple, powerful, and extendable JavaScript Template Engine.

Its Data Binding Syntax is like Angular, And I liked it, its really simple and fun.

This is how we can configure Swig in our Express App-

var cons = require('consolidate');
 
var app = express();
app.engine('html', cons.swig);
app.set('view engine''html');
app.set('views', __dirname + "/views");
 
app.get('/'function (req, res) {
    res.render('index', { name: 'Shahjada' });
});
 
var server = app.listen(8080, function () {
    var host = server.address().address;
    var port = server.address().port;
    console.log('Example app listening at http://%s:%s', host, port);
});

And our html is like below as simple –

<h1>Hello {{name}}</h1>

 
Its easy , right ?

Cheeers

Standard
Uncategorized

NodeJS : Connect MongoDB and get Data from Collection

In any Web application , its important to connect to Database for data .

In MEAN , as we use MongoDB , so I will write code how a Node app can talk with MongoDB Database.

I have a Database named newDB and I have a collection named myColl in my local MongoDB server.

Like below , we can connect and get data from Mongo Server.

var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/newDB'function(err , db) {
 
	if(err) {
		console.log(err);
		throw err;
	}
	
	db.collection('myColl').findOne({} , function(err , doc){
	
		if(err) {
			console.log(err);
			throw err;
		}
		console.dir(doc);
		db.close();
		//res.send(doc);
	});
 
	console.dir("Called FindOne");
});

Hope this Helps.

Standard
Uncategorized

ExpressJS – Configure Routing for Express App

Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.

Express is the most popular Web Framework on Node . So, I planned to write on Express and personally I am a MEAN (Mongo, Express , Angular , Node) Stack fan and MEAN stack became much powerful in Modern Web World.

This article shows how we can configure the routing for an Express app.

var express = require('express');
var app = express();
 
app.get('/'function (req, res) {
	res.send("Home");
});
 
app.get('/profile'function (req, res) {
	res.send("Profile");
});
 
app.get('/contact'function (req, res) {
	res.send("Contact");
});
 
app.get('*'function (req, res) {
	res.send("Not Found" , 404);
});
 
var server = app.listen(3001, function() {
	var host = server.address().address;
	var port = server.address().port;
	console.log('Express app listening at http://%s:%s', host, port);
});

The code is itself self explanatory . I have created 3 Routes and if User hits any other route beside these , Express will return “Not Found” with 404 Status which has been maintained by *

Here we can see server is listening to 3001 port , make sure to use that port which is empty

app takes 2 arguments , first is the route path and second is the callback which would be fired when that Route has been hit by User.

Hope this helps.

Cheers

Standard
Uncategorized

Bind C# List of object data with HTML without using ASP.Net control in ASP.Net

In ASP.Net we always use so may ASP.Net controls . But we also know ASP.Net controls have ViewState , so we should ignore using ASP.Net controls as much as possible to reduce the Load time of DOM .

In my example , I will show how we can bind and show the data to HTML without using ASP.Net Control in ASP.Net.

I have a List of a custom object like below :

protected List<voNote> notes = new List<voNote>();

This is a list of a ViewModel . and the ViewModel of my example is like below :::

public class voNote
    {
        public string Note { get; set; }

        public DateTime Date { get; set; }

        public string NoteCreatedBy { get; set; }

        public string TicketUrgency { get; set; }
    }

Let, We have populated the List from Database Server . Now we have to show/Bind the Data to the UI .

So my markup code will be just simple like below :

<%
        foreach (voNote note in notes)
        {
    %>
            <hr class="NoteBorder" />
            <div><%=note.Date %> | <%=note.NoteCreatedBy %> | <%= note.TicketUrgency %></div>
           
            <div class="NoteDiv"><%=note.Note %></div>
    <%
        }
    
    %>

So , its done 🙂

Standard
Uncategorized

Create a Custom GroupBox for selecting multiple choice in ASP.Net and C#

Many a time , We need to create a control for selecting Multiple Inputs in our Web Applications .

I am gonna show a demo how we can create a GroupBox type thing to select multiple items and Get those values in server side .

Lets see an example …

First see the image below :

Custom GroupBox for selecting multiple choice in ASP.Net and C#

Custom GroupBox for selecting multiple choice in ASP.Net and C#

If our requirement is like – User wants to see the report for all the Tasks which are in Open and Close Status.
So User can easily select multiple options .

So Here is my mark up code below :::

<asp:GridView ID="gridTicketStatus" runat="server" AutoGenerateColumns="false">
                <Columns>
                    <asp:TemplateField HeaderText="">
                        <ItemTemplate>
                            <asp:CheckBox ID="selectCheckBox" runat="server" />
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Id" Visible="false">
                        <ItemTemplate>
                            <asp:Label ID="lblStatusId" runat="server" Text='<%#Bind("ID") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Select Status">
                        <ItemTemplate>
                            <asp:Label ID="lblTaskStatus" runat="server" Text='<%#Bind("TaskStatus") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
            </asp:GridView>

Here I used a ASP.Net Grid which gets the status from the Database and Binds the Status.And I used another CheckBox , that’s how we can create any custom control . If we also need any DropDown inside it, we can easily add the DropDown with it as same way .

The Grid binding code in C# is like :::

DataTable dtStatus = TaskStatusGateway.GetAllTaskStatuses();
            gridTicketStatus.DataSource = dtStatus;
            gridTicketStatus.DataBind();

And after clicking the Button we can easily get all the selected Statuses by doing like below.

List<int> checkedStatus = new List<int>();

            if (gridTicketStatus.Rows.Count > 0)
            {
                for (int i = 0; i < gridTicketStatus.Rows.Count; i++)
                {
                    if (((CheckBox) (gridTicketStatus.Rows[i].FindControl("selectCheckBox"))).Checked)
                    {
                        int id = Convert.ToInt32(((Label) gridTicketStatus.Rows[i].FindControl("lblStatusId")).Text);
                        checkedStatus.Add(id);
                    }
                }
            }

So we are done .

Cheers 🙂

Standard
Uncategorized

Get Identity Column Value just after Inserting a row in MS SQL Server Table

Many a time , We need to get the auto Incremented Identity Column value just after Inserting/Saving a row to a Table in MS SQL Server.

In my Case of this Example, When I Insert a New Project to my tblProjects Table , I want the ID column value( which is basically auto incremented Identity Column in SQL Server) of my inserted Row .

For this , TSQL provides us a way to do that like below –

SELECT SCOPE_IDENTITY()

So in C# , our code can be like below :::

Note : We can use StoredProcedue Which is better practice .Then inside the SP ,we will use the code mentioned.

public static int CreateProject(Project projectObj)
        {
            string insertProjectQuery = "INSERT INTO tblProjects VALUES('" + projectObj.ProjectName + "','" + projectObj.TblCustomerId + "','" + projectObj.BClosed + "') SELECT SCOPE_IDENTITY() As ProjectId";
            DataTable dt = QueryGateway.GetDataThroughDataTable(insertProjectQuery);
            return  Convert.ToInt32(dt.Rows[0]["ProjectId"]);
        }

Cheers

Standard
Uncategorized

Convert image file to Byte/Binary and Save into SQL Server

For most of the Products , We need to save many types of Image files to SQL Server Table as binary Data .

For that case , We can keep our Column of the Table as varbinary(MAX) and Save the Image into this Column . Here is the SQL to do such things .

UPDATE DocumentTable
SET
DocumentContent = (SELECT * FROM OPENROWSET(BULK N'C:\logo.jpg', SINGLE_BLOB) as imagefile)
WHERE Id = 3

Standard
Uncategorized

Compress SQL Server DB .bak file in C#

Many a time , We need to take Backup of our Production Database . Most of the Time , This process is done Automatically .

And After Taking the Database , we can also compress that and keep for later use . This is how , we can compress Our .bak file in C# .

public void CompressDbBackup(string sFileName)
        {
            try
            {
                string sZipFileName = sFileName.Replace(".bak", ".zip");

                using (FileStream fStream = File.Open(sZipFileName, FileMode.Create))
                {
                    GZipStream obj = new GZipStream(fStream, CompressionMode.Compress);

                    byte[] bt = File.ReadAllBytes(sFileName);
                    obj.Write(bt, 0, bt.Length);

                    obj.Close();
                    obj.Dispose();
                }

                File.Delete(sFileName);
            }
            catch (Exception ex)
            {
                // Log Recorded
            }
        }

There will be another Post on How we can take Database backup Programmatically .

Keep an eye on this Blog . Thanks
Cheers 🙂

Standard
Uncategorized

Time Localization using .Net TimeZone API in C#

A time zone is a geographical region in which the same time is used.

You can use the TimeZone class to retrieve information about the current time zone, and to convert times from local time to Coordinated Universal Time (UTC) or vice versa. However, you cannot use the TimeZone class to represent time zones other than the local zone or to handle date and time conversions from one time zone to another. For this purpose, use the TimeZoneInfo class. You can use this class to retrieve information on any time zone defined on the local system, to create custom time zones, and to convert times from one time zone to another.
The TimeZone class supports only a single daylight saving time adjustment rule for the local time zone. As a result, the TimeZone class can accurately report daylight saving time information or convert between UTC and local time only for the period in which the latest adjustment rule is in effect. In contrast, the TimeZoneInfo class supports multiple adjustment rules, which makes it possible to work with historic time zone data.

Lets go to an example .

If you have an Application which will be used in so many Countries and every User comments on a Note in your Site and When Another User logs in , He wants to see the comment Time in His own TimeZone , not in your time Zone . Like If a person from Switzerland comments on a Note at 9.00 AM , after that when I log in I want to see that in my Time Zone Of Bangladesh which should be 1.00 PM . I used same concept few years back in one of My Sites and its awesome 🙂

Its better to Keep the DateTime Columns as UTC Date and Then convert to User’s own TimeZone By his TimeZoneId using .Net TimeZone API .

Your Site Can have a UI which would be used by The User to Set his Own Time Zone when he gets Registered Into your Site. So That UI can be like below :::

ddlTimeZone

And You can easily populate The Time Zone List DropDown .

Here is Asp.Net markup for that :

<asp:DropDownList ID="ddlTimeZoneId" runat="server">
                </asp:DropDownList>

And Binding DropDown Code will be like :::

private void LoadTimeZoneDropDown()
        {
            ddlTimeZoneId.DataSource = clsTimeZone.GetTimeZones();
            ddlTimeZoneId.DataTextField = "TimeZoneName";
            ddlTimeZoneId.DataValueField = "TimeZoneID";
            ddlTimeZoneId.DataBind();
        }

This clsTimeZone is my custom Class which is using .Net APIs . And I used This below Method to Get the Time Zone List .

public static Collection<structTimeZone> GetTimeZones()
        {
            Collection<structTimeZone> structTimeZoneColl = new Collection<structTimeZone>();

            ReadOnlyCollection<TimeZoneInfo> timeZoneInfos = TimeZoneInfo.GetSystemTimeZones();
            foreach (TimeZoneInfo timeZoneInfo in timeZoneInfos)
            {
                structTimeZoneColl.Add(new structTimeZone { TimeZoneName = timeZoneInfo.DisplayName, TimeZoneID = timeZoneInfo.Id });
            }
            return structTimeZoneColl;
        }

public struct structTimeZone
    {
        public string TimeZoneName { get; set; }
        public string TimeZoneID { get; set; }
    }

From here , User can set his Own Time Zone from the List which .Net Framework or Windows or Microsoft supports.

So your User Table should have Column like this :::

TimeZoneIdColumn

So your Initial Setup is done .

Now When Any User from Switzerland saves Note to Notes Table , then don’t Use Local DateTime rather use UTC Time .

It can be done by using this SQL In your StoredProcedure .

GETUTCDATE()

So your DB Table will hold UTC , so you can easily convert that to any Localized format , to any Time Zone by your TimeZoneId of that User .

So When need to show the Time to UI , just call This method which will return Local time Zone Info . In my Case I did something like this :::

DateTime localTime = clsTimeZone.ConvertToLocalTimeFromUtcTime(utcDate, timeZoneId);

And the implementation of the Method is just simple like below :::

public static DateTime ConvertToLocalTimeFromUtcTime(DateTime utcDate, string timeZoneId)   
        {
            TimeZoneInfo cstZone = TimeZoneInfo.FindSystemTimeZoneById(timeZoneId);
            DateTime cstTime = TimeZoneInfo.ConvertTimeFromUtc(utcDate, cstZone);
            return cstTime;
        }

Just Show that Local Time To The UI .
So you are done 🙂

Cheers

Standard