Wednesday, 15 October 2014

How to Use Log4net with ASP.NET MVC 5 for Logging

Log4net is an open source library that allows .NET applications to log output to a variety of sources.

Log4net provides a simple mechanism for logging information to a variety of sources. 
Information is logged via one or more loggers. These loggers provide 5 levels of logging:
  1. Debug
  2. Information
  3. Warnings
  4. Error
  5. Fatal
Here I will be walking through the step by step in implementing logging functionality using log4net framework in an ASP.NET MVC 5 application.

I am using Visual Studio Express 2013 for Web as my development environment targeting .NET framework 4.5.1

Step 1:

Open Visual Studio 2013 for Web and create a new ASP.NET Web application selecting MVC template.

Step 2: 

Now We need to add reference of log4net DLL using NuGet package manager.






Step 3:

Next, we need to configure our application to use log4net logging framework. Add the below line in yourstartup.cs file in ASP.NET MVC5 Solution folder. The below line of code provides information about log4net configuration file.

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "Web.config", Watch = true)]




Step 4:

Next, add the below section to web.config file.

<configSections>
    <!-- Add log4net config section-->
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,     log4net" />
  </configSections>

  <log4net debug="true">
    <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="logs\log.txt" />
      <appendToFile value="true" />
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="10MB" />
      <staticLogFileName value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%-5p %d %5rms %-22.22c{1} %-18.18M - %m%n" />
      </layout>
    </appender>

    <root>
      <level value="DEBUG" />
      <appender-ref ref="RollingLogFileAppender" />
    </root>
  </log4net>

Step 5:

Next modify Global.asax.cs and add the below code inside Application_Start() method.

readonly log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

Step 6:

Use the logger.Error() method to log messages when needed.


Step 7:

Run an application and we can see the log file generated under the logs folder under the application root directory as configured in the web config file.




DONE :)


Tuesday, 9 September 2014

instance failure' error while connection string is correct



If you got the error "instance failure", that might be the error with your SQL Server instance..


Make sure your SQL Server instance(i.e MS SQLSERVER) is running, where you can check in Services list. to get into services list: open run dialog box and type: "services.msc" (without quotes) and hit Enter.

That takes you to services management console, where you can check whether your instance in running or not..
If the problem still persists, then try using: Data Source=.\SQLEXPRESS.

For Example

 

Monday, 4 August 2014

HTTP could not register URL http://+:8080/. Your process does not have access rights to this namespace


HTTP could not register URL http://+:8080/. Your process does not have access rights to this namespace (see http://go.microsoft.com/fwlink/?LinkId=70353 for details).


Solution:
If You all are Getting This error in WCF, then just closed Visual studio and reopened it by right clicking on the Visual Studio icon and saying "Run as Administrator", Then it will Work !!!


 <system.serviceModel>
    <services>
      <service name="CompanyService.CompanyService" behaviorConfiguration="mexBehavior">
        <endpoint address="CompanyService" binding="basicHttpBinding" contract="CompanyService.ICompanyPublicService"></endpoint>
      <endpoint address="CompanyService" binding="netTcpBinding" contract="CompanyService.ICompanyConfidentialService"></endpoint>
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8000/"/>
          <add baseAddress="net.tcp://localhost:8090/"/>
          </baseAddresses>
        </host>
    </service>
    </services>
  <behaviors>
    <serviceBehaviors>
      <behavior name="mexBehavior">
        <serviceMetadata httpGetEnabled="true"/>
      </behavior>
    </serviceBehaviors>
  </behaviors>
  </system.serviceModel>

Friday, 1 August 2014

Full page video background with HTML5 and CSS in MVC5

View

<video id="video" preload="auto" autoplay="true" loop="loop" muted="muted" volume="0">
     <source src="movie.mp4" type="video/mp4">
    Sorry, your browser does not support HTML5 video.
</video>
 
 
CSS
 
#video {
     position: absolute;
     top: 0px;
     left: 0px;
     min-width: 100%;
     min-height: 100%;
     width: auto;
     height: auto;
     z-index: -1000;
     overflow: hidden;
}
 
Thats it ;) 

Remove Auto-Generated advertisement script appended to the results returned by ajax requests (Web hosting by Somee.com)

Remove Auto-Generated advertisement script appended to the results returned by ajax requests


OR

Removing or hiding javascript from a page using Javascript

Or
How to Remove Generated Script from somee.com

I have hosted my Site on somee.com.
I have used JQuery to send ajax requests.
On every ajax request the returned result is appended with the below text.
"<!--SCRIPT GENERATED BY SERVER! PLEASE REMOVE--> 
<center><a href="http://somee.com">Web hosting by Somee.com</a></center> </textarea>
</xml></script></noframes></noscript></object></layer></style></title></applet> 
<script language="JavaScript" 
src="http://ads.mgmt.somee.com/serveimages/ad2/WholeInsert4.js"></script>
<!--SCRIPT GENERATED BY SERVER! PLEASE REMOVE-->"
SO How to Resolve it .....

To Resolve Just Write the following Script

    <script>
        $(document).ready(function () {
            $("div[style='opacity: 0.9; z-index: 2147483647; position: fixed; left: 0px; bottom: 0px; height: 65px; right: 0px; display: block; width: 100%; background-color: #202020; margin: 0px; padding: 0px;']").remove();
            $("div[style='margin: 0px; padding: 0px; left: 0px; width: 100%; height: 65px; right: 0px; bottom: 0px; display: block; position: fixed; z-index: 2147483647; opacity: 0.9; background-color: rgb(32, 32, 32);']").remove();
            $("div[onmouseover='S_ssac();']").remove();
            $("center").remove();
        });
</script>


Thats It ;)



Tuesday, 29 July 2014

How to Post JSON Data to an MVC5 Controller via Ajax

It's just a simple form where you enter your first name and last name, and then use a multiselect dropdown to pick your favorite bands.

Home













and enter your First name, Last name and select your favorite Car.














Step 1: First Create PersonController.css

 [HttpGet]
        public ActionResult Index()
        {
            return View(new PersonModel());
        }

        [HttpPost]
        public JsonResult BadSave(string first, string last, List<string> favoriteBands)
        {
            Console.WriteLine(first);
            Console.WriteLine(last);
            Console.WriteLine(String.Join(" ",favoriteBands));

            return Json(new { result = "saved the bad way" });
        }

        [HttpPost]
        public JsonResult GoodSave(PersonModel model)
        {
            Console.WriteLine(model.First);
            Console.WriteLine(model.Last);
            Console.WriteLine(String.Join(" ", model.FavoriteBands));

            return Json(new { result = "saved the good way" });

        }


Step 2 : Create PersonModel.css Model

public class PersonModel
    {
        [DisplayName("First Name")]
        public string First { get; set; }

        [DisplayName("Last Name ")]
        public string Last { get; set; }

        [DisplayName("Favorite Car")]
        public List<string> FavoriteBands { get; set; }
    }

Step 3 : Create the View ie Index.cshtml

@model MVCJsonPost.Models.PersonModel
@{
    ViewBag.Title = "Home";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Home</h2>

<div>
    @Html.LabelFor(m => m.First)
    @Html.EditorFor(m => m.First)
</div>

<div>
    @Html.LabelFor(m => m.Last)
    @Html.EditorFor(m => m.Last)
</div>

<div>
    @Html.LabelFor(m => m.FavoriteBands)
    @Html.DropDownListFor(m => m.FavoriteBands, new SelectList(
                  new List<Object>{ 
                       new { value = 0 , text = "Honda City"  },
                       new { value = 1 , text = "Renault fluence" },
                       new { value = 2 , text = "Hyundai xcent"}
                    },
                  "value",
                  "text",
                   Model.FavoriteBands),
                    new { multiple = "multiple" })


</div>

<div>
    <input type="button" value="Bad Submit" id="bad" />
    <input type="button" value="Good Submit" id="good" />
</div>

<label id="result"></label>

Step 4: Create the js file i.e person.js in Script Folder

$(document).ready(function () {
    $('#good').click(function () {
        var request = new PersonModel();
        debugger;
        $.ajax({
            url: "Person/GoodSave",
            dataType: 'json',
            contentType: "application/json",
            type: "POST",
            data: JSON.stringify(request), //Ahhh, much better
            success: function (response) {
                $("#result").text(response.result);
            }
        });
    });

    $('#bad').click(function () {
        var request = new PersonModel();
        debugger;
        $.ajax({
            url: "Person/BadSave",
            dataType: 'json',
            type: "POST",
            data: "first=" + request.First + "&last=" + request.Last + "&favoriteBands=" + request.FavoriteBands, //How do you encode an array?? This doesn't even work right
            success: function (response) {
                $("#result").text(response.result);
            }
        });
    });
});

function PersonModel() {
    var self = this;
    self.First = $("#First").val();
    self.Last = $("#Last").val();

    self.FavoriteBands = $.map($('#FavoriteBands option:selected'),
                      function (e) { return $(e).val(); });
}


Run The Application  and fill the form and place some breakpoint to test and debug line by line















Done :)




Friday, 25 July 2014

How to Creating or Deleting a Profile in Another Language in LinkedIn

You can Create your profile in any number of language(to create you should visit http://www.linkedin.com/profile/edit-profile-in-another-language )  from the View Profile page.
While you can't change the language of your primary profile, you can create as many other language profiles as there are languages available.
So Now Question is How to create your profile in another language:
So For that :
  1. Click Profile at the top of your homepage.
  2. Click the  down arrow next to the Edit Profile button and select "Create profile in another language".
  3. Choose a language from the dropdown list and update your first name and last name if they're different in the new profile's language.
  4. Translate your existing Professional Headline.
    • Translations aren't done for you. You'll need to translate your own personal content.
  5. Click Create Profile to go to the Edit Profile page of your new language profile.
  6. Click any  Edit icon and translate the open fields.
  7. Click Save and continue editing other sections.
And How to delete a secondary language profile:
  1. Move your cursor over Profile at the top of your homepage and select Edit Profile.
  2. Select the language from the Profile dropdown list in the upper right.
  3. Click the Delete this profile link. If this link doesn't appear, the profile you're viewing is your primary profile. You can't change your primary profile's language setting.
  4. Click Delete.
Notes:
  • It is not possible to make another language profile as your default profile.

Thursday, 24 July 2014

How to Back Up Your Gmail Account

On February 28, 2011, Google confirmed that many Gmail users had temporarily lost access to their emails.If you're worried about ever losing your emails to a similar glitch, it's probably a good idea to regularly backup your Gmail account. By configuring an email client on your computer, you can download your emails onto your hard drive by following these steps
Method 1: Mail Settings in Gmail
Step 1: Log into Gmail and click on "Mail Settings" in the top right hand corner. This can be accessed from any Gmail page.
Step 2: Locate and click on the "Forwarding and POP/IMAP" tab.
Step 3: Look under "POP Download". Select the first option, "Enable POP for all mail (even mail that's already been downloaded)".
Step 4: Click on "Save Changes" at the bottom.
Step 5: Configure your mail client following the steps below. Once your mail client is configured to download your email, remember to open it periodically to backup.
Method 2 : Download Gmail Backup
Step 1: Go to: https://code.google.com/p/gmail-backup-com/ and select "download" to install the software.
Step 2: Open your command or terminal and go to directory of the program.
Step 3: Run the program and replace "dir" with the directory name you want to use and your email address with your own password.

Tuesday, 22 July 2014

Ccavenue Payment Integration in asp.net mvc5



Here i am writing a simple article to integrate Ccavenue payment integration.

Controller 

public ActionResult ccavenueForm()
 {
   try
            {
                Payment_ccavenue myUtility = new Payment_ccavenue();
             //This id(also User Id)  available at "Generate Working Key" of "Settings & Options" ;
                string Merchant_Id = "M_ravicm_14844";
             // 'your script should substitute the amount here in the quotes provided here
                string Amount = Session["Payment_Amount_CCAvenue"].ToString();
                string Order_Id = Session["Custom_Field"].ToString();// 'your script should substitute the order description here in the quotes provided here
                string Redirect_Url = GlobalVariables.Redirect_Redirect_ccavenue;//'your redirect URL where your customer will be redirected after authorisation from CCAvenue               
                string WorkingKey = "1r5aced2v9mmaqhb3k";// 'put in the 32 bit alphanumeric key in the quotes provided here.Please note that get this key ,login to your CCAvenue merchant account and visit the "Generate Working Key" section at the "Settings & Options" page. 
                ViewBag.Redirect_Redirect_ccavenue = Redirect_Url;
                ViewBag.Checksum = myUtility.getchecksum(Merchant_Id, Order_Id, Amount, Redirect_Url, WorkingKey);
                return View();
            }
            catch
            {
                // string S = Exception.ToString();
                return RedirectToRoute("ErrorHandling");
            }
        }

View 


<!-- #include virtual = "/payment/libfuncs.asp" -->
<HTML>
<HEAD>
<TITLE>Sub-merchant checkout page: www.mywebsite.com</TITLE>
</HEAD>
<BODY onload="document.forms['ccavenueForm'].submit();">
@{
string     Merchant_Id = "M_ravicm_14844"; //This id(also User Id)  available at "Generate Working Key" of "Settings & Options" ;
string Amount = Session["Payment_Amount_CCAvenue"].ToString();// 'your script should substitute the amount here in the quotes provided here
string Order_Id = Session["Custom_Field"].ToString();// 'your script should substitute the order description here in the quotes provided here
string Redirect_Url = @ViewBag.Redirect_Redirect_ccavenue;//'your redirect URL where your customer will be redirected after authorisation from CCAvenue
  //  Amount = "21";
    string WorkingKey = "2er4ed2v9mmaqhb3k"  ;// 'put in the 32 bit alphanumeric key in the quotes provided here.Please note that get this key ,login to your CCAvenue merchant account and visit the "Generate Working Key" section at the "Settings & Options" page. 
    
    string Checksum = ViewBag.Checksum;
    //Amount = "1111";
    string  billing_cust_name = "";
    string  billing_cust_address = "";
    string  billing_cust_state = "";
    string  billing_cust_country = "";
    string  billing_cust_tel = "";
    string  billing_cust_email = "";
    string delivery_cust_name = "";
    string  delivery_cust_address = "";
    string  delivery_cust_state = "";
    string  delivery_cust_country = "";
    string  delivery_cust_tel = "";
    string  delivery_cust_notes = "";
    string  Merchant_Param = "" ;
    string  billing_zip = "";
    string  delivery_zip = "";
    string billing_city = "";
    string delivery_city = "";

    }
<formmethod="post"name="ccavenueForm"action="https://www.ccavenue.com/shopzone/cc_details.jsp">
    <input type=hidden name=Merchant_Id value="@Merchant_Id">
    <input type=hidden name=Amount value="@Amount">
    <input type=hidden name=Order_Id value="@Order_Id">
    <input type=hidden name=Redirect_Url value="@Redirect_Url">
    <input type=hidden name=Checksum value="@Checksum">
    <input type="hidden" name="billing_cust_name" value="@billing_cust_name"> 
    <input type="hidden" name="billing_cust_address" value="@billing_cust_address"> 
    <input type="hidden" name="billing_cust_state" value="@billing_cust_state">
    <input type="hidden" name="billing_cust_country" value="@billing_cust_country"> 
    <input type="hidden" name="billing_cust_city" value="@billing_city"> 
    <input type="hidden" name="billing_zip_code" value="@billing_zip"> 
    <input type="hidden" name="billing_cust_tel" value="@billing_cust_tel"> 
    <input type="hidden" name="billing_cust_email" value="@billing_cust_email"> 
    <input type="hidden" name="delivery_cust_name" value="@delivery_cust_name"> 
    <input type="hidden" name="delivery_cust_address" value="@delivery_cust_address">
    <input type="hidden" name="delivery_cust_country" value="@delivery_cust_country"> 
    <input type="hidden" name="delivery_cust_state" value="@delivery_cust_state">
    <input type="hidden" name="delivery_cust_tel" value="@delivery_cust_tel"> 
    <input type="hidden" name="delivery_cust_notes" value="@delivery_cust_notes"> 
    <input type="hidden" name="Merchant_Param" value="@Merchant_Param"> 
    <input type="hidden" name="billing_zip_code" value="@billing_zip"> 
    <input type="hidden" name="delivery_cust_city" value="@delivery_city"> 
    <input type="hidden" name="delivery_zip_code" value="@delivery_zip"> 
    <!--<INPUT TYPE="submit" value="submit">-->
    </form>
</BODY>
</HTML>

Monday, 21 July 2014

How to Integrate Payzippy Payment gateway in Asp.net3.5 ?


Payzippy is one of the latest and Fast growing  payment gateway providing service in India(fom flipkart.com). They are providing SDK for PHP and Java but still no SDK for .NET platform. But Using Payzippy Rest API (support for JSON) , We can create Payment Integration in ASP.NET .

CS File

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Security.Cryptography;
public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
       protected Default2()
        {
            this.Init += Charging_Init;
            Main();
        }
       private void Charging_Init(object sender, EventArgs e)
        {
            this.EnableViewState = false;
        }
       private static string secretKey = "KEY_KEY_KEY_KEY_KEY";
        private static string generateSHA256(String input)
        {
            SHA256Managed crypt = new SHA256Managed();
            string hash = String.Empty;
            byte[] crypto = crypt.ComputeHash(Encoding.ASCII.GetBytes(input), 0, Encoding.ASCII.GetByteCount(input));
            foreach (byte bit in crypto)
            {
                hash += bit.ToString("x2");
            }
            return hash;
        }
        static string GenHash(Dictionary<string, string> chargingParams)
        {
            // Acquire keys and sort them.
            List<string> list = new List<string>(chargingParams.Keys);
            list.Sort();
            StringBuilder stringForHash = new StringBuilder();
            // Loop through keys.
            foreach (var key in list)
            {
                stringForHash.Append(chargingParams[key] + '|');
            }
            stringForHash.Append(secretKey);
            return generateSHA256(stringForHash.ToString());
        }
        public Dictionary<string, string> chargingParams;
        private void Main()
        {
            var currentTime = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond;

            this.chargingParams = new Dictionary<string, string>();
            chargingParams.Add("merchant_id", "test"); //Your MID issued by PayZippy.
            chargingParams.Add("buyer_email_address", "email@gmail.com"); // Email Address
            chargingParams.Add("merchant_transaction_id", "PAY_" + currentTime); //Your Transaction Id
            chargingParams.Add("transaction_type", "SALE"); //This is the default Value.
            chargingParams.Add("transaction_amount", "10000"); //Amount must be in paise. So, 1 Rupee= 100.
            chargingParams.Add("payment_method", "CREDIT"); // CREDIT,DEBIT,EMI,NET
            chargingParams.Add("bank_name", ""); //Bank Name required in case of EMI/NET.
            chargingParams.Add("emi_months", "0"); // Emi Months in case of EMI.
            chargingParams.Add("currency", "INR"); //INR is default.
            chargingParams.Add("ui_mode", "IFRAME"); //REDIRECT/IFRAME.
            chargingParams.Add("hash_method", "SHA256"); //MD5, SHA256
            chargingParams.Add("merchant_key_id", "payment"); //This is the default value.
            chargingParams.Add("timegmt", currentTime.ToString());
            chargingParams.Add("callback_url", "http://busnow.in/bus/default.aspx");
            chargingParams.Add("hash", GenHash(chargingParams));

            StringBuilder builder = new StringBuilder();
            builder.Append("https://www.payzippy.com/payment/api/charging/v1?");
            foreach (var entry in chargingParams)
            {
                builder.AppendFormat("{0}={1}&", entry.Key, entry.Value);
            }
            Console.WriteLine(builder.ToString());


        }

VIEW FILE(Code Design File)

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" action="https://www.payzippy.com/payment/api/charging/v1" method="post" runat="server">
        <div>
            <div>
                <%
                var url = "https://www.payzippy.com/payment/api/charging/v1?";
                foreach (var entry in chargingParams)
                {
                %>
                <input type="hidden" name="<%=entry.Key %>" value="<%=entry.Value %>" />
                <%
                url += entry.Key + "=" + entry.Value + "&";
                // do something with entry.Value or entry.Key
                }

                %>

                <input type="submit" />
            </div>
            <iframe width="500" height="500" src="<%=url %>"></iframe>
        </div>
    </form>
    <script>
        var x = document.getElementById("__VIEWSTATE");
        x.parentNode.removeChild(x);
    </script>
</body>

</html>

When you will Run you will get error message.


So first you have to register with PayZippy and get 

1. MID (merchant_id)
2. Secure key (used to determine hash)

3. Secure key id (merchant_key_id)


Then  place the value in the code and test :)