Wednesday, 24 August 2016


Handling JSON Arrays Returned From ASP.NET Web Services With jQuery



using System; 
using System.Collections.Generic; 
using System.Configuration; 
using System.Data; 
using System.Linq; 
using System.Text; 
using System.Text.RegularExpressions; 
using System.Web; 
using System.Web.Script.Serialization; 
using System.Web.Script.Services; 
using System.Web.Services; 
namespace VIS { 
    [WebService(Namespace = "http://tempuri.org/")] 
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 
    [System.ComponentModel.ToolboxItem(false)] 
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService] 
    public class WebMyService: System.Web.Services.WebService { 
        string connetionString = null; 
        SqlConnection sqlCnn; 
        SqlCommand sqlCmd; 
        SqlDataAdapter adapter = new SqlDataAdapter(); 
        DataSet dsbind = new DataSet(); 
        int i = 0; 
        string sql = null; 
        public class Gender { 
            public string employeeid { 
                get; 
                set; 
            } 
            public string male { 
                get; 
                set; 
            } 
            public string female { 
                get; 
                set; 
            } 
        } 
        public string JSONConversion(DataTable dt) { 
                DataSet ds = new DataSet(); 
                ds.Merge(dt); 
                StringBuilder JsonString = new StringBuilder(); 
                JsonString.Append("{"); 
                JsonString.Append("\"Data\""); 
                JsonString.Append(":"); 
                if (ds != null && ds.Tables[0].Rows.Count > 0) { 
                    JsonString.Append("["); 
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++) { 
                        JsonString.Append("{"); 
                        for (int j = 0; j < ds.Tables[0].Columns.Count; j++) { 
                            if (j < ds.Tables[0].Columns.Count - 1) { 
                                JsonString.Append("\"" + ds.Tables[0].Columns[j].ColumnName.ToString() + "\":" + "\"" + ds.Tables[0].Rows[i][j].ToString() + "\","); 
                            } else if (j == ds.Tables[0].Columns.Count - 1) { 
                                JsonString.Append("\"" + ds.Tables[0].Columns[j].ColumnName.ToString() + "\":" + "\"" + ds.Tables[0].Rows[i][j].ToString() + "\""); 
                            } 
                        } 
                        if (i == ds.Tables[0].Rows.Count - 1) { 
                            JsonString.Append("}"); 
                        } else { 
                            JsonString.Append("},"); 
                        } 
                    } 
                    JsonString.Append("]"); 
                    JsonString.Append("}"); 
                    return JsonString.ToString(); 
                } else { 
                    return null; 
                } 
            } 
            [WebMethod] 
            [ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
        public Gender[] GenderWise() { 
            connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password"; 
            sql = "select distinct(empid) as employeeid, count(case when gender='M' then 1 end) as Male, count(case when gender='F' then 1 end) as Female from V_CountOnGender"; 
            sqlCnn = new SqlConnection(connetionString); 
            try { 
                sqlCnn.Open(); 
                sqlCmd = new SqlCommand(sql, sqlCnn); 
                adapter.SelectCommand = sqlCmd; 
                adapter.Fill(dsbind); 
                JavaScriptSerializer obj = new JavaScriptSerializer(); 
                string result = string.Empty; 
                Gender[] arrlst = new Gender[dsbind.Tables[0].Rows.Count]; 
                if (dsbind.Tables[0].Rows.Count > 0) { 
                    for (int i = 0; i < dsbind.Tables[0].Rows.Count; i++) { 
                        Gender objgender = new Gender(); 
                        objgender.employeeid = dsbind.Tables[0].Rows[i]["employeeid"].ToString(); 
                        objgender.male = dsbind.Tables[0].Rows[i]["Male"].ToString(); 
                        objgender.female = dsbind.Tables[0].Rows[i]["Female"].ToString(); 
                        arrlst.SetValue(objgender, i); 
                    } 
                } else { 
                    result = "No Record Found"; 
                } 
            } catch (Exception ex) {} 
            return arrlst;; 
        } 
    } 














This will go into the < head > section of the page:  
 
    <script type = "text/javascript" src = "script/jquery-1.2.6.min.js" > < /script>
    <script type = "text/javascript" > 
    $(document).ready(function() { 
        $.ajax({ 
            type: "POST", 
            contentType: "application/json; charset=utf-8", 
            dataType: "json", 
            url: "/WebMyVoterService.asmx/GenderWise", 
            processData: false, 
            success: OnSuccess, 
            failure: function(response) { 
                alert("Can't be able to bind graph"); 
            }, 
            error: function(response) { 
                alert("Can't be able to bind graph"); 
            } 
        }); 
 
        function OnSuccess(response) { 
            var dpmale = []; 
            var dpfemale = []; 
            for (var i = 0; i < response.d.length; i++) { 
                var obj = response.d[i]; 
                var datamale = { 
                    y: parseInt(obj.male), 
                    label: obj.employeeid, 
                }; 
                var datafemale = { 
                    y: parseInt(obj.female), 
                    label: obj.employeeid, 
                }; 
                dpmale.push(datamale); 
                dpfemale.push(datafemale); 
            } 
            var chart = new CanvasJS.Chart("chartContainerbar", { 
                animationEnabled: true, 
                axisX: { 
                    interval: 1, 
                    labelFontSize: 10, 
                    lineThickness: 0, 
                }, 
                axisY2: { 
                    valueFormatString: "0", 
                    lineThickness: 0, 
                    labelFontSize: 10, 
                }, 
                toolTip: { 
                    shared: true 
                }, 
                legend: { 
                    verticalAlign: "top", 
                    horizontalAlign: "center", 
                    fontSize: 10, 
                }, 
                data: [{ 
                    type: "stackedBar", 
                    showInLegend: true, 
                    name: "Male", 
                    axisYType: "secondary", 
                    color: "#f8d347", 
                    dataPoints: dpmale 
                }, { 
                    type: "stackedBar", 
                    showInLegend: true, 
                    name: "Female", 
                    axisYType: "secondary", 
                    color: "#6ccac9", 
                    dataPoints: dpfemale 
                }] 
            }); 
            chart.render(); 
        } 
    });
<  /script> 

Tuesday, 23 August 2016



Convert HTML Tables to DataSet in C#

 

private DataSet ConvertHTMLTablesToDataSet(string HTML)
{
// Declarations
DataSet ds = new DataSet();
DataTable dt = null;
DataRow dr = null;
DataColumn dc = null;
string TableExpression = "<TABLE[^>]*>(.*?)</TABLE>";
string HeaderExpression = "<TH[^>]*>(.*?)</TH>";
string RowExpression = "<TR[^>]*>(.*?)</TR>";
string ColumnExpression = "<TD[^>]*>(.*?)</TD>";
bool HeadersExist = false;
int iCurrentColumn = 0;
int iCurrentRow = 0;
// Get a match for all the tables in the HTML
MatchCollection Tables = Regex.Matches(HTML, TableExpression, RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.IgnoreCase);
// Loop through each table element
foreach (Match Table in Tables)
{
// Reset the current row counter and the header flag
iCurrentRow = 0;
HeadersExist = false;
// Add a new table to the DataSet
dt = new DataTable();
//Create the relevant amount of columns for this table (use the headers if they exist, otherwise use default names)
// if (Table.Value.Contains("<th"))
if (Table.Value.Contains("<TH"))
{
// Set the HeadersExist flag
HeadersExist = true;
// Get a match for all the rows in the table
MatchCollection Headers = Regex.Matches(Table.Value, HeaderExpression, RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.IgnoreCase);
// Loop through each header element
foreach (Match Header in Headers)
{
dt.Columns.Add(Header.Groups[1].ToString());
}
}
else
{
for (int iColumns = 1; iColumns <= Regex.Matches(Regex.Matches(Regex.Matches(Table.Value, TableExpression, RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.IgnoreCase)[0].ToString(), RowExpression, RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.IgnoreCase)[0].ToString(), ColumnExpression, RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.IgnoreCase).Count; iColumns++)
{
dt.Columns.Add("Column " + iColumns);
}
}
//Get a match for all the rows in the table
MatchCollection Rows = Regex.Matches(Table.Value, RowExpression, RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.IgnoreCase);
// Loop through each row element
foreach (Match Row in Rows)
{
// Only loop through the row if it isn't a header row
if (!(iCurrentRow == 0 && HeadersExist))
{
// Create a new row and reset the current column counter
dr = dt.NewRow();
iCurrentColumn = 0;
// Get a match for all the columns in the row
MatchCollection Columns = Regex.Matches(Row.Value, ColumnExpression, RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.IgnoreCase);
// Loop through each column element
foreach (Match Column in Columns)
{
// Add the value to the DataRow
dr[iCurrentColumn] = Column.Groups[1].ToString();
// Increase the current column
iCurrentColumn++;
}
// Add the DataRow to the DataTable
dt.Rows.Add(dr);
}
// Increase the current row counter
iCurrentRow++;
}
// Add the DataTable to the DataSet
ds.Tables.Add(dt);
}
return ds;
}
 
 

The 5 mistakes in the web.config in Asp.Net

 
 
 
 
1. Custom Errors Disabled
 
Vulnerable configuration:
<configuration>
<system.web>
<customErrors mode="Off">
Secure configuration:
<configuration>
<system.web>
<customErrors mode="RemoteOnly">
 
 
2. Leaving Tracing Enabled in Web-Based Applications
 
Vulnerable configuration:
<configuration>
<system.web>
<trace enabled="true" localOnly="false">
Secure configuration:
<configuration>
<system.web>
<trace enabled="false" localOnly="true">
 
 
3. Debugging Enabled
 
Vulnerable configuration:
<configuration>
<system.web>
<compilation debug="true">
Secure configuration:
<configuration>
<system.web>
<compilation debug="false">
 
 
4. Cookies Accessible through Client-Side Script
 
Vulnerable configuration:
<configuration>
<system.web>
<httpCookies httpOnlyCookies="false">
Secure configuration:
<configuration>
<system.web>
<httpCookies httpOnlyCookies="true">
 
 
5. Cookieless Session State Enabled
 
Vulnerable configuration:
<configuration>
<system.web>
<sessionState cookieless="UseUri">
Secure configuration:
<configuration>
<system.web>
<sessionState cookieless="UseCookies">

Monday, 22 August 2016

Friday, 19 August 2016

 

Basic of LINQ

 

The acronym LINQ is for Language Integrated Query. Microsoft’s query language is fully integrated and offers easy data access from in-memory objects, databases, XML documents and many more. It is through a set of extensions, LINQ ably integrate queries in C# and Visual Basic.

 

Basic Example of LINQ 
 
using System;
using System.Linq;
class Program
{
static void Main()
{
string[] words = {"hello", "wonderful", "LINQ", "beautiful", "world"};
var shortWords = from word in words
where word.Length <= 5
select word;
foreach (var word in shortWords)
{
Console.WriteLine(word);
}
Console.ReadLine();
}
}
 
Output :
hello
LINQ
world
 
The types of LINQ :-
LINQ to Objects
LINQ to XML(XLINQ)
LINQ to DataSet
LINQ to SQL (DLINQ)
LINQ to Entities
 
 
 
 
 
 
 
 
 
 
 
 
LINQ to SQL Example
 
using System;
using System.Linq;
namespace LINQtoSQL
{
class LinqToSQLCRUD
{
static void Main(string[] args)
{
string connectString = System.Configuration.ConfigurationManager.ConnectionStrings ["LinqToSQLDBConnectionString"].ToString();
LinqToSQLDataContext db = new LinqToSQLDataContext(connectString);
//Create new Employee
Employee newEmployee = new Employee();
newEmployee.Name = "ABC";
newEmployee.Email = "abc@xyz.com";
newEmployee.ContactNo = "1234567890";
newEmployee.DepartmentId = 3;
newEmployee.Address = "India";
//Add new Employee to database
db.Employees.InsertOnSubmit(newEmployee);
//Save changes to Database.
db.SubmitChanges();
//Get new Inserted Employee
Employee insertedEmployee = db.Employees.FirstOrDefault(e =>e.Name.Equals("Michael"));
Console.WriteLine("Employee Id = {0} , Name = {1}, Email = {2}, ContactNo = {3}, Address = {4}",
insertedEmployee.EmployeeId, insertedEmployee.Name, insertedEmployee.Email,
insertedEmployee.ContactNo, insertedEmployee.Address);
Console.WriteLine("\nPress any key to continue.");
Console.ReadKey();
}
}
}
using System;
using System.Linq;
namespace LINQtoSQL
{
class LinqToSQLCRUD
{
static void Main(string[] args)
{
string connectString = System.Configuration.ConfigurationManager.ConnectionStrings["LinqToSQLDBConnectionString"].ToString();
LinqToSQLDataContext db = new LinqToSQLDataContext(connectString);
//Get Employee for update
Employee employee = db.Employees.FirstOrDefault(e =>e.Name.Equals("Michael"));
newEmployee.Name = "ABC";
newEmployee.Email = "abc@xyz.com";
newEmployee.ContactNo = "9954567890";
newEmployee.DepartmentId = 3;
newEmployee.Address = "India-Delhi";
//Save changes to Database.
db.SubmitChanges();
//Get Updated Employee
Employee updatedEmployee = db.Employees.FirstOrDefault(e =>e.Name.Equals("George Michael"));
Console.WriteLine("Employee Id = {0} , Name = {1}, Email = {2}, ContactNo = {3}, Address = {4}",
updatedEmployee.EmployeeId, updatedEmployee.Name, updatedEmployee.Email,
updatedEmployee.ContactNo, updatedEmployee.Address);
Console.WriteLine("\nPress any key to continue.");
Console.ReadKey();
}
}
}
using System;
using System.Linq;
namespace LINQtoSQL
{
class LinqToSQLCRUD
{
static void Main(string[] args)
{
string connectString = System.Configuration.ConfigurationManager.ConnectionStrings["LinqToSQLDBConnectionString"].ToString();
LinqToSQLDataContext db = newLinqToSQLDataContext(connectString);
//Get Employee to Delete
Employee deleteEmployee = db.Employees.FirstOrDefault(e =>e.Name.Equals("ABC"));
//Delete Employee
db.Employees.DeleteOnSubmit(deleteEmployee);
//Save changes to Database.
db.SubmitChanges();
//Get All Employee from Database
var employeeList = db.Employees;
foreach (Employee employee in employeeList)
{
Console.WriteLine("Employee Id = {0} , Name = {1}, Email = {2}, ContactNo = {3}",
employee.EmployeeId, employee.Name, employee.Email, employee.ContactNo);
}
Console.WriteLine("\nPress any key to continue.");
Console.ReadKey();
}
}
}
 
 
 
 
 
 
 
 
 
 
 
LINQ to Object Example
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LINQtoObjects
{
class Program
{
static void Main(string[] args)
{
string[] tools = { "A", "B", "C", "D", "E","F" };
var list = from t in tools
select t;
StringBuilder sb = new StringBuilder();
foreach (string s in list)
{
sb.Append(s + Environment.NewLine);
}
Console.WriteLine(sb.ToString(), "Tools");
Console.ReadLine();
}
}
}
 
 
 
 
 
 
 
 
 
 
LINQ to XML Example
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
namespace LINQtoXML
{
class ExampleOfXML
{
static void Main(string[] args)
{
string myXML = @"<Departments>
<Department>Account</Department>
<Department>IT</Department>
<Department>Sales</Department>
<Department>Marketing</Department>
</Departments>";
XDocument xdoc = new XDocument();
xdoc = XDocument.Parse(myXML);
var result = xdoc.Element("Departments").Descendants();
foreach (XElement item in result)
{
Console.WriteLine("Department Name - " + item.Value);
}
Console.WriteLine("\nPress any key to continue.");
Console.ReadKey();
}
}
}