23 Kasım 2012 Cuma

mvc de $.ajax() ile multi delete


function f_MultiDelete()
{
if ($(".chList").size() > 0) {
            var IDS = [];

            $(".chList").each(function (i) {
                if ($(this).attr('checked') == "checked" && $(this).attr('name') == "checkDelete") {
                    var ID = $(this).attr("vl");
                    IDS.push(ID);
                }
            });
            if (IDS.length > 0) {
                $.ajax({
                    type: "POST",url: Path,

                    traditional:true,
                    dataType:"json",
                    data: { 'IDList': IDS },
                    success: function (data) {
                        alert(data);
                    }
                });
            }
        }
}

<input name="checkDelete" class="chList" vl="4" type="checkbox" />
<input name="checkDelete" class="chList" vl="3" type="checkbox" />
<input name="checkDelete" class="chList" vl="2" type="checkbox" />
<input name="checkDelete" class="chList" vl="5" type="checkbox" />

<div onclick="f_MultiDelete('/Admin/AGaleri/MultiDelete/')" class="btn btn-primary">Seçilileri Sil </div>




public ActionResult MultiDelete(IEnumerable<string> IDList)
{
    //IDList parametresinden seçili ID lere ulaşabilirsiniz.
}

24 Ekim 2012 Çarşamba

asp.nette web servis kullanımı

Şimdilik .net 3.5 ta web servisi oluşturabiliyoruz. .net4.0 henüz desteklemiyor

    public class Service1 : System.Web.Services.WebService
    {
        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }


        [WebMethod]
        public bool firstService(string name,string lastName)
        {
            // yazmak istediğimiz kodlar           
        }

        // webmethod fonksiyonlarımız istediğimiz kadar çoğaltabiliriz.
    }



Web servisini projemize 'tryWebService' adında ekliyoruz
            
        var service1 = new tryWebService.Service1SoapClient();
        service1.firstService("parametre1", "parametre2");

 // yazdığımız tüm methodlara service1 örneğinden ulaşabiliriz.

28 Eylül 2012 Cuma

asp.net te windows service kullanımı

[ServiceContract]
    public interface IService1
    {
        [OperationContract]
        string GetData(int value);

        [OperationContract]
        CompositeType GetDataUsingDataContract(CompositeType composite);

        [OperationContract]
        string GetUserInfo(int ID);

        [OperationContract()]
        IEnumerable<User> GetUserList();
    }

    [DataContract]
    public class CompositeType
    {
        bool boolValue = true;
        string stringValue = "Hello ";

        [DataMember]
        public bool BoolValue
        {
            get { return boolValue; }
            set { boolValue = value; }
        }

        [DataMember]
        public string StringValue
        {
            get { return stringValue; }
            set { stringValue = value; }
        }
    }

    [DataContract]
    public class User
    {
        public int ID { get; set; }
        public string name { get; set; }
        public string password { get; set; }
        public User() { }
        public User(int _ID, string _name, string _password)
        {
            this.ID = _ID;
            this.name = _name;
            this.password = _password;
        }
    }    


//**********************************//
public class Service1 : IService1
    {
        public string GetData(int value)
        {
            return string.Format("You entered: {0}", value);
        }

        public CompositeType GetDataUsingDataContract(CompositeType composite)
        {
            if (composite == null)
            {
                throw new ArgumentNullException("composite");
            }
            if (composite.BoolValue)
            {
                composite.StringValue += "Suffix";
            }
            return composite;
        }

        public string GetUserInfo(int ID)
        {
            string sb = "";
            User us = new User() { ID = 3, name = "hakan", password = "passsssssss" };
            if (us.ID == ID)
            {
                sb = us.ID + " : " + us.name + " : " + us.password;
            }
            return sb;
        }

        public IEnumerable<User> GetUserList()
        {
            NSGenel.Genel.MesajGoster("ok");
            return new List<User>() { new User() { ID = 3, name = "asdfsdf", password = "psdfsf" } };
            //return (List<User>)(us.Add(new User { ID = 3, name = "dfgdfg", password = "passs" }));
            
        }
    }
//******************************//
servisi projemize ekledikten sonra
ServiceReference1.IService1 service = new ServiceReference1.Service1Client();
service örneğiyle yazdığımız metodlara ulaşabiliriz.



11 Eylül 2012 Salı

asp.net mvc de bot yapımı

sayfadaki tüm <a> ve <a> tagı içerisindeki <img> taglarını çekmek için
public ActionResult Index()
        {
            ViewData["datas"] = ss();
            return View();
        }
        List<string> dataList = new List<string>();
        private List<string> ss()
        {
            string Site = "http://shiftdelete.net/";
            WebClient client = new WebClient();
            Stream data = client.OpenRead(Site);
            StreamReader reader = new StreamReader(data, Encoding.GetEncoding("utf-8"));
            string datas = reader.ReadToEnd();

            string pattern3 = "<a.*?href=.*?>(.*?(<img.*?>).*?)</a>";
            MatchCollection mathcollection = System.Text.RegularExpressions.Regex.Matches(datas, pattern3);
            foreach (Match match in mathcollection)
            {
                if (match.Value.ToString().Contains("<img"))
                        dataList.Add(match.Value);
            }
            return dataList;
        }



//******************************************//
index sayfamız

<h2>Index</h2>
@{
    List<string> datas = (List<string>)ViewData["datas"];
    foreach(string s in datas.ToList())
    {
        <hr />
        <label>@s.ToString()</label>
    }
    }


9 Eylül 2012 Pazar

asp.net mvc de jQuery.ajax ile UserControl Kullanımı

function f_EditCategory(path) {
        $.ajax({
            url: path, type: 'POST',
            success: function (data) {
                $("#divTake").load(data);
            },
            data: { Mode: ID }
        });
        jQuery.facebox();
    } 

<a onclick='f_EditCategory("/AHome/EditCategory/5/"'>Kategori Düzenle </a>
<div id='divTake'></div>

//***************************************//

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult EditCategory(int? p1)
    {
        ViewData["ID"] = p1.HasValue ? p1.Value : 0;
        return PartialView("UserControl1");
    }

//**************************************//

UserControl1 içeriği
<div>
gelen ID @ViewData[ID]
</div>

8 Eylül 2012 Cumartesi

asp.net mvc de jQuery.ajax ile Resim,Dosya(multiupload) Ekleme

http://www.uploadify.com/ ilgili dosyaları indirdikten sonra

<link href="@Url.Content("~/Content/uploadify/uploadify.css")" rel="stylesheet" type="text/css" />

<script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>

<script src="@Url.Content("~/Content/uploadify/jquery.uploadify.min.js")" type="text/javascript"></script>

<script type="text/javascript">


    jQuery(document).ready(function () {

        var inputName = "file";

        jQuery("#" + inputName).uploadify({

            'hideButton': true,
            'wmode': 'transparent',
            'buttonText':'Seçiniz',
            'swf': '@Url.Content("~/Content/uploadify/uploadify.swf")',
            'uploader': '@Url.Action("Upload","Home")',
            'script': '@Url.Action("Upload", "Home")',
            //'script': '/Home/Upload',
            'fileDataName': inputName,
            'sizeLimit': 38000000,
            'cancelImg': '@Url.Content("~/Content/uploadify/cancel.png")',
            'auto': false,
            'debug': false,
            'multi': true,
            'formData': { 'ID': '2', 'KID': '3' },// Extra parametre göndermek isteyenler için..
            "onUploadStart":function (file) { $("#" + inputName).uploadify("settings", "ID", 'KID', 2); },// Extra parametre göndermek isteyenler için..

onError: function () { alert('some error occurred. Sorry'); },

            onComplete: function (event, queueId, fileObj, response, data) { alert(response); }
        });
    });
</script>

<p>
    <form method="post" enctype="multipart/form-data">
        <p>
            <input type="file" name="file" id="file" />
            <a href="javascript:$('#file').uploadify('upload','*')">Upload Files</a>
        </p>
    </form>
</p>


        [HttpPost]

        public JsonResult Upload(int? ID,int? KID)
        {
            foreach (string file1 in Request.Files)
            {
                var postedFileBase = Request.Files[file1];            
                string filename= postedFileBase.FileName;
                postedFileBase.SaveAs(HttpContext.Server.MapPath("/UserFiles/") + filename);

            }

            return Json(true);
        }



UserControl da Event Tanımlama


UserControldaki buttonumuz için click event

     
  public delegate void UserControlbtnClikcHandler(object sender, EventArgs e);
  public event UserControlbtnClikcHandler btnLoginClick;

  private void btnLogin_Click(object sender, EventArgs e)
  {
     if (this.btnLoginClick != null)
         this.btnLoginClick(sender, e);
  }



UserControlu kullandığımız formdan erişmek için

    private void ucLogin1_btnLoginClick(object sender, EventArgs e)
    {
         MessageBox.Show("");

         //usercontroldeki tüm controllere ucLogin1. şeklinde ulaşabiliriz.. 
    }

6 Eylül 2012 Perşembe

base64 encode,read byte

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

        public static string base64Decode(string data)
        {
            try
            {
                System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
                System.Text.Decoder utf8Decode = encoder.GetDecoder();

                byte[] todecode_byte = Convert.FromBase64String(data);
                int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
                char[] decoded_char = new char[charCount];
                utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
                string result = new String(decoded_char);
                return result;
            }
            catch (Exception e)
            {
                throw new Exception("Error in base64Decode" + e.Message);
            }
        }

        //*****************//
        public static byte[] getBytes(string str)
        {
            byte[] bytes = new byte[str.Length * sizeof(char)];
            System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
            return bytes;
        }
        public static string GetString(byte[] bytes)
        {
            char[] chars = new char[bytes.Length / sizeof(char)];
            System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
            return new string(chars);
        }

4 Eylül 2012 Salı

asp.net mvc de döviz kurlarını alma

public ActionResult Index()
        {
            
            XmlTextReader oku = new XmlTextReader("http://www.tcmb.gov.tr/kurlar/today.xml");
            XmlDocument dok = new XmlDocument();
            dok.Load(oku);
            XmlNode xdollar = dok.SelectSingleNode("/Tarih_Date/Currency[CurrencyName='US DOLLAR']");
            XmlNode xeuro = dok.SelectSingleNode("/Tarih_Date/Currency[CurrencyName='EURO']");
            XmlNode xsterling = dok.SelectSingleNode("/Tarih_Date/Currency[CurrencyName='POUND STERLING']");

            double dolar = double.Parse(xdollar.ChildNodes[4].InnerText);
            double euro = double.Parse(xeuro.ChildNodes[4].InnerText);
            double sterling = double.Parse(xsterling.ChildNodes[4].InnerText);
            
            ViewData["dolar"] = dolar;
            ViewData["euro"] = euro;
            ViewData["sterling"] = sterling;
         
             //ya da

            Func<XmlNode, double> fnc = delegate(XmlNode x) {
                  return double.Parse(x.ChildNodes[4].InnerText);
            };
            ViewData["dolar"] = fnc(xdollar);
            ViewData["euro"] = fnc(xeuro);
            ViewData["sterling"] = fnc(xsterling);
         
            return View();
        }

//*************************************//

<h2>Index</h2>

Dolar: @ViewData["dolar"]<hr />
Euro: @ViewData["euro"]<hr />
Sterling: @ViewData["sterling"]

3 Eylül 2012 Pazartesi

asp.net mvc de jQuery ajax ile post işlemi


var path='/Home/Update';
function (path, ID) {
        $.ajax({
                     url: path, type: 'POST',
                     success: function (msg) { alert(msg); },
                     data: { param1: ID} });
    }

//************************//

public JsonResult Update(int? param1)
        {
            //işlemler
            return Json("ok");
        }

1 Eylül 2012 Cumartesi

jQuery sayfalama kodlarım

<div class="pagination" id="divPager"></div>
<div  style=" display:none;">
            <label id="lblTotalRecord">50</label>// taoplam kayıt sayısı
            <label id="lblRecordSize">15 </label>// sayfada kaç adet
            <label id="lblNumSize">10 </label>// numarator sayısı
            <label id="lblCurrentPage">2 </label>// geçerli sayfa
</div>

<script type="text/javascript">  

$(document).ready(function () {
       f_GetPage("/AHome/Hizmet/Sayfa/");
});

function   f_GetPage (path) {
        var TotalRecord, RecordSize, NumSize, CurrentPage;
        TotalRecord = jQuery("#lblTotalRecord").text(); RecordSize = jQuery("#lblRecordSize").text(); NumSize = jQuery("#lblNumSize").text(); CurrentPage = jQuery("#lblCurrentPage").text();
        jQuery("#divPager > ul ").html(f_Page(path, TotalRecord, RecordSize, NumSize, CurrentPage));
    }


function f_Page(Path, TotalRecord, RecordSize, NumSize, CurrentPage) {
    var sb = "0";
    TotalRecord = parseInt(TotalRecord);RecordSize = parseInt(RecordSize);CurrentPage = parseInt(CurrentPage);
    if (TotalRecord > RecordSize) {
        sb = "<span class='spnc' id='spnc" + NumSize + "'></span>";
        var TotalNum;
        TotalNum = TotalRecord % RecordSize ? Math.floor(TotalRecord / RecordSize + 1) : TotalRecord / RecordSize;
        if (TotalNum >= CurrentPage) {
            var startindex = CurrentPage % NumSize ? Math.floor(CurrentPage / NumSize) : CurrentPage / NumSize - 1;
            startindex = startindex * NumSize;
            var finishindex = parseInt(startindex) + parseInt(NumSize);
            var tfi = TotalRecord % RecordSize ? Math.floor(TotalRecord / RecordSize) + 1 : TotalRecord / RecordSize;
            if (finishindex > tfi) finishindex = tfi;
            if (startindex >= NumSize) sb += "<li><a href=" + startindex + "> Önceki </a></li>"; else sb += "<li><a href='#'> Önceki </a></li>";
            for (var i = startindex + 1; i <= finishindex; i++) {
                if (i == CurrentPage) sb += "<li class='active'><a href='#'>" + i + "</a></li>";
                else sb += "<li><a href='" + Path + i + "'>" + i + "</a><li>";
            }
            var r = CurrentPage % NumSize ? (parseInt(Math.floor(CurrentPage / NumSize)) * NumSize + parseInt(NumSize)) : ((parseInt(CurrentPage / NumSize) - 1) * NumSize + parseInt(NumSize));
            if (r < TotalNum) sb += "<li><a href='" + i + "'> :right</a></li>"; else sb += "<li><a href='#'>Sonraki</a></li>"
        }
    }
    return sb;
}
</script>

1 Temmuz 2012 Pazar

notlar



var el = $('input[type=text], textarea');
el.focus(function (e) { if (e.target.value == e.target.defaultValue) e.target.value = ''; });
        el.blur(function (e) { if (e.target.value == '') e.target.value = e.target.defaultValue; });



Response.Redirect(Url.RouteUrl(new { controller = "Home", action = "Index" }));

9 Şubat 2012 Perşembe

try javascript define object



<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
var myFunc=function(name){
this.name=name
};

myFunc.prototype = {
propFirst:null,
propSecond:0,

propFunc : function(msg){
this.propFirst = msg;
//this.name=msg;
alert(this.propSecond+" : "+this.name+ " : "+msg);
}

};


$(document).ready(function(){

var x = new myFunc("fName");

x.propFunc("shit");


});
</script>

</head>
<body>

</body>
</html>