ASP.NET – How to call a server-side method from client-side JavaScript

Decoding the Web

Introduction

This is a tutorial on how to call a server-side ASP.NET method from a client-side JavaScript method.

If you are wondering when that could become useful, imagine the following scenario:

A Web Application having an implemented authentication system.
Users log in with their username and password.
At any point the user is able to log out by clicking on the respective “Log Out” button.
On the server-side, the log out action would trigger a cleaning up process of user’s temp data.

However, the user instead of clicking on the “Log Out” button, may simply close the browser window. Now since HTTP is a stateless protocol, the server-side cannot directly detect the user’s action. Therefore the client-side (browser) would have to notify the server that the user is closing the window.

A solution to this problem would be to call a JavaScript function when the client-side “onUnload” event…

View original post 397 more words

Converting Linq Expressions to T-SQL

devioblog

In my post about a Batch Update command for Linq To SQL, the code I presented uses a method ToMSSqlString() which has not yet been defined.

The method converts a Linq Expression to a T-SQL expression by evaluating the current node of the expression tree and evaluation the node’s children:

public static class ExpressionExtensions { public static string ToMSSqlString(this Expression expression) { switch (expression.NodeType) { case ExpressionType.Add: var add = expression as BinaryExpression; return add.Left.ToMSSqlString() + " + " + add.Right.ToMSSqlString(); case ExpressionType.Constant: var constant = expression as ConstantExpression; if (constant.Type == typeof(string)) return "N'" + constant.Value.ToString().Replace("'", "''") + "'"; return constant.Value.ToString(); case ExpressionType.Equal: var equal = expression as BinaryExpression; return equal.Left.ToMSSqlString() + " = " + equal.Right.ToMSSqlString(); case ExpressionType.Lambda: var l = expression as LambdaExpression; return l.Body.ToMSSqlString(); case ExpressionType.MemberAccess: var memberaccess = expression as MemberExpression; // todo: if column aliases are used, look up ColumnAttribute.Name return "[" +…

View original post 74 more words

How to read object images from MS-Word using Interop

Obtaining Image from ms-word gave me headache for  a week. MS-Word contains two type of shapes: Shape and InlineShapes.

Shape refers to the objects inserted as object like Chemical Equations, Microsoft Equations, while inline shapes refer to images inserted, drawings etc. Following code provides an way to save both such files.

An updated version of the code will be republished later.

using System.Drawing;

using System.Drawing.Imaging;

using System.IO;

using System.Threading;

using System.Windows.Forms;

using MyProject.Common;

using Microsoft.Office.Interop.Word;

using Application = Microsoft.Office.Interop.Word.Application;

public class InteropOfficeHelper

{

public void Main(string filePath, int index, string savedFilePath, bool isInline)

{

// Open a doc file

var wordApplication = new Application();

var document = wordApplication.Documents.Open(filePath);

//if not inline and other shapes

if (!isInline)

{

if (index <= wordApplication.ActiveDocument.Shapes.Count)

{

var shapeId = index;

var thread = new Thread(() => SaveShapeToFile(shapeId, wordApplication, savedFilePath));

thread.SetApartmentState(ApartmentState.STA);

thread.Start();

thread.Join();

}

}

//if inliine images

else

{

if (index <= wordApplication.ActiveDocument.InlineShapes.Count)

{

var shapeId = index;

var thread = new Thread(() => SaveInlineShapeToFile(shapeId, wordApplication, savedFilePath));

thread.SetApartmentState(ApartmentState.STA);

thread.Start();

thread.Join();

}

}

// Close word

wordApplication.Quit();

}

protected static void SaveInlineShapeToFile(int inlineShapeId, Application wordApplication, string savedFilePath)

{

// Get the shape, select, and copy it to the clipboard

var inlineShape = wordApplication.ActiveDocument.InlineShapes[inlineShapeId];

inlineShape.Select();

wordApplication.Selection.Copy();

// Check data is in the clipboard

if (Clipboard.GetDataObject() != null)

{

var data = Clipboard.GetDataObject();

// Check if the data conforms to a bitmap format

if (data != null && data.GetDataPresent(DataFormats.Bitmap))

{

// Fetch the image and convert it to a Bitmap

var image = (Image)data.GetData(DataFormats.Bitmap, true);

var currentBitmap = new Bitmap(image);

// Save the bitmap to a file

currentBitmap.Save(savedFilePath);

}

}

}

protected static void SaveShapeToFile(int shapeId, Application wordApplication, string savedFilePath)

{

// Get the shape, select, and copy it to the clipboard

var shape = wordApplication.ActiveDocument.Shapes[shapeId];

shape.Select();

wordApplication.Selection.Copy();

// Check data is in the clipboard

var data = Clipboard.GetDataObject();

if (data != null)

{

// Check if the data conforms to a bitmap format

if (data.GetDataPresent(DataFormats.Bitmap))

{

// Fetch the image and convert it to a Bitmap

var image = (Image)data.GetData(DataFormats.Bitmap, true);

var currentBitmap = new Bitmap(image);

// Save the bitmap to a file

currentBitmap.Save(savedFilePath);

}

else if (data.GetDataPresent(“PNG”))

{

var byteArray = StreamHelper.ReadToEnd((Stream)data.GetData(“PNG”));

using (var stream = new MemoryStream(byteArray))

{

using (var newImage = Image.FromStream(stream))

{

newImage.Save(savedFilePath, ImageFormat.Png);

}

}

}

else if (data.GetDataPresent(“GIF”))

{

var byteArray = StreamHelper.ReadToEnd((Stream)data.GetData(“GIF”));

using (var stream = new MemoryStream(byteArray))

{

using (var newImage = Image.FromStream(stream))

{

newImage.Save(savedFilePath, ImageFormat.Gif);

}

}

}

}

}

}

USING CURSOR IN MSSQL 2008 R2

Using Cursor is one of my favorite option while i need to perform a loop for an undefined sets of data, though this might cost you operational in-efficiency and memory leakage problems. Hence i suggest you DO NOT use cursor until you need to perform row by row operations on a list of data.
Before Starting with an example, lets go through basic working principle of using cursor in MSSQL.
First you need to define a temporary variable (which is a normal variable) to fetch particular column value into it for operation.
Then you define the cursor name along with data-type you need to hold and the query that fetches a list of the values.
And after you get all these values you fetch data until all the data have been fetched.
Lets see an Example.

— temporary variable that holds the data from cursor 
DECLARE @ID int

— now define cursor and its source
DECLARE cursor_Author_ID
                  CURSOR READ_ONLY FOR 
                 SELECT au_id FROM authors

open cursor
OPEN cursor_Author_ID
 
–fetch first Data
 FETCH NEXT FROM cursor_Author_ID INTO 
               @ID
–keep fetching data until all data have been read
 WHILE @@FETCH_STATUS = 0 
              BEGIN
               —write your code here, use the ID

                                                                
                   –keep fetching data until all data have been read  

                    FETCH NEXT FROM cursor_Author_ID  INTO  
                    @ID  
           END 
you need to close the cursor like any file, after opening it
 CLOSE cursor_Author_ID  
— deallocate the cursor to release all the resources used by it and 
— also reuse the for other variables
 DEALLOCATE  cursor_Author_ID  

Introduction

Hi, everyone. This is me Sagar Khyaju. I’m working as software developer in e-Zone International in Baneshwor, Kathmandu Nepal. It has been 2 years since my professional career start-up. Although the duration has not been so big, I will be sharing my experiences and knowledge and problems, I have faced yet.

My area of coverage will be basically in c#, .net, ASP.NET, ASP.NET MVC, SQL SERVER, OOP (Object Oriented Programming) etc and more. 

Using Encryption/Decryption of System.Security of C#.NET 4.0


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security;
using System.Security.Cryptography;

namespace FMISLayer.Service
{
public class clsSecurityService
{
///

/// Generates a hash for the given plain text value and returns a
/// base64-encoded result. Before the hash is computed, a random salt
/// is generated and appended to the plain text. This salt is stored at
/// the end of the hash value, so it can be used later for hash
/// verification.
///

 

////// Plaintext value to be hashed. The function does not check whether
/// this parameter is null.
/// ////// Name of the hash algorithm. Allowed values are: “MD5”, “SHA1”,
/// “SHA256”, “SHA384”, and “SHA512” (if any other value is specified
/// MD5 hashing algorithm will be used). This value is case-insensitive.
/// ///
/// Hash value formatted as a base64-encoded string.
///
public static string ComputeHash(string plainText, string hashAlgorithm)
{

// Convert plain text into a byte array.
byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

// Because we support multiple hashing algorithms, we must define
// hash object as a common (abstract) base class. We will specify the
// actual hashing algorithm class later during object creation.
HashAlgorithm hash;

// Make sure hashing algorithm name is specified.
if (hashAlgorithm == null)
hashAlgorithm = “”;

// Initialize appropriate hashing algorithm class.
switch (hashAlgorithm.ToUpper())
{
case “SHA1”:
hash = new SHA1Managed();
break;

case “SHA256”:
hash = new SHA256Managed();
break;

case “SHA384”:
hash = new SHA384Managed();
break;

case “SHA512”:
hash = new SHA512Managed();
break;

default:
hash = new MD5CryptoServiceProvider();
break;
}

// Compute hash value of our plain text with appended salt.
byte[] hashBytes = hash.ComputeHash(plainTextBytes);

// Convert result into a base64-encoded string.
string hashValue = Convert.ToBase64String(hashBytes);

// Return the result.
return hashValue;
}

///

/// Compares a hash of the specified plain text value to a given hash
/// value.
///

 

////// Plain text to be verified against the specified hash. The function
/// does not check whether this parameter is null.
/// ////// Name of the hash algorithm. Allowed values are: “MD5”, “SHA1”,
/// “SHA256”, “SHA384”, and “SHA512” (if any other value is specified,
/// MD5 hashing algorithm will be used). This value is case-insensitive.
/// ////// Base64-encoded hash value produced by ComputeHash function. This value
/// includes the original salt appended to it.
/// ///
/// If computed hash mathes the specified hash the function the return
/// value is true; otherwise, the function returns false.
///
public static bool VerifyHash(string plainText,string hashAlgorithm,string hashValue)
{
byte[] hashWithSaltBytes;
try
{
// Convert base64-encoded hash value into a byte array.
hashWithSaltBytes = Convert.FromBase64String(hashValue);
}
catch
{
return false;
}
// We must know size of hash (without salt).
int hashSizeInBits, hashSizeInBytes;

// Make sure that hashing algorithm name is specified.
if (hashAlgorithm == null)
hashAlgorithm = “”;

// Size of hash is based on the specified algorithm.
switch (hashAlgorithm.ToUpper())
{
case “SHA1”:
hashSizeInBits = 160;
break;

case “SHA256”:
hashSizeInBits = 256;
break;

case “SHA384”:
hashSizeInBits = 384;
break;

case “SHA512”:
hashSizeInBits = 512;
break;

default: // Must be MD5
hashSizeInBits = 128;
break;
}

// Convert size of hash from bits to bytes.
hashSizeInBytes = hashSizeInBits / 8;

// Make sure that the specified hash value is long enough.
if (hashWithSaltBytes.Length < hashSizeInBytes)
return false;

// Allocate array to hold original salt bytes retrieved from hash.
byte[] saltBytes = new byte[hashWithSaltBytes.Length –
hashSizeInBytes];

// Copy salt from the end of the hash to the new array.
for (int i = 0; i < saltBytes.Length; i++)
saltBytes[i] = hashWithSaltBytes[hashSizeInBytes + i];

// Compute a new hash string.
string expectedHashString = ComputeHash(plainText, hashAlgorithm);

// If the computed hash matches the specified hash,
// the plain text value must be correct.
return (hashValue == expectedHashString);
}

}
}