Friday, July 29, 2011

Same static menu simple with setTimeout

Баруун зүүн талд тогтмол байдаг меню хэрхэн хийх вэ?

STATICMENU = getElementById("myDivId");


function InitializeStaticMenu()
STATICMENU.style.top = document.body.scrollTop + stmnBASE;

How to extend jquery functions by my method

jQuery class өмнө нь jquery.min.js ээс үүсчихсэн ба түүний функцууд дээр өөрийнхөө функцийг нэмэхдээ доорх маягаар хийнэ

jQuery.fn.myJqueryMethod = function (options, callbackFunc) {
        methodOpt = jQuery.extend ({
           timeout: 5000,
           myOptions: 'default'
        }, options);
       
        $(this).empty();
        selected = this;
        setHtml = methodOpt.myOptions;
        $(selected).append(setHtml);
        if(typeof callbackFunc == 'function'){
                    callbackFunc.call(this);
                }

        function MyLocalUtilMethod(data) {
                        return "hi, " + data;
        }
}

Ингээд ажиллуулахдаа:
 $("#myElementId").myJqueryMethod({myOptions: 'my html text'}, function(th) { alert(th); });
нэг иймэрхүү код бичнэ

ASP.NET MVC 3 Razor html render partial, page, action, load page using ajax

@*controller is not working, path is required *@
@*RenderPage("~/Views/Home/Simple.cshtml") *@

@*controller is not working, path load from ~/Views/Shared/_LogOnPartial.cshtml *@
@*{ Html.RenderPartial("_LogOnPartial"); }*@

@*controller is working, path load from ~/Views/{controller}/{action}.cshtml *@
@*{ Html.RenderAction("Simple", "Home"); }*@
@*Html.Action("Simple", "Home")*@

Simple.cshtml is

if Layout == null then only write a html in simple.cshtml
else load layout.cshtml with simple.cshtml

Хар ухаанаар зөвхөн simple.cshtml доторхи html ийг ( магадгүй нэр хуудас дотор хэд хэдэн асtion ажиллуулах гэж байгаа бол ийм шаардлага гарна )
@{        Layout = null;       }
болгох хэрэгтэй. тэгэхгүй бол ( Layout = null; ийм код байхгүй л бол ) бүх хуудас дуудагдаж давхар давхар тагууд харагдана гэсэн үг.
Хэрэв AJAX аар тухайн хуудлыг дангаар нь дуудах гэж байгаа бол заавал Layout = null; гэх албагүй хоосон орхиход л болно

Жишээ нь: Ajax ашиглан List.cshtml г дуудах бол нэг иймэрхүү код байж болно


~/Views/Admin/_MainLayout.cshtml байна

~/Views/Admin/Menu/Index.cshtml

@{
    this.setLayout("_MainLayout", true);
    ViewBag.Title = "Цэс бүртгэх";
    var listUrl = WebSites.Current.FullName + "/Admin/Part/Menu/List/";
    var editUrl = WebSites.Current.FullName + "/Admin/Part/Menu/Edit/";
    var deleteUrl = WebSites.Current.FullName + "/Admin/Part/Menu/Delete/";
    var editing = WebUtil.checkUrlIsSession(editUrl);
}
@section Commands {
    <ul class="command-tabs">
        <li class="tab active_tab"><a href="javascript:void(0)" onclick="listMenu();"><span>
            Жагсаалт</span></a></li>
        <li class="tab"><a href="javascript:void(0)" onclick="createMenu();"><span>Шинэ</span></a></li>
    </ul>
}
@section Types {
    @{
        var menuTypes = Util.enumToList(typeof(MenuTypeEnum));
        <text><span>Цэсний төрөл: </span><select onchange="listMenu();" id="MenuTypeCode" class="select">
            @foreach(var mt in menuTypes) {
                <option value="@mt.Value">@mt.Text</option>
            }
        </select>
        </text>   
    }
}
<script type="text/javascript">
    function listMenu() {
        $("#content").ajaxGet("@listUrl?MenuTypeCode=" + $("#MenuTypeCode").val());
        return false;
    }
    function createMenu() {
        $("#content").ajaxGet("@editUrl");
        return false;
    }
    function changeClass(sel) {
        $("ul.command-tabs > li > a").parent().removeClass("active_tab");
        $(sel).parent().addClass("active_tab");
    }
    $(function () {
        var editing = "@editing".toLowerCase();
        var alla = $("ul.command-tabs > li > a");
        $(alla).click(function (event) {
            changeClass(event.currentTarget);
        });
        if (editing == "true") {
            changeClass($("ul.command-tabs > li > a[onclick*='createMenu()']"));
            createMenu();
        } else
            $("#MenuTypeCode").change();
    });
</script>


~/Views/Admin/Menu/List.cshtml

@model IEnumerable<MenuInfo>
@{
    Layout = null;
}
<table id="grid" class="tablesorter">
    <thead>
        <tr>
            <th>
                Дээд цэс
            </th>
            <th>
                Нэр
            </th>
            <th>
                Хэсгийн нэр
            </th>
            <th>
                Цэсний төрөл
            </th>
            <th>
                Тайлбар
            </th>
            <th>
                Холбоос
            </th>
            <th>
                Дугаарлалт
            </th>
            <th>
                Идэвхитэй?
            </th>
            <th>
                Хэрэглэгч
            </th>
            <th colspan="2">
                Комманд
            </th>
        </tr>
    </thead>
    <tbody>
        @if (Model != null)
        {
            foreach (var item in Model)
            {
            <tr>
                <td>
                    @item.ParentMenu.Name
                </td>
                <td>
                    @item.Name
                </td>
                <td>
                    @item.Category.Name
                </td>
                <td>
                    @item.MenuTypeCode.ToText(typeof(MenuTypeEnum))
                </td>
                <td>
                    @item.Descr
                </td>
                <td>
                    @item.LinkText
                </td>
                <td>
                    @item.Ordering
                </td>
                <td>
                    @item.IsActive.ToText()
                </td>
                <td>
                    @item.ModifiedName
                </td>
                <td>
                    <a class="img-item-delete" href="#">
                        <img alt="" src="@Url.Content("~/Content/admin/images/delete-32.png")" height="32" width="32"/></a>
                </td>
                <td>
                    <a class="img-item-edit" href="#">
                        <img alt="" src="@Url.Content("~/Content/admin/images/edit-32.png")" height="32" width="32"/></a>
                </td>
            </tr>
            }
        }
    </tbody>
</table>
<div id="pager" class="pager"></div>
<script type="text/javascript">
    $(function () {
        $("#grid")
        .tablesorter({ widthFixed: true, widgets: ['zebra'] })
        .tablesorterPager({ container: $("#pager") });
    });
</script>

ASP.NET 2 caching, MVC3 OutputCache with Razor

ASP.NET 2.0
 
Web caching technology in ASP.NET and C# is helpful 
for popular website reducing its server workload and improving access 
times. This tutorial will show you how to use web caching save data to 
RAM, and improve data access times therefore.
First, import the namespace of System.Web.Caching
using System.Web.Caching
Try Server Intellect for Windows Server Hosting. Quality and Quantity!
Declare the variables
static bool itemRemoved = false;
static CacheItemRemovedReason reason;
CacheItemRemovedCallback onRemove = null;
We used over 10 web hosting companies before we found Server Intellect. Their dedicated servers and add-ons were setup swiftly, in less than 24 hours. We were able to confirm our order over the phone. They respond to our inquiries within an hour. Server Intellect's customer support and assistance are the best we've ever experienced.
Define the method of AddItemToCache, it will use Cache.Add to add items to cache

public void AddItemToCache(Object sender, EventArgs e)
{
itemRemoved = false;

onRemove = new CacheItemRemovedCallback(this.RemovedCallback);

if (Cache["Key1"] == null)
Cache.Add("Key1", "Caching", null, DateTime.Now.AddSeconds(60), TimeSpan.Zero, CacheItemPriority.High, onRemove);
}

Define the method of RemoveItemFromCache, it will use Cache.Remove to remove items from cache

public void RemoveItemFromCache(Object sender, EventArgs e)
{
if (Cache["Key1"] != null)
Cache.Remove("Key1");
}
If you're ever in the market for some great Windows web hosting, try Server Intellect. We have been very pleased with their services and most importantly, technical support.
When using the method of Cache.Remove , it will be leaded to invoke RemovedCallback method

public void RemovedCallback(String k, Object v, CacheItemRemovedReason r)
{
itemRemoved = true;
reason = r;
}
If you're looking for a really good web host, try Server Intellect - we found the setup procedure and control panel, very easy to adapt to and their IT team is awesome!
Page_Load

protected void Page_Load(object sender, EventArgs e)
{
if (itemRemoved)
{
Response.Write("RemovedCallback event raised.");
Response.Write("<BR>");
Response.Write("Reason: <B>" + reason.ToString() + "</B>");
}
else
{
Response.Write("Value of cache key: <B>" + Server.HtmlEncode(Cache["Key1"] as string) + "</B>");
}
}
We chose Server Intellect for its dedicated servers, for our web hosting. They have managed to handle virtually everything for us, from start to finish. And their customer service is stellar.
The HTML of the web page

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>

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

<html>

<body>
<Form id="Form1" runat="server">
<input id="Submit1" type=submit OnServerClick="AddItemToCache" value="Add Item To Cache" runat="server"/>
<input id="Submit2" type=submit OnServerClick="RemoveItemFromCache" value="Remove Item From Cache" runat="server"/>
</Form>

</body>
</html>
 
 
ASP.NET 4.0 RAZOR
 
@{
    var cacheItemKey = "Time";
    var cacheHit = true;
    var time = WebCache.Get(cacheItemKey);

    if (time == null) {
        cacheHit = false;
    }

    if (cacheHit == false) {
        time = @DateTime.Now;
        WebCache.Set(cacheItemKey, time, 1, false);
    }
}<!DOCTYPE html>
<html>
<head>
    <title>WebCache Helper Sample</title>
</head>
<body>
    <div>
        @if (cacheHit) {
            @:Found the time data in the cache.
        } else {
            @:Did not find the time data in the cache.
        }
    </div>
    <div>
        This page was cached at @time.
    </div>
</body>
</html>
 
OR
 
[OutputCache(Duration=10, VaryByParam="none")]
public ActionResult Index()
{
    return View();
}
 
OR 

public ActionResult Index()
{
    WebCache.Set(key, data, minutesToCache, false);
    return View();
}
 
 
OR
Гараар бичсэн Cache чадвартай объектын жишээ

public abstract class DataLoader
    {
        private static readonly Hashtable _buffer = new Hashtable();
        private static readonly Hashtable _cached = new Hashtable();
       
        // Data Buffer
        protected void setBuffer(dynamic data)
        {
            setBuffer(this.GetType().FullName, data);
        }

        private void setBuffer(string type, dynamic data)
        {
            Hashtable hash = null;
            if (_buffer.ContainsKey(type))
                hash = (Hashtable)_buffer[type];
            else
            {
                hash = new Hashtable();
                _buffer.Add(type, hash);
            }
            if (hash.ContainsKey(WebSites.Current.Name))
                hash[WebSites.Current.Name] = data;
            else
                hash.Add(WebSites.Current.Name, data);
        }

        protected dynamic getBuffer()
        {
            return getBuffer(this.GetType().FullName);
        }

        private dynamic getBuffer(string type)
        {
            Hashtable hash = null;
            if (_buffer.ContainsKey(type))
                hash = (Hashtable)_buffer[type];
            else
            {
                hash = new Hashtable();
                _buffer.Add(type, hash);
            }
            if (hash.ContainsKey(WebSites.Current.Name))
                return hash[WebSites.Current.Name];
            else
                return null;
        }

        public object Ready(int cacheSecond, params object[] args)
        {
            dynamic data = getCache();
            if (data == null)
            {
                data = Load();
                setCache(cacheSecond, data);
            }
            return data;
        }

        protected abstract dynamic Load();

        protected void setCache(int cacheSecond, dynamic data)
        {
            string type = GetType().FullName;
            Hashtable hash = null;

            if (_cached.ContainsKey(type))
                hash = (Hashtable)_cached[type];
            else
            {
                hash = new Hashtable();
                _cached.Add(type, hash);
            }
           
            DataCacheModel model = new DataCacheModel();
            model.set(cacheSecond, data);
           
            if (hash.ContainsKey(WebSites.Current.Name))
                hash[WebSites.Current.Name] = model;
            else
                hash.Add(WebSites.Current.Name, model);
        }

        protected dynamic getCache()
        {
            string type = GetType().FullName;
            Hashtable hash = null;

            if (_cached.ContainsKey(type))
                hash = (Hashtable)_cached[type];
            else
            {
                hash = new Hashtable();
                _cached.Add(type, hash);
            }
            if (hash.ContainsKey(WebSites.Current.Name))
                return ((DataCacheModel)hash[WebSites.Current.Name]).get();
            else
                return null;
        }
    }

Wednesday, July 20, 2011

Selected TD of TR of TABLE class style change

Horizontal

<!DOCTYPE HTML>
<html>
<head>
<script src="jquery-1.4.2.min.js"></script>
<style>
.btn { background-color:red; }
</style>
</head>
<body>
<script type="text/javascript">
$(function(){
    var $firstClicked = false;
    var $trs = $("#table1 tr");
    $trs.each(function(indx,tr){
        var $tr_childs = $(tr).children();
        $tr_childs.click(function(){
                //$(this) is current td
                $td_indx = $(this).index();
                if(!$firstClicked){
                    $firstClicked = true;
                } else {
                    $firstClicked = false;
                    $tr_childs.filter(function(ii){
                        return $first_td_indx <= ii && ii <= $td_indx;
                    }).addClass("btn");
                }
                $first_td_indx = $td_indx;
        });
    });   
});
</script>
<table border="1" id="table1">
<tbody>
<tr>
    <td><input type="button" value="1"></td>
    <td><input type="button" value="2"></td>
    <td><input type="button" value="3"></td>
</tr>
<tr>
    <td><input type="button" value="1"></td>
    <td><input type="button" value="2"></td>
    <td><input type="button" value="3"></td>
</tr>
</tbody>
</table>
</body>
</html>

 Vertical

<!DOCTYPE HTML>
<html>
<head>
<script src="jquery-1.4.2.min.js"></script>
<style>
.btn { background-color:red; }
</style>
</head>
<body>
<script type="text/javascript">
$(function(){
    var $firstClicked = false;
    var $trs = $("#table1 tr");
    var $tds = $("#table1 tr td");
    $tds.click(function(){
        //$(this) is current td
        $tr_indx = $(this).parent().index();
        $td_indx = $(this).index();
        if(!$firstClicked){
            $firstClicked = true;
        } else {
            $firstClicked = false;
            $trs.filter(function(ii){
                return $first_tr_indx <= ii && ii <= $tr_indx;
            }).find("td:eq(" + $first_td_indx + ")").addClass("btn");
        }
        $first_td_indx = $td_indx;
        $first_tr_indx = $tr_indx;
    });   
});
</script>
<table border="1" id="table1">
<tbody>
<tr>
    <td><input type="button" value="1"></td>
    <td><input type="button" value="2"></td>
    <td><input type="button" value="3"></td>
</tr>
<tr>
    <td><input type="button" value="1"></td>
    <td><input type="button" value="2"></td>
    <td><input type="button" value="3"></td>
</tr>
</tbody>
</table>
</body>
</html>

Saturday, July 16, 2011

ASP.NET MVC 3 @Facebook.LoginButton simple

Эхлээд ~/Views/Web.config доторхи кодыг ийм болгож өөрчилнө. Ингэж байж ASP.NET MVC 3 Razor syntax @Facebook бичиглэлийг танина. Үгүй бол @Microsoft.Web.Helpers.Facebook гэж бичсэн ч болно.

<system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
      <namespaces>
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
        <add namespace="Microsoft.Web.Helpers"/>
      </namespaces>
    </pages>
  </system.web.webPages.razor>

Index.csHtml код дотор нэг иймэрхүү код бичвэл шууд Login With Facebook харагдана

@model WebApplication1.Controllers.MyModel
@{
    ViewBag.Title = "Home Page";

    var userData = "hi, it's simple text file" + Environment.NewLine;

    var dataFile = Server.MapPath("~/App_Data/data.txt");
    File.WriteAllText(@dataFile, userData);
    var result = "Information saved.";

    Bing.SiteUrl = "http://pl-developer.blogspot.com/";
    Bing.SiteTitle = "pl-developer.blogspot.com";
}

@section header0 {
    <div id="title">
        <h1>My MVC Application @ViewBag.Time | @Model.name</h1>
    </div>
    <div id="logindisplay">
        @Html.Partial("_LogOnPartial")
    </div>
    <nav>
        <ul id="menu">
            <li>@Html.ActionLink("Home", "Index", "Home")</li>
            <li>@Html.ActionLink("About", "About", "Home")</li>
        </ul>
    </nav>
}

<h2>@ViewBag.Message</h2>
<p>
    To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">http://asp.net/mvc</a>.
    @{
        if (Helpers.isFacebookAuthenticated()) {
            <text>Welcome, @Facebook.GetFacebookUserProfile().Name</text>
        }
        string baseUrl = Context.Request.Url.GetLeftPart(UriPartial.Authority);
    }
</p>

@section same {
    <text><b>boroo, @WarningHelpers.Warning(result)</b></text>
}

<div>
    <hr />  
    @Facebook.GetInitializationScripts()
    @Facebook.LoginButtonTagOnly("", true, "long", "short", "loginRedirect('" + @baseUrl + "')", false, "email")
    <hr />
</div>


Helpers.cshtml in App_Code folder

@functions {
public static bool isFacebookAuthenticated()
    {
        Facebook.AppId = "169933786406617";
        Facebook.AppSecret = "2eb9f7461338f1e3c0d03292416c2b41";
        HttpCookieCollection cookies = HttpContext.Current.Request.Cookies;
        var cookieName = "fbs_" + Facebook.AppId;
        if (cookies[cookieName] == null) return false;
       
        try {
            if (Facebook.IsFacebookUserAuthenticated)
            {
                Facebook.UserProfile profile = Facebook.GetFacebookUserProfile();
                profile.Name.ToString();
                return true;
            }
            else return false;
        } catch {
            cookies[cookieName].Values.Clear();
            return false;
        }
    }
}

Thursday, July 14, 2011

html 5 simples

<!DOCTYPE html>
<html>
<head>
</head>
<body>
asd
<article style="width:600px;" contenteditable="false" dir="auto">
    <aside>
    <h4>Epcot Center</h4>
    The Epcot Center is a theme park in Disney World, Florida.
    </aside>
    <a href="http://blog.netscape.com/2007/12/28/end-of-support-for-netscape-web-browsers"
    hidden0="hidden" id="atag">
    Netscape is dead</a><br />
    AOL has a long history on the internet, being one of
    the first companies to really get people online.....
    <div draggable="true" style="cursor: move;">my div tag</div>
</article>

<hr />

<input list="cars" />
<datalist id="cars">
    <option value="BMW">
    <option value="Ford">
    <option value="Volvo">
</datalist>

<hr />

<p spellcheck="true">spell checking</p>

<hr />

<audio style="margin-top:70px;" controls="controls" tabindex="0">
  <source type="audio/ogg" src="http://www.w3schools.com/html5/song.ogg"></source>
Your browser does not support the audio element.
</audio>

<hr />

<canvas id="myCanvas"></canvas>
<script type="text/javascript">
var canvas=document.getElementById('myCanvas');
var ctx=canvas.getContext('2d');
ctx.fillStyle='#FF0000';
ctx.fillRect(0,0,80,100);
</script>

<hr />

<script type="text/javascript">               
var dragItems = document.querySelectorAll('[draggable=true]')
//alert(dragItems.length);
</script>

<hr />

<audio id="multiaudio1" src="http://www.w3schools.com/html5/song.ogg" preload="auto"></audio>
<a href="javascript:play_multi_sound('multiaudio1');">play music</a><br />
<script type="text/javascript">
    function play_multi_sound(s) {
        document.getElementById(s).play();
    }
</script>

<hr />

<embed src="http://www.youtube.com/v/N8gvHaX1cwY?version=3" />
<embed src="file:///Temp/asdfasdf.xls" type="application/vnd.ms-excel" height="600" width="800"/>

<hr />

<figure>
  <figcaption style="color:red">A view of the pulpit rock in Norway</figcaption>
  <img src="http://www.w3schools.com/html5/img_pulpit.jpg" width="304" height="228" />
</figure>

<hgroup>
<h1>Welcome to my WWF</h1>
<h2>For a living planet</h2>
</hgroup>

<p>Do not forget to buy <mark>milk</mark> today.</p>

<hr />

<video width="320" height="240" controls="controls">
  <source src="http://www.w3schools.com/html5/movie.ogg" type="video/ogg" />
  Your browser does not support the video tag.
</video>



</body>
</html>

Thursday, July 7, 2011

Sizeof programming language type



CSharp C#

ExpressionConstant value
sizeof(sbyte) 1
sizeof(byte) 1
sizeof(short) 2
sizeof(ushort) 2
sizeof(int) 4
sizeof(uint) 4
sizeof(long) 8
sizeof(ulong) 8
sizeof(char) 2 (Unicode)
sizeof(float) 4
sizeof(double) 8
sizeof(decimal) 16
sizeof(bool) 1

JAVA


Primitive Type
Size
Minimum Value
Maximum Value
char
  16-bit  
  Unicode 0
  Unicode 216-1
byte
  8-bit  
  -128
  +127
short
  16-bit  
  -215
(-32,768)
  +215-1
(32,767)
int
  32-bit  
  -231
(-2,147,483,648)
  +231-1
(2,147,483,647)
long
  64-bit  
  -263
(-9,223,372,036,854,775,808)
  +263-1
(9,223,372,036,854,775,807)
float
  32-bit  
  32-bit IEEE 754 floating-point numbers
double
  64-bit  
  64-bit IEEE 754 floating-point numbers
boolean
  1-bit  
  true or false
void
  -----  
  -----  
  -----  

other type reference
http://www.techonthenet.com/