Category Archives: ASP.NET

Lambda Extension Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Extensions;

/*
* Lambda Extension Example
*/
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            IEnumerable cities = new[] { "Ghest", "London", "Las Vegas", "Hyderabad" };

            IEnumerable query = cities.Filter( (item) => item.StartsWith("L"));
            //IEnumerable query = cities.Filter(StringThatStartWithL);
            //IEnumerable query = cities.Filter(delegate(string item) { return item.StartsWith("L"); });

            foreach(var city in query){
                Console.WriteLine(city);
            }

            Console.ReadKey();
        }

        //static bool StringThatStartWithL(string s)
        //{
        //    return s.StartsWith("L");
        //}
    }
}

namespace Extensions
{
    public delegate bool FilterDelegate(T item);

    public static class FilterExtensions
    {
        public static IEnumerable Filter(this IEnumerable input,
            FilterDelegate predicate)
        {
            foreach (var item in input)
            {
                if (predicate(item))
                {
                    yield return item;
                }
            }
        }
    }
}
Posted in ASP.NET, Tech Note | Tagged , | Leave a comment

Uploading File using Ajax and receiving binary data in Asp.net (C#)

In this post, I will show you how to upload a file using Ajax (Asynchronous JavaScript and XML) and receive the binary data in Asp.net C#. And it is ultra simple!

1. HTML

2. JS

function uploadfile(){
    var bannerImage = $("#bannerImage").val();

    if (bannerImage) {
            var file = document.getElementById('bannerImage').files[0];
            var formData = new FormData();
            formData.append(file.name, file);

            var xhr = new XMLHttpRequest();
            var url = "/Category/UpdateBannerImage";
            xhr.open('POST', url, true);
            xhr.onload = function (e) {
                var response = $.parseJSON(e.target.response);
                console.log(response.fileName);
            };

           xhr.send(formData);  // multipart/form-data

    }
}

(Sending Binary Data)

3. C#, Receiving binary data

public JsonResult UpdateBannerImage()
{
    HttpPostedFileBase bannerImage = Request.Files[0] as HttpPostedFileBase;
    if (bannerImage != null && bannerImage.ContentLength > 0)
    {
	var fileName = Path.GetFileName(bannerImage.FileName);
	fileName = Regex.Replace(fileName, @"\s|\$|\#\%", "");
	var path = Path.Combine(Server.MapPath("~/images/category_banners"), fileName);
	bannerImage.SaveAs(path);

	return Json(new { success = false ,error = false, message = "Image has been updated successfully", fileName = fileName });
    }
    else
    {
	return Json(new { success = true, error = "File is empty" });
    }
}
Posted in ASP.NET, JavaScript, Tech Note | Tagged , , , | 2 Comments

IIS7, 403 – Forbidden: Access is denied. ASP.Net MVC

I developed a application and tested on local. and I published the application on server then I got this error: 403 – Forbidden: Access is denied.

Also, I tried to run on server side,

and same error occur.

It happened because it was Forms Authentication, it is managed module. but the module was not running on the server. so it gives HTTP error 403.14-Forbidden error.

I set the ‘Run All Managed Modules for All requests’ option under the Web.Config file.

then the error message is gone.

<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules runAllManagedModulesForAllRequests="true"></modules>
<handlers>
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit"/>

IIS Modules Overview

Posted in ASP.NET, Tech Note | Tagged , , | 1 Comment

To set up for Advantage Database Server(v.11) and Code First

Server : Advantage Database Server 11

Path : \ADS_DB:6262\DB\DBB.ADD (Port : 6262)

Test Access Table : WEBORDERLN (ADT Type)

Web.config


Controller, (For use, we need to make this separate to model and controller. I mention this, because someone will say about this /..\ )

public class Ads_Context : DbContext
{
    public Ads_Context(): base("name=Ads_Context")
{
}
public DbSet webOrderLns { get; set; }
}

public class HomeController : Controller
{
    //
    // GET: /Home/

    public string Index()
    {
        var context = new Ads_Context().webOrderLns.ToList();
        return "A";
    }

}
[Table( "WEBORDERLN", Schema = "::this" )]
public class WebOrderLN
{
    [Key]
    public string PK {get; set;}
    public string FK { get; set; }
    public string pickno { get; set; }
}

The key point is,

[Table( "WEBORDERLN", Schema = "::this" )]

Advantage .NET Data Provider 11 for window download

Posted in ASP.NET, Database | Tagged , , , , | Leave a comment

PHP Curl and C# HttpWebRequest

Sample HTTP POST


POST /web_services/vterm_extensions/transaction_processing.asmx/BANKCARD_VOID HTTP/1.1
Host: www.sagepayments.net
Content-Type: application/x-www-form-urlencoded
Content-Length: length

M_ID=string&M_KEY=string&T_REFERENCE=string

Using C# HttpWebRequest

Dictionary post_values = new Dictionary();
post_values.Add("M_ID", "TestUsrID");
post_values.Add("M_KEY", "TestKey");
post_values.Add("T_REFERENCE", "TestRef");

String post_string = "";

foreach (KeyValuePair post_value in post_values)
{
   post_string += post_value.Key + "=" + HttpUtility.UrlEncode(post_value.Value) + "&";
}
post_string = post_string.TrimEnd('&');
string VOID_URL = "https://www.sagepayments.net/web_services/vterm_extensions/transaction_processing.asmx/BANKCARD_VOID";
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(VOID_URL);
objRequest.Method = "POST";
objRequest.ContentLength = post_string.Length;
objRequest.ContentType = "application/x-www-form-urlencoded";

// post data is sent as a stream
StreamWriter myWriter = null;
myWriter = new StreamWriter(objRequest.GetRequestStream());
myWriter.Write(post_string);
myWriter.Close();

// returned values are returned as a stream, then read into a string
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
using (StreamReader responseStream = new StreamReader(objResponse.GetResponseStream()))
{
   post_response = responseStream.ReadToEnd();
   responseStream.Close();
}

Console.WriteLine("Response"+post_response);

Using PHP Curl

$param = array("M_ID" => "TestUsrID", "M_KEY" => "TestKey", "T_REFERENCE" => "TestRef");

$url = "https://www.sagepayments.net/web_services/vterm_extensions/transaction_processing.asmx/BANKCARD_VOID";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);

$response = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

if (curl_errno($ch)) {
   echo "Error : ".curl_error($ch));
}
curl_close($ch);

echo "Response : ".$response;

C# HttpWebRequest Class Reference : http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx
PHP CURL Reference : http://us2.php.net/manual/en/book.curl.php

Posted in ASP.NET, PHP, Tech Note | Tagged , | 2 Comments

Asp.net (C#) Lock Table and Record (Advantage Database Server)

Lock Table

[HttpGet]
public ActionResult lockTable()
{
    string conn_string = System.Configuration.ConfigurationManager.ConnectionStrings["Ads_Context"].ConnectionString;
    using (AdsConnection conn = new AdsConnection(conn_string))
    {
	Ads_Connection.Open();

	AdsCommand cmd = new AdsCommand("misys01", conn);
	cmd.CommandType = CommandType.TableDirect;

	AdsExtendedReader reader = cmd.ExecuteExtendedReader();

	reader.LockTable();

	System.Threading.Thread.Sleep(5000); // Lock table about 5 Sec

	if (reader.IsTableLocked())
	{
	    return Content("Table is locked");
	}
	else
	{
	    return Content("Table is not locked");
	}
    }

    // Locking will be released when finished this method.
}

Update Locking Table

[HttpGet]
public ActionResult UpdateLockingTable()
{
    string conn_string = System.Configuration.ConfigurationManager.ConnectionStrings["Ads_Context"].ConnectionString;
    using (AdsConnection conn = new AdsConnection(conn_string))
    {
	Ads_Connection.Open();

	bool processing = true;

	while (processing)
	{
	    try
	    {
		string query = "SELECT finvno FROM misys01";
		AdsCommand cmd = conn.CreateCommand();
		cmd.CommandText = query;

		AdsDataReader reader = cmd.ExecuteReader();

		reader.Read();

		string invno = reader["finvno"].ToString();
		invno = "290002";

		AdsCommand cm = new AdsCommand("UPDATE misys01 SET finvno = '" + invno + "'", conn);
		cm.ExecuteNonQuery();

		processing = false;
					
	    }
	    catch (Exception e)
	    {
		processing = true; //back to loop
		//return Content(e.Message);
	    }
	}

	return Content("Updated");
    }
}

Lock Record

[HttpGet]
public ActionResult LockRecord()
{
    string conn_string = System.Configuration.ConfigurationManager.ConnectionStrings["Ads_Context"].ConnectionString;
    using (AdsConnection conn = new AdsConnection(conn_string))
    {
	Ads_Connection.Open();

	string query = "SELECT finvno FROM misys01";
	AdsCommand cmd = conn.CreateCommand();
	cmd.CommandText = query;

	AdsExtendedReader reader = cmd.ExecuteExtendedReader();
	reader.Read();
	
	int recordNo = reader.RecordNumber;
	reader.LockRecord(recordNo);

	System.Threading.Thread.Sleep(10000); // Lock record about 10 sec

	if (reader.IsRecordLocked())
	{
	    return Content("Record is locked");
	}
	else
	{
	    return Content("Record is not locked");
	}
    }
    // Locking will be released when finished this method.
}
Posted in ASP.NET, Database, Tech Note | Tagged , , , , , | 1 Comment

C#, Base64 Encode & Decode method

public string base64Encode(string data)
{
    try
    {
	byte[] byte_data = new byte[data.Length];
	byte_data = System.Text.Encoding.UTF8.GetBytes(data);
	string encodedData = Convert.ToBase64String(byte_data);
	return encodedData;
    }
    catch (Exception e)
    {
	throw new Exception(e.Message);
    }
}

public string base64Decode(string data)
{
    try
    {
	System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
	System.Text.Decoder utf8Decode = encoder.GetDecoder();
	byte[] byte_data = Convert.FromBase64String(data);
	int charCount = utf8Decode.GetCharCount(byte_data, 0, byte_data.Length);
	char[] decoded_char = new char[charCount];
	utf8Decode.GetChars(byte_data, 0, byte_data.Length, decoded_char, 0);
	string result = new String(decoded_char);
	return result;
    }catch(Exception e){
	throw new Exception(e.Message);
    }
}
Posted in ASP.NET, Tech Note | Tagged , , , , , , | Leave a comment

The application pool that you are trying to use has the ‘managedRuntimeVersion’ property set to ‘v2.0’. This application requires ‘v4.0’.

Error Message :

The application pool that you are trying to use has the ‘managedRuntimeVersion’ property set to ‘v2.0’. This application requires ‘v4.0’.

Posted in ASP.NET, Tech Note | Tagged | 2 Comments

Inject Script and Css files into _Layout from view

There are many way to insert loading script and css tags into _Layout.

And I like to use Section, because it is the most simple I think.

[View]

@section Header {

< script src="@Url.Content("~/Scripts/app.js")" type="text/javascript">< /script>

}

[_Layout]

.
// [IN HEAD]
.
@if(IsSectionDefined("Header")){
   @RenderSection("Header")
}
Posted in ASP.NET, Tech Note | 1 Comment