Aklımda Kalası Kelimeler

* давайте работать вместе
* Zarf ve Mazruf, Zerafet(xHoyratlık) ile aynı kökten(za-ra-fe) gelir
* Bedesten
* Suç subuta ermiştir - Suç sabit olmuştur
ASP.NET etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster
ASP.NET etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster

7 Eylül 2014 Pazar

httpCompression Asp.net ve IIS Gzip Deflate

Ozenemiyorum ama bulduğum kaynaklar:

4 Nisan 2013 Perşembe

Code First ile Migration

Context sınıfınızın default yapıcısı olmalı ve doğru dbnin adını vermelisiniz.


PM konsolunuzda ilgili projenizin(context'i barındıran) kök klasörüne gelmelisiniz ve "Enable-Migrations –EnableAutomaticMigrations" kodunu çalıştırmalısınız. Bu kodu bulamadım diyerek çalışmazsa entity framework'ünüzü güncellemeyi deneyin. Enable-Migrations –EnableAutomaticMigrations çalıştıktan sonra Migrations diye bir klasör ve içinde Configuration.cs sınıfının oluştuğunu göreceksiniz.


Ardından "Update-Database -Verbose" kodunu kullanrak kodunuzdaki güncellemeyi veritabanınıza yansıtabilirsiniz. -Verbose parametresi ile çalıştırılan SQL ifadelerini gözlemleyebilirsiniz.


Son olarak hem PM de hangi klasörede olduğumuzu hemde update sonucundaki sql ifadelerini görebileceğiniz ekran:

3 Nisan 2013 Çarşamba

ASP.Net Life Cycle bir kenarda dursun

İlgili sayfa: http://fuchangmiao.blogspot.com/2007/11/aspnet-20-page-lifecycle.html

26 Şubat 2012 Pazar

14 Ağustos 2011 Pazar

Basit bir dll'i WebControl olarak ASPX sayfanızda Kontrol gibi göstermek.

Herşey bir sınıfsa (%100 OO), o zaman bir web control'ü de sınıf olmalı. Demek ki bir Class Library projesi işimizi görecek, custom server side web control yapmamız için.

Tek olayımız, sınıfımızın webde görünmesi için onun Render gibi bir metoda ya da CreateChildControls diye başka bir metoda ihtiyacımız olmasıdır(CreateChildControls metodunu atıyorda olabilirim).

Sınıfımızı WebControl'den türettim ve içinde Render metodunu gördüm. Ona da ekranda görüldüğünde belli olsun diye birşeyler yazdım.

using System.Web.UI;

using System.Web.UI.WebControls;

namespace Cem.Controls.WebKontrol
{
public class CemKontrol:WebControl
{
protected override void Render(HtmlTextWriter writer)
{
base.Render(writer);
writer.Write("
CEMMMMMM
");
}
}
}


Şimdi bu sınıftan oluşan dll dosyamı (GAC'a yüklesem güzel olurdu ama çöplük değil GAC'ım) web application/web site projeme referanslıyorum(web site'da denemedim ama onada referanslarım herhalde).

Bu arada Render metodumuzdan biraz bahsedelim. protected override void Render(HtmlTextWriter writer) metodumuzun içinde this.Controls.Add(new Label(){ Text="<p style='color:orange'>Portakal Ağacı ektim buraya</p>" }); diyebiliriz. Ama bu Label'ın ekranda çıkması için base.Render(writer); metod çağrısını en altta yapmamız gerekiyor.

Sonrada Default.aspx dosyamı aşağıdaki gibi düzenliyorum:
<%@ Page Language="C#" 

AutoEventWireup="true"
CodeBehind="Default.aspx.cs"
Inherits="WebApplication1._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@ Register Assembly="Cem.Controls.WebKontrol, Version=1.0.0.0, Culture=neutral, PublicKeyToken=026d3b7fdfbc431f"
Namespace="Cem.Controls.WebKontrol"
TagPrefix="cc" %>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<cc:CemKontrol runat="server" ID="ccccem" />
</div>
</form>
</body>
</html>


Sonuçta istediğimi aldım:



Şimdi birde CenkKontrol.cs isminde sınıf dosyasını DLL imize ekleyip web sayfamızda gösterelim:

Sonucumuz:

Bu durumda özetimizde Yunus Emre'den:
girdim ilim meclisine, eyledim kıldım talep
dediler ilim geride, illa edep illa edep.


Bu da güzel bir kaynak: Walkthrough: Creating a Web Custom Control

2 Ağustos 2011 Salı

ASP.NET ile Kullanıcı Kontrolü




User Control (uc.ascx):
<%@ Control Language="C#" %>

<script runat="server">

protected override void CreateChildControls()
{
base.CreateChildControls();
inputBox.Text = "cem";
inputBox.TextChanged += new EventHandler(inputBox_TextChanged);
}

void inputBox_TextChanged(object sender, EventArgs e)
{
inputBox.Text = "ne demek değişti";
inputBox.Text += Environment.NewLine;
inputBox.Text += this.DegistirilebilirProperty;
}

private string degisken;
[Personalizable]
public string DegistirilebilirProperty
{
get{ return degisken; }

set { degisken = value; }
}
</script>

<div>
Merhaba ben User Control ;)
</div>
<div>
<asp:TextBox runat="server" ID="inputBox"
TextMode="MultiLine" Rows="3"/>
<asp:Button runat="server"
ID="searchButton" Text="Search" />
</div>


Default.aspx:
<%@ Page Language="C#" 
AutoEventWireup="true"
CodeBehind="Default.aspx.cs"
Inherits="wacop._Default" %>

<%@ Register Src="uc.ascx"
TagName="uc"
TagPrefix="uc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<uc1:uc ID="uc1" runat="server"
DegistirilebilirProperty="Değiştirdim işte bunu!!" />
</form>
</body>
</html>


Tüm bunların peşine okumak isteyebileceğiniz bir iki adres:
How to: Treat a User Control as a Web Parts Control
How Do I: Create Visual Web Parts for SharePoint 2010 in Visual Studio 2010?
How to register a WebService from a User Control
Calling Web Service from embedded user control
Call webservice from UserControl in Sharepoint

16 Mart 2011 Çarşamba

ASP.NET ile Excel import

Ref: http://www.aspfree.com/c/a/ASP.NET-Code/Read-Excel-files-from-ASPNET/


protected void Page_Load(object sender, EventArgs e)
{
string strConn;
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=C:\\temp\\deltamed.xls;" +
"Extended Properties=Excel 8.0;";
//You must use the $ after the object you reference in the spreadsheet
OleDbDataAdapter myCommand = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", strConn);

DataSet myDataSet = new DataSet();
myCommand.Fill(myDataSet, "ExcelInfo");
DataGrid1.DataSource = myDataSet.Tables["ExcelInfo"].DefaultView;
DataGrid1.DataBind();
}

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server">SpreadSheetContents:</asp:Label><br />
<asp:DataGrid ID="DataGrid1" runat="server" />
</div>
</form>
</body>
</html>

30 Ocak 2011 Pazar

MasterPage içinde javascriptleri sayfaya eklemek


protected void Page_Load(object sender, EventArgs e)
{
f_ScriptLinkEkle();
}

/// <summary>
/// Bu metod ile script ve link etiketleri sayfanın en üstüne bir kere eklenir.
/// Böylece hangi klasördeki sayfa çağırılırsa çağırılsın tekrar js ve css leri eklemek gerekmez.
/// </summary>
void f_ScriptLinkEkle()
{
List lstScripts = new List();
lstScripts.AddRange(
new[]
{
"Scripts/jquery-1.3.2.js",
"Scripts/jquery-1.3.2-vsdoc.js",
"Scripts/jquery.blockUI.1.33.js",
"Scripts/jquery.blockUI.js",
"Scripts/jquery.fancybox/jquery.easing.1.3.js",
"Scripts/jquery.fancybox/jquery.fancybox-1.2.1.js",
"Scripts/jquery.fancybox/jquery.fancybox.css"
}
);

List lstLinks = new List();
lstLinks.AddRange(new[]
{
"App_Themes/OrderDefault/styles.css",
"Scripts/jquery.fancybox/jquery.fancybox.css"
});


string[] sarrSegments = Request.AppRelativeCurrentExecutionFilePath.Split(new[] { '/' });
string sUstDizin = "";
for (int j = 1; j < sarrSegments.Length - 1; j++)
{
sUstDizin += "../";
}

foreach (string script in lstScripts)
{
cpScripts.Controls.Add(new LiteralControl(""));
}

foreach (string link in lstLinks)
{
cpScripts.Controls.Add(new LiteralControl("<link href=\"" + sUstDizin + link + "\" type=\"text/css\" rel=\"stylesheet\"/>"));
}
}

12 Ocak 2011 Çarşamba

Visual Studio ile yerel IIS üstünde çalışırken HTTP Error 500.21 hatası aldığında

Ref: http://forums.asp.net/t/1587832.aspx
Yukarıdaki adreste yaşananlar ile benim aldığım sonuç aynı(IIS 7 ve IIS 7.5).


HTTP Error 500.21 - Internal Server Error
Handler "PageHandlerFactory-Integrated" has a bad module "ManagedPipelineHandler" in its module list

* Managed handler is used; however, ASP.NET is not installed or is not installed completely.
* There is a typographical error in the configuration for the handler module list.





29 Aralık 2010 Çarşamba

ASP.NET te Authentication ve Authorization


private void Page_Load(object sender, System.EventArgs e)
{
Response.Write("Authentication Tipi : " + Request.ServerVariables["AUTH_TYPE"] + "
");
Response.Write("Mevcut Sistem Kullanıcı : " + HttpContext.Current.User.Identity.Name + "
");
Response.Write("Mevcut ASP.NET kullanıcısı : " + WindowsIdentity.GetCurrent().Name + "
");
Response.Write("Şifre : " + Request.ServerVariables["AUTH_PASSWORD"]);
}

NTLM




Authentication Tipi : NTLM
Mevcut Sistem Kullanıcı : AK_METAL\selim.sen
Mevcut ASP.NET kullanıcısı : NT AUTHORITY\NETWORK SERVICE
Şifre :

BASIC




Authentication Tipi : Basic
Mevcut Sistem Kullanıcı : AK_METAL\selim.sen
Mevcut ASP.NET kullanıcısı : NT AUTHORITY\NETWORK SERVICE
Şifre : sifreKabak

DIGEST




Authentication Tipi : Digest
Mevcut Sistem Kullanıcı : AK_METAL\selim.sen
Mevcut ASP.NET kullanıcısı : NT AUTHORITY\NETWORK SERVICE
Şifre :






Referans: http://www.csharpnedir.com/articles/read/?id=485&title=ASP.NET%20G%C3%BCvenlik%20I%20-%20IIS%20Authentication

22 Şubat 2010 Pazartesi

ASP.NET Web Site Paths

http://msdn.microsoft.com/en-us/library/ms178116.aspx

An absolute URL path. An absolute URL path is useful if you are referencing resources in another location, such as an external Web site.


<img src="http://www.contoso.com/MyApplication/Images/SampleImage.jpg" />



A site-root relative path, which is resolved against the site root (not the application root). Site-root relative paths are useful if you keep cross-application resources, such as images or client script files, in a folder that is located under the Web site root.

This example path assumes that an Images folder is located under the Web site root.


<img src="/Images/SampleImage.jpg" />



If your Web site is http://www.contoso.com, the path would resolve to the following.


http://www.contoso.com/Images/SampleImage.jpg



A relative path that is resolved against the current page path.


<img src="Images/SampleImage.jpg" />



A relative path that is resolved as a peer of the current page path.


<img src="../Images/SampleImage.jpg" />

16 Şubat 2010 Salı

ASP.NET te Page Error

Code Behind kısmında hata yakalama:

protected void Page_Error(object sender, EventArgs e)
{
try
{
Response.Write(Server.GetLastError().Message);
}
finally
{
Server.ClearError();
}
}


Global.asax ta hata yakalama:

protected void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
Exception objErr = Server.GetLastError().GetBaseException();
string err = "Error in: " + Request.Url.ToString() +
". Error Message:" + objErr.Message.ToString();

}

14 Şubat 2010 Pazar

Dizinleri TreeView içinde göstermek



<asp:TreeView ID="tvKlasorler" runat="server" ImageSet="Arrows" PathSeparator="|"
ShowCheckBoxes="Leaf" >
<HoverNodeStyle Font-Underline="True" ForeColor="#5555DD" />
<SelectedNodeStyle Font-Underline="True" ForeColor="#5555DD" HorizontalPadding="0px"
VerticalPadding="0px" />
<NodeStyle Font-Names="Verdana" ForeColor="Black" HorizontalPadding="5px"
NodeSpacing="0px" VerticalPadding="0px" />
</asp:TreeView>


CODE BEHIND:

protected void Page_Load(object sender, EventArgs e)
{
TreeNode root = new TreeNode("KÖK-Root"); // EN ÜST TUTUCU

DirectoryInfo dir = new DirectoryInfo(Server.MapPath("~/"));
foreach (DirectoryInfo g in dir.GetDirectories())
{
//SVN ne Resharper klasörleri hariç
if (!f_SVNDizinimi(g) && !f_ResharperDizinimi(g) )
{
// Bu klasörü ve altındaki klasörleri Root Node'a ekle
root.ChildNodes.Add(f_GetNode(g));
}
}
tvKlasorler.Nodes.Add(root);
}

private TreeNode f_GetNode(DirectoryInfo altDizin)
{
//Bu klasörü NODE olarak oluşturalım. (Ağacın bir dalı olsun)
TreeNode tn = new TreeNode(altDizin.Name);

//Bu dalın alt dalları(klasörleri) varmı? Varsa, SVN ve RESHARPER olmayanları çekelim
DirectoryInfo[] yeniDizi = f_AltDizinleriGetir(altDizin.GetDirectories());

//Eğer alt dalları yoksa bir üst dala eklenmek üzere geri gönderelim
if (yeniDizi.Count() == 0)
{
return new TreeNode(altDizin.Name);
}
else //Eğer alt dalları varsa
{
//Alt dalların(klasörlerin) herbirini dolaşalım ve bulunduğumuz dala ekleyelim
foreach (DirectoryInfo info in yeniDizi)
{
tn.ChildNodes.Add(f_GetNode(info));
}
return tn;
}
}

private DirectoryInfo[] f_AltDizinleriGetir(DirectoryInfo[] dirs)
{
return dirs.Where(d => ((f_Dizinmi(d) && !f_Gizlimi(d) && !f_SVNDizinimi(d) && !f_ResharperDizinimi(d)))).Select(p => p).ToArray();
}

private bool f_Dizinmi(DirectoryInfo g)
{
return ((g.Attributes & FileAttributes.Directory) == FileAttributes.Directory);
}

private bool f_Gizlimi(DirectoryInfo g)
{
return ((g.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden);
}

private bool f_SVNDizinimi(DirectoryInfo g)
{
return g.Name.Equals(".svn");
}

private bool f_ResharperDizinimi(DirectoryInfo g)
{
return g.Name.Equals("_ReSharper");
}

17 Ocak 2010 Pazar

Application_BeginRequest ile loglama




// Global.asax içinde
protected void Application_BeginRequest(object sender, EventArgs e)
{
Uri uri = HttpContext.Current.Request.Url;
StreamWriter sw = File.AppendText(Server.MapPath("~/test.txt"));
sw.WriteLine(uri.PathAndQuery + "\t\t" + DateTime.Now.ToString("HH:mm:ss.fffffff"));
sw.Flush();
sw.Close();
}



<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="HttpHandlerKullananWeb._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h1>Tekrar yükle</h1>

<script type="text/javascript">

setTimeout(function() {
var ss = "default.aspx?id=" + Math.random();
document.write(ss)
window.location = ss;
}, 1000);

</script>

</div>
</form>
</body>
</html>


/Default.aspx18:11:38.1581721
/default.aspx?id=0.981415984579683718:11:39.4771721
/default.aspx?id=0.069058977730859418:11:40.5121721
/default.aspx?id=0.292619688396253118:11:41.5431721
/default.aspx?id=0.2771434686967443318:11:42.5711721
/default.aspx?id=0.2399070493119078718:11:43.6031721
/default.aspx?id=0.515263955577543418:11:44.6311721
/default.aspx?id=0.966319288964455418:11:45.6601721
/default.aspx?id=0.0523383615308979418:11:46.6891721
/default.aspx?id=0.99070154676295818:11:47.7231721
/default.aspx?id=0.850952136399098818:11:48.7491721
/default.aspx?id=0.888948235623865918:11:49.7801721
/default.aspx?id=0.810726927811147118:11:50.8091721
/default.aspx?id=0.955277945826294818:11:51.8381721
/default.aspx?id=0.884317455302272118:11:52.8671721
/default.aspx?id=0.261800651271007918:11:53.8971721
/default.aspx?id=0.2361858997090218218:11:54.9261721
/default.aspx?id=0.0636965551525190418:11:55.9551721
/default.aspx?id=0.550006071355276818:11:56.9871721
/default.aspx?id=0.1465605177084249318:11:58.0161721
/default.aspx?id=0.801216411263875518:11:59.0451721
/default.aspx?id=0.1391057298117566218:12:00.0731721
/default.aspx?id=0.80565989399424918:12:01.1041721
/default.aspx?id=0.941316114752180218:12:02.1331721
/default.aspx?id=0.03283465597320278618:12:03.1621721
/default.aspx?id=0.68376576402704218:12:04.1931721
/default.aspx?id=0.07307012362005218:12:05.2221721
/default.aspx?id=0.2422870348938556718:12:06.2671721

ASp.Net Resimleri

Request



Request.Url




Request.UserLanguages



Request.Params.AllKeys - Request.ServerVariables



Request.Filter - Request.Headers



File Upload




protected void btnYukle_Click(object sender, EventArgs e)
{
// Check to see if file was uploaded
if (flYuklenen.PostedFile != null)
{
// Get a reference to PostedFile object
HttpPostedFile yuklenenDosya = flYuklenen.PostedFile;

// Get size of uploaded file
int iDosyaUzunlugu = yuklenenDosya.ContentLength;

// make sure the size of the file is > 0
if (iDosyaUzunlugu > 0)
{
// Allocate a buffer for reading of the file
byte[] dosyaVerisi = new byte[iDosyaUzunlugu];

// Read uploaded file from the Stream
yuklenenDosya.InputStream.Read(dosyaVerisi, 0, iDosyaUzunlugu);

// Create a name for the file to store
string strSadeceDosyaAdi = Path.GetFileName(yuklenenDosya.FileName);
string sKaydedilecekYer = Server.MapPath("MediaYuklenen") + "/";
string sKaydedilecekDosyaAdi = strSadeceDosyaAdi +DateTime.Now.ToString("-ddMMyyyyhhMMss");

// Save file to disk
yuklenenDosya.SaveAs(sKaydedilecekYer+sKaydedilecekDosyaAdi);
}
}
}



HTTP Request




AbsolutePath"/Default.aspx"string
AbsoluteUri"http://localhost:50416/Default.aspx"string
Authority"localhost:50416"string
DnsSafeHost"localhost"string
Fragment""string
Host"localhost"string
HostNameTypeDnsSystem.UriHostNameType
IsAbsoluteUritruebool
IsDefaultPortfalsebool
IsFilefalsebool
IsLoopbacktruebool
IsUncfalsebool
LocalPath"/Default.aspx"string
OriginalString"http://localhost:50416/Default.aspx"string
PathAndQuery"/Default.aspx"string
Port50416int
Query""string
Scheme"http"string
-Segments{string[2]}string[]
[0]"/"string
[1]"Default.aspx"string
UserEscapedfalsebool
UserInfo""string
+Static membersSystem.UriSystem.Uri
+Non-Public members{http://localhost:50416/Default.aspx}System.Uri



REQUEST





+ AcceptTypes {string[1]} string[]
AnonymousID null string
ApplicationPath "/" string
AppRelativeCurrentExecutionFilePath "~/Ilanlar.aspx" string
+ Browser {System.Web.Mobile.MobileCapabilities} System.Web.HttpBrowserCapabilities {System.Web.Mobile.MobileCapabilities}
+ ClientCertificate {System.Web.HttpClientCertificate} System.Web.HttpClientCertificate
+ ContentEncoding {System.Text.UTF8Encoding} System.Text.Encoding {System.Text.UTF8Encoding}
ContentLength 0 int
ContentType "" string
+ Cookies {System.Web.HttpCookieCollection} System.Web.HttpCookieCollection
CurrentExecutionFilePath "/Ilanlar.aspx" string
FilePath "/Ilanlar.aspx" string
+ Files {System.Web.HttpFileCollection} System.Web.HttpFileCollection
+ Filter {System.Web.HttpInputStreamFilterSource} System.IO.Stream {System.Web.HttpInputStreamFilterSource}
+ Form {} System.Collections.Specialized.NameValueCollection {System.Web.HttpValueCollection}
+ Headers {Connection=Keep-Alive&Accept=*%2f*&Accept-Encoding=gzip%2c+deflate&Accept-Language=tr&Host=localhost%3a53237&User-Agent=Mozilla%2f4.0+(compatible%3b+MSIE+8.0%3b+Windows+NT+5.1%3b+Trident%2f4.0%3b+.NET+CLR+1.1.4322%3b+.NET+CLR+2.0.50727%3b+.NET+CLR+3.0.4506.2152%3b+.NET+CLR+3.5.30729)} System.Collections.Specialized.NameValueCollection {System.Web.HttpHeaderCollection}
HttpMethod "GET" string
+ InputStream {System.Web.HttpInputStream} System.IO.Stream {System.Web.HttpInputStream}
IsAuthenticated true bool
IsLocal true bool
IsSecureConnection false bool
+ LogonUserIdentity {System.Security.Principal.WindowsIdentity} System.Security.Principal.WindowsIdentity
+ Params {ALL_HTTP=HTTP_CONNECTION%3aKeep-Alive%0d%0aHTTP_ACCEPT%3a*%2f*%0d%0aHTTP_ACCEPT_ENCODING%3agzip%2c+deflate%0d%0aHTTP_ACCEPT_LANGUAGE%3atr%0d%0aHTTP_HOST%3alocalhost%3a53237%0d%0aHTTP_USER_AGENT%3aMozilla%2f4.0+(compatible%3b+MSIE+8.0%3b+Windows+NT+5.1%3b+Trident%2f4.0%3b+.NET+CLR+1.1.4322%3b+.NET+CLR+2.0.50727%3b+.NET+CLR+3.0.4506.2152%3b+.NET+CLR+3.5.30729)%0d%0a&ALL_RAW=Connection%3a+Keep-Alive%0d%0aAccept%3a+*%2f*%0d%0aAccept-Encoding%3a+gzip%2c+deflate%0d%0aAccept-Language%3a+tr%0d%0aHost%3a+localhost%3a53237%0d%0aUser-Agent%3a+Mozilla%2f4.0+(compatible%3b+MSIE+8.0%3b+Windows+NT+5.1%3b+Trident%2f4.0%3b+.NET+CLR+1.1.4322%3b+.NET+CLR+2.0.50727%3b+.NET+CLR+3.0.4506.2152%3b+.NET+CLR+3.5.30729)%0d%0a&APPL_MD_PATH=&APPL_PHYSICAL_PATH=C%3a%5cProjeler%5cYabanTV%5cSourceCode%5cTest%5cwaDataGrid%5c&AUTH_TYPE=NTLM&AUTH_USER=VS08SQL05%5cAdministrator&AUTH_PASSWORD=&LOGON_USER=VS08SQL05%5cAdministrator&REMOTE_USER=VS08SQL05%5cAdministrator&CERT_COOKIE=&CERT_FLAGS=&CERT_ISSUER=&CERT_KEYSIZE=&CERT_SECRETKEYSIZE=&CERT_SERIALNUMBER=&CERT_SERVER_ISSUER=&CERT_SERVER_SUBJECT=&CERT_SUBJECT=&CONTENT_LENGTH=0&CONTENT_TYPE=&GATEWAY_INTERFACE=&HTTPS=&HTTPS_KEYSIZE=&HTTPS_SECRETKEYSIZE=&HTTPS_SERVER_ISSUER=&HTTPS_SERVER_SUBJECT=&INSTANCE_ID=&INSTANCE_META_PATH=&LOCAL_ADDR=127.0.0.1&PATH_INFO=%2fIlanlar.aspx&PATH_TRANSLATED=C%3a%5cProjeler%5cYabanTV%5cSourceCode%5cTest%5cwaDataGrid%5cIlanlar.aspx&QUERY_STRING=&REMOTE_ADDR=127.0.0.1&REMOTE_HOST=127.0.0.1&REMOTE_PORT=&REQUEST_METHOD=GET&SCRIPT_NAME=%2fIlanlar.aspx&SERVER_NAME=localhost&SERVER_PORT=53237&SERVER_PORT_SECURE=0&SERVER_PROTOCOL=HTTP%2f1.1&SERVER_SOFTWARE=&URL=%2fIlanlar.aspx&HTTP_CONNECTION=Keep-Alive&HTTP_ACCEPT=*%2f*&HTTP_ACCEPT_ENCODING=gzip%2c+deflate&HTTP_ACCEPT_LANGUAGE=tr&HTTP_HOST=localhost%3a53237&HTTP_USER_AGENT=Mozilla%2f4.0+(compatible%3b+MSIE+8.0%3b+Windows+NT+5.1%3b+Trident%2f4.0%3b+.NET+CLR+1.1.4322%3b+.NET+CLR+2.0.50727%3b+.NET+CLR+3.0.4506.2152%3b+.NET+CLR+3.5.30729)} System.Collections.Specialized.NameValueCollection {System.Web.HttpValueCollection}
Path "/Ilanlar.aspx" string
PathInfo "" string
PhysicalApplicationPath "C:\\Projeler\\YabanTV\\SourceCode\\Test\\waDataGrid\\" string
PhysicalPath "C:\\Projeler\\YabanTV\\SourceCode\\Test\\waDataGrid\\Ilanlar.aspx" string
+ QueryString {} System.Collections.Specialized.NameValueCollection {System.Web.HttpValueCollection}
RawUrl "/Ilanlar.aspx" string
RequestType "GET" string
+ ServerVariables {ALL_HTTP=HTTP_CONNECTION%3aKeep-Alive%0d%0aHTTP_ACCEPT%3a*%2f*%0d%0aHTTP_ACCEPT_ENCODING%3agzip%2c+deflate%0d%0aHTTP_ACCEPT_LANGUAGE%3atr%0d%0aHTTP_HOST%3alocalhost%3a53237%0d%0aHTTP_USER_AGENT%3aMozilla%2f4.0+(compatible%3b+MSIE+8.0%3b+Windows+NT+5.1%3b+Trident%2f4.0%3b+.NET+CLR+1.1.4322%3b+.NET+CLR+2.0.50727%3b+.NET+CLR+3.0.4506.2152%3b+.NET+CLR+3.5.30729)%0d%0a&ALL_RAW=Connection%3a+Keep-Alive%0d%0aAccept%3a+*%2f*%0d%0aAccept-Encoding%3a+gzip%2c+deflate%0d%0aAccept-Language%3a+tr%0d%0aHost%3a+localhost%3a53237%0d%0aUser-Agent%3a+Mozilla%2f4.0+(compatible%3b+MSIE+8.0%3b+Windows+NT+5.1%3b+Trident%2f4.0%3b+.NET+CLR+1.1.4322%3b+.NET+CLR+2.0.50727%3b+.NET+CLR+3.0.4506.2152%3b+.NET+CLR+3.5.30729)%0d%0a&APPL_MD_PATH=&APPL_PHYSICAL_PATH=C%3a%5cProjeler%5cYabanTV%5cSourceCode%5cTest%5cwaDataGrid%5c&AUTH_TYPE=NTLM&AUTH_USER=VS08SQL05%5cAdministrator&AUTH_PASSWORD=&LOGON_USER=VS08SQL05%5cAdministrator&REMOTE_USER=VS08SQL05%5cAdministrator&CERT_COOKIE=&CERT_FLAGS=&CERT_ISSUER=&CERT_KEYSIZE=&CERT_SECRETKEYSIZE=&CERT_SERIALNUMBER=&CERT_SERVER_ISSUER=&CERT_SERVER_SUBJECT=&CERT_SUBJECT=&CONTENT_LENGTH=0&CONTENT_TYPE=&GATEWAY_INTERFACE=&HTTPS=&HTTPS_KEYSIZE=&HTTPS_SECRETKEYSIZE=&HTTPS_SERVER_ISSUER=&HTTPS_SERVER_SUBJECT=&INSTANCE_ID=&INSTANCE_META_PATH=&LOCAL_ADDR=127.0.0.1&PATH_INFO=%2fIlanlar.aspx&PATH_TRANSLATED=C%3a%5cProjeler%5cYabanTV%5cSourceCode%5cTest%5cwaDataGrid%5cIlanlar.aspx&QUERY_STRING=&REMOTE_ADDR=127.0.0.1&REMOTE_HOST=127.0.0.1&REMOTE_PORT=&REQUEST_METHOD=GET&SCRIPT_NAME=%2fIlanlar.aspx&SERVER_NAME=localhost&SERVER_PORT=53237&SERVER_PORT_SECURE=0&SERVER_PROTOCOL=HTTP%2f1.1&SERVER_SOFTWARE=&URL=%2fIlanlar.aspx&HTTP_CONNECTION=Keep-Alive&HTTP_ACCEPT=*%2f*&HTTP_ACCEPT_ENCODING=gzip%2c+deflate&HTTP_ACCEPT_LANGUAGE=tr&HTTP_HOST=localhost%3a53237&HTTP_USER_AGENT=Mozilla%2f4.0+(compatible%3b+MSIE+8.0%3b+Windows+NT+5.1%3b+Trident%2f4.0%3b+.NET+CLR+1.1.4322%3b+.NET+CLR+2.0.50727%3b+.NET+CLR+3.0.4506.2152%3b+.NET+CLR+3.5.30729)} System.Collections.Specialized.NameValueCollection {System.Web.HttpServerVarsCollection}
TotalBytes 0 int
+ Url {http://localhost:53237/Ilanlar.aspx} System.Uri
+ UrlReferrer null System.Uri
UserAgent "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)" string
UserHostAddress "127.0.0.1" string
UserHostName "127.0.0.1" string
+ UserLanguages {string[1]} string[]
+ Static members
+ Non-Public members

ASP.NET HttpHandler, HttpModule Özetim

Referans: Burak Selim Şenyurt



Sayfanın yaşam döngüsü:
PreInit -> Init -> Load -> Change/ Click -> PreRender -> UnLoad -> Dispose




using System;
using System.Web;

namespace MyHttpHandlers
{
/*
IHttpHandler arayüzü, HandlerOrnek isimli sınıfımız içerisine iki üye dahil eder.
Bunlardan ProcessRequest isimli metod, gelen talepleri değerlendirebileceğimiz üyedir.
Yani talebe göre Html içeriğini oluşturabileceğimiz bir başka deyişle http isteğini
kendi istediğimiz şekilde ele alabileceğimiz yerdir.
Dikkat ederseniz bu metod parametre olarak HttpContext tipinden bir değişken almaktadır.
Bu değişken sayesinde, Response, Request ve Server nesnelerine erişebiliriz.
Bu da gelen talepler HttpHandler içerisinde değerlendirebileceğimiz anlamına gelir.

IsReusable özelliği ise sadece okunabilir bir özelliktir
ve ilgili HttpHandler nesne örneğine ait referansın başka talepler
içinde kullanılıp kullanılmayacağını belirler.
*/
public class HandlerOrnek : IHttpHandler
{
#region IHttpHandler Members

public bool IsReusable
{
get { return true; }
}

public void ProcessRequest(HttpContext context)
{
string isim = context.Request["Ad"];
context.Response.Write(" Adım : " + isim + "
");
}

#endregion
}



//------------------------- HTTPMODULE ÖRNEĞİ ------------------//



/*
IHttpHandler, uygulandığı tipe iki metod dahil eder. Init ve Dispose.
Init metodu HttpApplication tipinden bir parametre almaktadır ki
bu parametre sayesinde var olan HttpModule olaylarına müdahale etme,
aktif Http içeriğine ulaşma gibi imkanlara sahip olabiliriz.

Dispose metodunu ise, bu sınıfa ait nesne örneği yok edilmeden önce
yapmak istediğimiz kaynak temizleme işlemleri için kullanabiliriz.
Örneğin Module içerisinden kullanılan unmanaged(managed) kaynakların
serbest bırakılması için ele alabiliriz.
*/
class ModuleOrnek : IHttpModule
{
#region IHttpModule Members

public void Init(HttpApplication context)
{
// Save the application
mApplication = context;

context.PreSendRequestContent += new EventHandler(context_PreSendRequestContent);

// http://www.informit.com/articles/article.aspx?p=25339&seqNum=3
// Wire up beginrequest
context.BeginRequest += new System.EventHandler(BeginRequest);

// Wire up endrequest
context.EndRequest += new System.EventHandler(EndRequest);
}

public void Dispose()
{
throw new NotImplementedException();
}

#endregion

#region Bizim eklediklerimiz


private HttpApplication mApplication;


/*
Bakın burada uygulama için PreSendRequestContent isimli bir olay yüklenmiştir.
Bu olay, HttpHandler tarafından üretilen HTML içeriği gönderilmeden önce çalışır.
Böylece bu modülü kullanan bir uygulama içerisindeki herhangi bir sayfa talebinde
gönderilen Http içeriğine "Bu sayfa Z şirketi tarafından üretilmiştir..." cümlesi
bir yorum takısı (comment tag) olarak eklenecektir.
Yazdığımız HttpModullerin ilgili web uygulaması içerisinde geçerli olmasını sağlamak için
yine web.config dosyasında düzenleme yapmamız gerekmektedir.
Bu amaçla, web.config dosyasına aşağıdaki gibi httpModules sekmesini dahil etmemiz
ve yeni HttpModule' ümüzü bildirmemiz yeterli olacaktır.
*/
void context_PreSendRequestContent(object sender, EventArgs e)
{
mApplication.Response.Output.Write("Bu sayfa Z şirketi tarafından üretilmiştir");
}

public void BeginRequest(object sender, EventArgs e)
{
mApplication.Response.Write(
"");
}

public void EndRequest(object sender, EventArgs e)
{
mApplication.Response.Write(
"");
}


#endregion
}
/*
Olay (Event) İşlevi
--------------------- ----------------------------------
BeginRequest Bir talep geldiğinde tetiklenir.
EndRequest Cevap istemciye gönderilmeden hemen önce tetiklenir.
PreSendRequestHeaders İstemciye HTTP Header gönderilmeden hemen önce tetiklenir.
PreSendRequestContent İstemciye içerik gönderilmeden hemen önce tetiklenir.
AcquireRequestState Session gibi durum nesneleri (state objects) elde edilmeye hazır hale geldiğinde tetiklenir.
AuthenticateRequest Kullanıcı doğrulanmaya hazır hale geldiğinde tetiklenir.
AuthorizeRequest Kullanıcının yetkileri kontrol edilmeye hazır hale geldiğinde tetiklenir.
*/
}


16 Ocak 2010 Cumartesi

JQuery ve ASP.NET web servisi ile JSON veriyi parsetmek


public class HavaDurumu
{
public string Min;
public string Max;
public string Name;
public string Image;
}

[WebMethod]
public HavaDurumu f_HavaDurumuJson(string _sSehirler)
{
// TR873,TR2342 gibi bir string gelecek.
string[] _ArrSehirler = _sSehirler.Split(new[] { ',' });

string sSehirSonucu = "";
string name = "", min = "", max = "", image_code = "";

// Settings içinde havaDurumu = http://www.bugun.com.tr/files/hava.xml olmalı
XmlTextReader xmlReader = new XmlTextReader(Properties.Settings.Default.havaDurumu);
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(xmlReader);
XmlNode topNode = xmlDocument.DocumentElement;

foreach (string sehir in _ArrSehirler)
{
XmlNode hava = topNode.SelectSingleNode("record[code='" + sehir + "']");

name = hava.ChildNodes[1].InnerText;
min = hava.ChildNodes[4].InnerText;
max = hava.ChildNodes[5].InnerText;
image_code = hava.ChildNodes[6].InnerText;
sSehirSonucu += "{name:'" + name + "', min:" + min + ", max:" + max + ", image_code:'" + image_code + "'},";
}

return new HavaDurumu()
{
Name = name,
Image = image_code,
Min = min,
Max = max
};
}



function f_HavaDurumuJson(_sehir) {
alert("sehir sorgu: " + _sehir);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: 'WS/wsGenel.asmx/f_HavaDurumuJson',
data: "{_sSehirler:'" + _sehir + "'}",
dataType: "json",
success: function(data) {

alert(data.d.Name);
alert(data.d.Min);
alert(data.d.Max);
alert(data.d.Image);

$.each(data.d, function(ozellik, deger) {
alert(ozellik + " - " + deger);
});
}
});
}

f_HavaDurumuJson('TR2342');





Bir sınıfın dizi tipinde dönen değerini almak



public class HavaDurumu
{
public string Min;
public string Max;
public string Name;
public string Image;
}

[WebMethod]
public HavaDurumu[] f_HavaDurumuJson(string _sSehirler)
{
// TR873,TR2342 gibi bir string gelecek.
string[] _ArrSehirler = _sSehirler.Split(new[] { ',' });
HavaDurumu[] sonuc = new HavaDurumu[_ArrSehirler.Length];

string sSehirSonucu = "";
string name = "", min = "", max = "", image_code = "";

// Settings içinde havaDurumu = http://www.bugun.com.tr/files/hava.xml olmalı
XmlTextReader xmlReader = new XmlTextReader(Properties.Settings.Default.havaDurumu);
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(xmlReader);
XmlNode topNode = xmlDocument.DocumentElement;

for (int i = 0; i < _ArrSehirler.Length; i++)
{
string sehir = _ArrSehirler[i];
XmlNode hava = topNode.SelectSingleNode("record[code='" + sehir + "']");

name = hava.ChildNodes[1].InnerText;
min = hava.ChildNodes[4].InnerText;
max = hava.ChildNodes[5].InnerText;
image_code = hava.ChildNodes[6].InnerText;
sSehirSonucu += "{name:'" + name + "', min:" + min + ", max:" + max + ", image_code:'" + image_code + "'},";
sonuc[i] = new HavaDurumu()
{
Name = name,
Image = image_code,
Min = min,
Max = max
};
}

return sonuc;
}



function f_HavaDurumuJson(_sehir) {
alert("sehir sorgu: " + _sehir);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: 'WS/wsGenel.asmx/f_HavaDurumuJson',
data: "{_sSehirler:'" + _sehir + "'}",
dataType: "json",
success: function(data) {

alert("Dizinin uzunluğu: " + data.d.length);
alert("0. elemanın Name değeri: "+ data.d[0].Name);
$.each(data.d, function(i, eleman) {

alert(eleman.Name + " | " + eleman.Min + " | " + eleman.Max + " | " + eleman.Image);

$.each(eleman, function(key, value) {
alert(key + " - " + value);
});

});
}
});
}

f_HavaDurumuJson('TR2342,TR4801');


Kaynak:
http://www.eburhan.com/jquery-ve-json-islemleri/
http://prettycode.org/2009/04/07/using-jquery-with-aspnet-web-services-and-json/