session killer script

this one line of script is a killer of asp.net session on ie 7, 8, and 9 browsers (maybe ie6, i didn't test it):

$(document).ready(function() {
// for remembering the selected tabs
$("div[id*='tabs']").tabs({ cookie: { expires: 999, name: this.id }, cache: false, collapsible: true });
}

script'i 2 parça halinde yazmak buna neden oluyor.


//        // for remembering the selected tabs
        //        $("div[id*='tabs']").tabs({ cookie: { expires: 999, name: this.id }, cache: false, collapsible: true });

        // fade effect
        $("div[id*='tabs']").tabs({
            fx: {
                opacity: 'toggle',
                duration: 'fast'
            },
            cookie: { expires: 999, name: this.id }, cache: false, collapsible: true
        });

t-sql find object references

select object_name(object_id), OBJECT_DEFINITION(object_id)
from sys.objects
where OBJECT_DEFINITION(object_id) like '%CDS%' and type='P'

örn: ProductId alanının kullanıldığı sp'ler.

streamreader encoding

sorun: doğru encoding verilmezse türkçe karakterler okunamıyor.

çözüm:
StreamReader sr = new StreamReader("ornek.txt", Encoding.GetEncoding("windows-1254"));
textBox1.Text = sr.ReadToEnd();

Value cannot be null. Parameter name: name

add web reference ile web service eklenirken, veya web service çalıştırılırken, dbml'in güncel olmaması nedeniyle bulunamayan nesneler (stored procedure vb.) bu hataya neden olabiliyor.

indexed view with schemabinding

ALTER VIEW [dbo].[Vw_View1] WITH SCHEMABINDING AS
SELECT ...
FROM ...

CREATE UNIQUE CLUSTERED INDEX [IX_Index1] ON [dbo].[Vw_View1]
(
[Column1] ASC
)
GO

related errors:
Cannot create index on view  because the view is not schema bound.

http://www.mssqltips.com/tip.asp?tip=1610

checkboxlist prerender

protected void cblDilekceTipi_PreRender(object sender, EventArgs e)
{
foreach (ListItem item in cblDilekceTipi.Items)
{
item.Text = item.Text.Replace(" Dilekçesi", "");
}
}

ie6 background image

{ background: transparent url('../img/external.gif') no-repeat; padding-left: 10px; height: 20px; float: left; position: relative; filter: alpha(opacity=40); opacity: .40; }

the critical points are bold.

fixed bottom bar (facebook style) with jquery

http://ryan.rawswift.com/2009/02/15/fixed-that-bar-at-the-bottom-like-facebook/

jquery ui tabs sayfa yüklenirken dağılma sorunu

sayfanın tamamı yüklenmeden önce, yani document.ready sırasında çalışacak ve tab'ları düzenleyecek tabs metodu çalışmadan önce, tab'lar açık görünüyor. bunun önüne geçmek için kullanılabilecek bir yol; tab içeriğini gizlemek, sayfa yüklendikten sonra göstermek:

$("div[id*='tabs']").tabs({
fx: {
opacity: 'toggle',
duration: 'fast'
}
});

$(document).ready(function() {
document.getElementById('toptab').style.display = 'block';
}

http://stackoverflow.com/questions/1069758/should-jquery-tabs-be-inside-document-ready

jquery tipsy ie tooltip bug fix

http://github.com/jaz303/tipsy/commit/88923af6ee0e18ac252dfc3034661674b7670a97

initcap: set first letter uppercase, rest of other lowercase

CREATE FUNCTION [dbo].[InitCap] ( @InputString varchar(4000) )
RETURNS VARCHAR(4000)
AS
BEGIN

DECLARE @Index INT
DECLARE @Char CHAR(1)
DECLARE @PrevChar CHAR(1)
DECLARE @OutputString VARCHAR(255)

SET @OutputString = LOWER(@InputString)
SET @Index = 1

WHILE @Index <= LEN(@InputString)
BEGIN
SET @Char = SUBSTRING(@InputString, @Index, 1)
SET @PrevChar = CASE WHEN @Index = 1 THEN ' '
ELSE SUBSTRING(@InputString, @Index - 1, 1)
END

IF @PrevChar IN (' ', ';', ':', '!', '?', ',', '.', '_', '-', '/', '&', '''', '(')
BEGIN
IF @PrevChar != '''' OR UPPER(@Char) != 'S'
SET @OutputString = STUFF(@OutputString, @Index, 1, UPPER(@Char))
END

SET @Index = @Index + 1
END

RETURN @OutputString

END
GO


http://www.sql-server-helper.com/functions/initcap.aspx

select a treenode, and expand all parent nodes of it

select a treenode, and expand all parent nodes of it.

private void SetSelectedNode(int sira)
{
if (sira > 0)
{
TreeNode selectedNode = null;
foreach (TreeNode node in tvMadde.Nodes)
{
if (node.Value == sira.ToString())
{
selectedNode = node;
}

if (selectedNode == null)
{
if (node.ChildNodes.Count > 0)
{
selectedNode = GetNode(node, sira);
}
}
else
{
selectedNode.Checked = true;
selectedNode.Select();
if (selectedNode.Parent != null)
{
// selectedNode.Parent.Expand();
// selectednode'un tüm parent'larını aç
ExpandParent(selectedNode);
}

break;
//return;
}
}

if (selectedNode != null)
{
selectedNode.Checked = true;
selectedNode.Select();
selectedNode.Parent.Expand();
}
}
}

private void ExpandParent(TreeNode childNode)
{
if (childNode.Parent != null)
{
childNode.Parent.Expand();
ExpandParent(childNode.Parent);
}
}

making one button click another

input type="button" value="File" onclick="document.getElementById('file').click()"
input type="file" style="display:none" id="file" onchange="alert(this.value)"

http://www.webmasterworld.com/forum91/3606.htm

anonymous type in repeater or datalist

rptTargets.DataSource = from t in DB.SalesTargets select new { t.Target, t.SalesRep.RepName };

string repName = (string)DataBinder.Eval(e.Item.DataItem, "RepName");
string target = (string)DataBinder.Eval(e.Item.DataItem, "Target");

http://stackoverflow.com/questions/1212210/anonymous-type-in-repeater-databound-event

jquery autocomplete turkish character problem

sonuçların listelendiği sayfaya aşağıdaki meta tag'i ekle:

meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-9"

linq ExecuteQuery return multiple objects

// 1. Sadece Table1 sınıfını döndürür:

var query = "Select t1.*, t2.*, t2.PK
From Table1 t1
Inner Join Table2 t2 On t2.PK= t1.FK"


// 2. Hem Table1 sınıfını, hem de Table1 sınıfını döndürür:

var query = "Select t1.*, t2.*, t1.FK
From Table1 t1
Inner Join Table2 t2 On t2.PK= t1.FK"

var karars = db.ExecuteQuery(query).ToList();


// 3. Herhangi bir sınıf'ın örneğini döndürmez. Sadece select ile belirtilen alanları döndürür:

select new { k.KararId, k.Baslik, k.EsasNo, k.EsasTarihi, k.KararNo, k.KararTarihi, k.Ozet, k.MerciId, m.MerciAdi }).Distinct();


protected string GetMerciAdi()
{
try
{
// durum 2
return Eval("MerciAdi").ToString();
}
catch (Exception)
{
// durum 3
return ((Merci)Eval("Merci")).MerciAdi;
}
}

RegisterClientScriptBlock RegisterStartupScript

RegisterClientScriptBlock - RegisterStartupScript farkı:

RegisterStartupScript jquery autocomplete'in çalışmasını engelledi. RegisterClientScriptBlock ile değiştirince sorun ortadan kalktı.

resolveclienturl resolveurl

ResolveClientUrl("~/css/style.css") : MyWebSite/css/style.css
ResolveUrl("~/css/style.css") : /MyWebSite/css/style.css

/ : website'ın root'una çıkarıyor.

urlrewriting uygulandığında css ve js için path sorunu olabiliyor. resolveclienturl yerine resolveurl metodu kullanıldığınd bu sorun ortadan kalkıyor:

litCss.Text = "link +="" css="" href="" rel="stylesheet" resolveurl("~="" style.css")="" type="text/css">link";

bazı durumlarda (ki bunu netleştiremedim henüz) aspx'ten çağrılan protected metodlar çalışmıyor:

hyperlink'in navigateurl'i için yazdığım protected string getnavigateurl() çağrılmıyor.
ama page_load'da bu hyperlink'in navigateurl'ine değer atayabiliyorum.

basic t-sql commands

-- add primary key to a table
ALTER TABLE Karar ADD CONSTRAINT
PK_Karar PRIMARY KEY NONCLUSTERED
(
KararId
) ON [PRIMARY]
GO

-- change data type of a column
alter table Products
alter column ProductName varchar(250)

Supression of Click Sound on WebBrowser Navigate

Open the Sounds and Multimedia Control Panel applet (go to Start, Settings, Control Panel, and double-click Sounds and Multimedia).
Select the Sounds tab.
Under Sound Events, navigate to the Internet Explorer section.
Navigate to Start Navigation and remove the sound for this event by selecting "none."
Click OK.

OR

Start the registry editor (e.g., regedit.exe).
Navigate to the HKEY_CURRENT_USER\AppEvents\Schemes\Apps\Explorer\Navigating subkey.
Select the .current subkey.
Select Delete from the Edit menu.
Click Yes in the confirmation dialog box.

http://social.msdn.microsoft.com/forums/en-US/winforms/thread/e72b37d2-d20b-4a59-8560-24a10b17db97/

bir tablo uzerinden iliskili diger tabloyu guncelleme

UPDATE TABLE1
SET Column1 = (SELECT TABLE2.Column1
     FROM TABLE2
WHERE TABLE2.IDColumn = TABLE1.IDColumn)

update yayin
set ukod = s.ukod
     from yayin y, sayfa1$ s
where s.yayinno = y.yayinno

bir tablonun id alanina deger atamak

DECLARE @ID decimal
SET @ID = 0

DECLARE #cursor CURSOR FOR
(SELECT _ID FROM _TABLE)

OPEN #cursor
FETCH NEXT FROM #cursor

WHILE @@FETCH_STATUS = 0
BEGIN
UPDATE _TABLE
SET _ID = @ID + 1
WHERE CURRENT OF #cursor
SET @ID = @ID + 1
FETCH NEXT FROM #cursor
END

CLOSE #cursor
DEALLOCATE #cursor

sql server full-text search


sorun:
SQL Server encountered error 0x80070218 while communicating with full-text filter daemon host (FDHost) process. Make sure that the FDHost process is running. To re-start the FDHost process, run the sp_fulltext_service 'restart_all_fdhosts' command or restart the SQL Server instance.


çözüm:
EXEC sp_fulltext_service 'restart_all_fdhosts'


sorun devam ediyorsa:
sql server configuration manager --> sql full-text filter daemon launcher
çalıştığından emin ol.


sorun devam ediyorsa:
sql server configuration manager --> sql full-text filter daemon launcher
log on as değerinin sql server'ınki ile aynı olduğundan (local system, local service, network service) emin ol.


tabloya full-text index tanımlama:
tabloya sağ tık --> full-text index --> define full-text index...


full-text index kullanarak arama yapma:
select *
from Mevzuat
where contains (MevzuatAdi, 'YERALTI or DEVLET')



eğer query sonuç döndürmüyorsa:
full-text index'i silip yeniden yarat.

not: query'nin ilk çalışması yavaş olabilir. diğer çalışmalar hızlı olacaktır.

The backup set holds a backup of a database other than the existing database

RESTORE DATABASE yourdatabasename
FROM DISK = N'C:\yourbackupfilename'
WITH REPLACE

redirect page after embedded youtube video ends

<script type='text/javascript' src='swfobject.js'></script>

<div id='mediaspace'>
This video requires Javascript and Flash</div>

<script type='text/javascript'>
var player = null;
function playerReady(thePlayer) {
player = document.getElementsByName('ply')[0];
addListeners();
}
function stateMonitor(obj) {
if (obj.newstate == 'COMPLETED') {
// load a new page
window.location = 'http://www.google.com';
}
};
function addListeners() {
if (player) { player.addModelListener("STATE", "stateMonitor"); }
else { setTimeout("addListeners()", 100); }
}
// var s1 = new SWFObject('player-viral.swf', 'ply', '470', '320', '9', '#ffffff');
// s1.addParam('allowfullscreen', 'false');
// s1.addParam('allowscriptaccess', 'always');
// s1.addParam('flashvars', 'file=http://www.youtube.com/v/SXg1qpUiY7Y&autostart=true');
// s1.write('mediaspace');
</script>

<object id="thePlayer" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" name="ply" width="400" height="315">
<param name="movie" value="player-viral.swf" />
<param name="allowfullscreen" value="true" />
<param name="allowscriptaccess" value="always" />
<param name="flashvars" value="file=video.flv&image=preview.jpg" />
<embed
type="application/x-shockwave-flash"
id="player2"
name="player2"
src="player-viral.swf"
width="400"
height="315"
allowscriptaccess="always"
allowfullscreen="true"
flashvars="file=<%= VideoPath %>&image=preview.jpg&autostart=true"
/>
</object>

http://www.warriorforum.com/programming-talk/35546-redirect-another-url-after-embedded-youtube-video-ends-possible.html

enable remote connection on sql server 2008

http://www.linglom.com/2009/03/28/enable-remote-connection-on-sql-server-2008-express/

the trick is to enable tcp/ip protocol:

- On the left window, expand SQL Server Network Configuration -> Protocols for SQLEXPRESS. You see that TCP/IP protocol status is disabled.

- Right-click on TCP/IP and select Enable to enable the protocol.

html parser

http://htmlagilitypack.codeplex.com/

extension methods in linq

public static class MyExtensions
{
    public static IEnumerable SelectWhere(
     this IEnumerable source,
     Func filter)
    {
        var results = new List();

        foreach (var s in source)
            if (filter(s))
                results.Add(s);

        return results;
    }
}


    private double? GetConvertedPrice(RealEstate realEstate)
    {
        return realEstate.Price * exchangeRates[realEstate.PriceCurrencyId.Value - 1].Value;
    }




        var realEstates = _db.RealEstates.SelectWhere(re =>
                                                       (re.CategoryId == null || catId == null || re.CategoryId == catId)
                                                       && (re.TypeId == null || typeId == null || re.TypeId == typeId)
                                                       && (re.CityId == null || cityId == null || re.CityId == cityId)
                                                       && (re.DistrictId == null || districtId == null || re.DistrictId == districtId)
                                                       && (re.Price == null || priceMin == null || GetConvertedPrice(re) >= priceMin)
                                                       && (re.Price == null || priceMax == null || GetConvertedPrice(re) <= priceMax)
            );


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

jquery reference problem


sort a generic list

public struct SlideObject : IComparable
{
public int Id { get; set; }
public string Title { get; set; }
public string NavUrl { get; set; }
public string ImgUrl { get; set; }
public DateTime AddDate { get; set; }

public static Comparison AddDateComparison = (so1, so2) => so1.AddDate.CompareTo(so2.AddDate);

//public static Comparison AddDateComparison = delegate(SlideObject so1, SlideObject so2)
//{
// return so1.AddDate.CompareTo(so2.AddDate);
//};

#region IComparable Members

public int CompareTo(SlideObject other)
{
return AddDate.CompareTo(other.AddDate);
}

#endregion
}

http://dotnetslackers.com/community/blogs/simoneb/archive/2007/06/20/How-to-sort-a-generic-List_3C00_T_3E00_.aspx

http://www.codeproject.com/KB/linq/Article.aspx?aid=27834

export data to excel in asp.net

Page Language="C#" AutoEventWireup="true" EnableEventValidation="false"

public override void VerifyRenderingInServerForm(Control control) {
/* Confirms that an HtmlForm control is rendered for the specified ASP.NET
server control at run time. */
}

//Export to Excel from a GridView
protected void ExportToExcel() {
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("content-disposition", "attachment;filename=MyFiles.xls");

// for turkish support
Response.ContentEncoding = Encoding.GetEncoding("ISO-8859-9");
Response.Charset = "ISO-8859-9";

this.EnableViewState = false;

System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);

gvFiles.RenderControl(htw);

Response.Write(sw.ToString());
Response.End();
}

http://blogs.msdn.com/erikaehrli/archive/2009/01/30/how-to-export-data-to-excel-from-an-asp-net-application-avoid-the-file-format-differ-prompt.aspx

regular expression samples

\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)* email address abc@defg.com
^{3,50}$ at least 3 characters a25
(\d{3} ?)?\d{3} \d{2} \d{2} phone (212) 212 12 12
(\d{4}) 4-digit number 2010
^(\d{1,3}(\,\d{3})*|(\d+))(\.\d{1,2})?$ price 123,456.78
(?=.*\d) must contain at least one numeric character
(?=.*[a-z]) must contain one lowercase character
(?=.*[A-Z]) must contain one uppercase character
.{8,10} From 8 to 10 characters in length
\s allows a space

add timer to jquery coda slider

add this code row to coda-slider.js file:

var cycleTimer = setInterval(function (){$scroll.trigger('next')}, 5000);

failed to retrieve directory listing

solution : c:\windows\system32\inetsrv\inetpub.exe is the file you need to add to your exceptions in Windows Server 2008.

IIS 7.0, FTP 7, and Firewalls
FTP on Windows 2008 Server - Firewall Solution

conflict between asp.net scriptmanager with jquery

solution links :
http://encosia.com/2009/03/25/document-ready-and-pageload-are-not-the-same/
http://api.jquery.com/live/
http://encosia.com/2008/09/28/avoid-this-tricky-conflict-between-aspnet-ajax-and-jquery/

unrecognized configuration section connectionstrings

error : Unrecognized configuration section 'connectionStrings'

solution : change the Framework to version 2.0 in IIS (tab of ASP.NET).

linq : left join with linq

            var vehicles = (from vehicle in DB.Vehicles
                            join brand in DB.VehicleBrands on vehicle.BrandId equals brand.Id into data_b from b in data_b.DefaultIfEmpty()
                            join model in DB.VehicleModels on vehicle.ModelId equals model.Id into data_m from m in data_m.DefaultIfEmpty()
                            join type in DB.VehicleTypes on vehicle.TypeId equals type.Id into data_t from t in data_t.DefaultIfEmpty()
                            where
                                (brandId == null || vehicle.BrandId == brandId) &&
                                (modelId == null || vehicle.ModelId == modelId) &&
                                (typeId == null || vehicle.TypeId == typeId) &&
                                (priceMin == null || vehicle.Price >= priceMin) &&
                                (priceMax == null || vehicle.Price <= priceMax) &&
                                vehicle.IsDeleted == false && vehicle.IsActive == true && vehicle.IsSold == false
                            orderby vehicle.CreateDate descending
                            select new
                                       {
                                           vehicle.Id,
                                           vehicle.Title,
                                           b.BrandName,
                                           m.ModelName,
                                           vehicle.Price,
                                           vehicle.CreateDate,
                                           vehicle.PhotoPath
                                       });

            gvVehicle.DataSource = vehicles;
            gvVehicle.DataBind();

Could not deserialize data returned from server

If you should happen to see this error when calling Users.GetInfo() it's because facebook changed something in the way their hs_info is passed down and the C# API is not expecting nullable values.

Here is the fix:

recompile the binaries from source with the following members and their referencing properties set to set to int?

These are members of > Facebook.Schema.hs_info

private int? grad_yearField;
private int? hs1_idField;
private int? hs2_idField;

If you don't have the capability or need to get your site running ASAP.. i've attached the binaries with this change already compiled in.

~Lucas Smolic

File Attachments
recompiled_binaries.zip
Xsd2CodeSource.cs

http://facebooktoolkit.codeplex.com/WorkItem/View.aspx?WorkItemId=17036

facebook application notes

* Canvas Callback URL
debug yapabilmek için,
http://localhost:3681/Musicower.Web.Test/
'e ayarlarsın ve lokaldeki kodlar çalışır.
yayına almak için, sunucu adresine ayarlarsın;
http://212.154.37.195/Musicower/

t-sql: how to delete duplicate records

Method 1: SET ROWCOUNT


Syntax for SET ROWCOUNT is as follows:

SET ROWCOUNT { number | @number_var }
SET ROWCOUNT limits the sql server engine to process a specific number of rows. So the process stops after the defined number of rows are reached. The default value for ROWCOUNT is 0 which means no limit on the returning result set so all rows are returned. After a ROWCOUNT command is run and all processes are completed, you can also set the ROWCOUNT to 0 to turn off this option.

If we return back to our sample, in order to delete four times repeated rows, we can set the ROWCOUNT value to 3

SET ROWCOUNT 3
DELETE FROM Users WHERE FirstName = N'Elvis' AND LastName = N'Presley'
SET ROWCOUNT 0
-- (3 row(s) affected)
After running the above DELETE FROM command with SET ROWCOUNT statement, the last status of the table Users as below.



We are successfull to delete the identical rows with the row number 9 in the above picture.

If you want to delete the identical records automatically we can use a cursor. It is important that while you are declaring the cursor for dublicate rows, you should select the count of identical rows minus one, since we want one of the dublicated records exist in the table after delete processes.

You should also pay attention to the SET ROWCOUNT commands around the DELETE FROM command in the body of the cursor.

DECLARE @Count int
DECLARE @FirstName nvarchar(50)
DECLARE @LastName nvarchar(50)

DECLARE dublicate_cursor CURSOR FAST_FORWARD FOR
SELECT FirstName, LastName, Count(*) - 1
FROM Users
GROUP BY FirstName, LastName
HAVING Count(*) > 1

OPEN dublicate_cursor

FETCH NEXT FROM dublicate_cursor INTO @FirstName, @LastName, @Count

WHILE @@FETCH_STATUS = 0
BEGIN

SET ROWCOUNT @Count
DELETE FROM Users WHERE FirstName = @FirstName AND LastName = @LastName
SET ROWCOUNT 0

FETCH NEXT FROM dublicate_cursor INTO @FirstName, @LastName, @Count
END

CLOSE dublicate_cursor
DEALLOCATE dublicate_cursor

Method 2: TOP


A second method we can use while removing dublicate records from Users table is using the TOP expression in DELETE statement. With the release of SQL Server 2005, as an T-SQL enhancement TOP expression now takes a variable where else in SQL Server 2000 TOP was expecting a constant numeric value. This is very useful since if we decide to use a cursor, etc to delete all dublicates once, we may use a variable with the TOP expression.

If we return back to our original sample data in the Users table, we can run a similar command to remove two of the three identical records having firstname equal to Jane and last name equal to Fonda

DELETE TOP (2) FROM Users
WHERE FirstName = N'Jane' AND LastName = N'Fonda'
If you have not used the (n) syntax, you shoul get the following error; don't worry, just use the paranthesis.

Msg 102, Level 15, State 1, Line 2
Incorrect syntax near '2'.
You can guess that we can use this DELETE TOP combination within a cursor in order to remove all the dublicated records leaving only one of them in the sample table. Here is the cursor that we can use:

DECLARE @Count int
DECLARE @FirstName nvarchar(50)
DECLARE @LastName nvarchar(50)

DECLARE dublicate_cursor CURSOR FAST_FORWARD FOR
SELECT FirstName, LastName, Count(*) - 1
FROM Users
GROUP BY FirstName, LastName
HAVING Count(*) > 1

OPEN dublicate_cursor

FETCH NEXT FROM dublicate_cursor INTO @FirstName, @LastName, @Count

WHILE @@FETCH_STATUS = 0
BEGIN

DELETE TOP(@Count) FROM Users WHERE FirstName = @FirstName AND LastName = @LastName

FETCH NEXT FROM dublicate_cursor INTO @FirstName, @LastName, @Count
END

CLOSE dublicate_cursor
DEALLOCATE dublicate_cursor
Again I want to point to the issue that ROWCOUNT will not be considered in the next releases of SQL SERVER. You can find this information in the BOL on topics about ROWCOUNT and TOP. You can refer to ms-help://MS.SQLCC.v9/MS.SQLSVR.v9.en/udb9/html/50705caa-4d0a-490f-92a4-75ece96e0a54.htm for more information. I also copied the important note from BOL to here:

Using SET ROWCOUNT will not affect DELETE, INSERT, and UPDATE statements in the next release of SQL Server. Avoid using SET ROWCOUNT with DELETE, INSERT, and UPDATE statements in new development work, and plan to modify applications that currently use it. We recommend that DELETE, INSERT, and UPDATE statements that currently are using SET ROWCOUNT be rewritten to useTOP.


Method 3: Adding an IDENTITY column


A third method can be adding an identity column to the table in order to distinguish all rows from each other. Of course, if you do not have the permissions to alter the table in order to add a new column, this method can not be implemented.

Run the below sql command to add a new column to the Users table, which will also fill the newly added column Id with integer values in sequential order and will distinguish each record from its identical ones.

ALTER TABLE Users ADD Id int IDENTITY(1,1)
After you run the above command, Users table will be as below:



Now it is easy to delete dublicates by using the Id column. For example, for dublicates of row with Id 8, we can run the below command

DELETE FROM Users WHERE Id IN (2,10,12)
And now let's look how we can automatically delete dublicates in this situation. We can use a Common Table Expression (CTE) to make a change and use a CTE instead of using a cursor. Here is the CTE (common table expression) sample that will delete the dublicates in our Users table.

WITH Dublicates_CTE(FirstName, LastName, Id)
AS
(
SELECT FirstName, LastName, Min(Id) Id
FROM Users
GROUP BY FirstName, LastName
HAVING Count(*) > 1
)
DELETE FROM Users
WHERE Id IN (
SELECT Users.Id
FROM Users
INNER JOIN Dublicates_CTE
ON Users.FirstName = Dublicates_CTE.FirstName
AND Users.LastName = Dublicates_CTE.LastName
AND Users.Id <> Dublicates_CTE.Id
)
It is important to note that CTEs (Common Table Expressions) are also new enhancements in t-sql with the new release of SQL Server, SQL Server 2005. So the above sql statement will not run on SQL Server 2000 databases. For more samples and definition on CTEs you can read the article titled Common Table Expression.

After you have done, you can drop the identity column Id by running an ALTER TABLE command as shown below:

ALTER TABLE Users DROP COLUMN Id

http://www.kodyaz.com/articles/delete-duplicate-records-rows-in-a-table.aspx

youtube arama sonuclari tarayiciya gore degisiyor

chrome youtube'da aşapıdaki arama sonucunda şu uyarıyı yapıp video önerilerinde bulunurken:

" No videos found for “"David Bowie - Joe the Lion tam parça "” "

http://www.youtube.com/results?search_query=+%22David+Bowie+-+Joe+the+Lion+tam+parça+%22&exact_query=David+Bowie+-+Joe+the+Lion+tam+parça+

firefox ve ie7'de sonuç bulunamıyor:

" No videos found for “” "

ForeignKeyReferenceAlreadyHasValueException

Çözüm:

cover.OriginalSongId = song.SongId;

yerine,

cover.OriginalSong = song;

http://dotnetslackers.com/Community/blogs/bmains/archive/2009/05/21/linq-to-sql-error-foreignkeyreferencealreadyhasvalueexception.aspx

http://social.msdn.microsoft.com/Forums/en-US/linqprojectgeneral/thread/744b2c6a-ecb8-44bf-b72a-dc1b85b34342

If the association property is assigned a value you cannot change the foreign key field anymore, you must change the relationship by changing the assocition property. For example, using Customer and Order from Northwind sample database. If the 'Customer' property on an order is assigned a value you can no longer manually change the order's CustomerID field, since it must match the PK of the customer. You can, however, change the 'Customer' property directly, assigning it a new customer instance. This action will automatically update the CustomerID field to match.

The DELETE statement conflicted with the REFERENCE constraint

Delete Rule : Cascade

linq deleteonnull

An attempt was made to remove a relationship between a User and a User_UserRole. However, one of the relationship's foreign keys (User_UserRole.UserID) cannot be set to null.

[Association(Name="User_User_UserRole", Storage="_User", ThisKey="UserID", OtherKey="UserID", IsForeignKey=true, DeleteOnNull = true)]

getting a flash object to the bottom

The Flash object is a windowed thingie; it lies above the browser in its own window. The fix is to compile it with wmode="opaque". If it's not yours to compile, use . If you're using the embed element, add the attribute wmode="opaque".

http://forums.devshed.com/html-programming-1/positioning-a-layer-above-a-flash-object-412427.html

jquery autocomplete cache problem

You have to make a little changes in autocomplete.js.

Search for "*if (data && data.length*)" condition which is inside "request"
function. Add this code before the *if * condition

if(data)
data.length=0;

http://www.mail-archive.com/jquery-en@googlegroups.com/msg80627.html

Cannot remove an entity that has not been attached

You are using two different context. One retrieves it, the second tries to delete it.

http://forums.asp.net/p/1475529/3430701.aspx#3430701

adding css file dynamically

protected void Page_Init(object sender, EventArgs e)
{
// Define an HtmlLink control.
HtmlLink myHtmlLink = new HtmlLink();
myHtmlLink.Href = "~/StyleSheet.css";
myHtmlLink.Attributes.Add("rel", "stylesheet");
myHtmlLink.Attributes.Add("type", "text/css");

// Add the HtmlLink to the Head section of the page.
Page.Header.Controls.Add(myHtmlLink);
}

http://www.aspdotnetfaq.com/Faq/How-do-I-dynamically-add-CSS-file-for-ASP-NET-ASPX-page.aspx

webbrowser documentcompleted is raised more than once

çözüm:
webbrowser'ın readystate özelliği complete ise işlem yap.

private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
    if (webBrowser1.ReadyState == WebBrowserReadyState.Complete)
    {
         // do something
    }
}

not: saatlerce bu sorunla uğraştım. algoritmamda bir hata olduğunu düşünüyordum. sonra "acaba bu bir bug olabilir mi" diye google'a danıştım ve aramam sadece ve sadece "webbrowser documentcompleted" sözcüklerinden oluşuyordu. çıkan sonuçlardan dördüncüsünde yanıtı buldum. ve bu durum bana şunu düşündürdü:
eğer msdn'den webbrowser kontrolünü veya onun documentcompleted event'ini incelemiş olsaydım, bu bilgiye zaten ulaşmış olacaktım. hazıra konmaya çalışmak işte bazen tam tersine böyle zaman kayıplarına yol açıyor. bu da bana ders olsun =/

not2: webBrowser1_DocumentCompleted event'inde exception oluştuğunda uyarı verilmiyor. try catch ile kendin yakalamalısın.

URL Escape Characters

http://community.contractwebdevelopment.com/url-escape-characters

http://www.blooberry.com/indexdot/html/topics/urlencoding.htm

linq : insert into middle table

var band = new Band {Title = bandName};
if (_db.Bands.Where(b => b.Title == bandName).Count() == 0)
{
_db.Bands.InsertOnSubmit(band);
_db.SubmitChanges();
}

1. sadece band_genre tablosuna kayıt yapar:

var bandGenre = new Band_Genre();
bandGenre.BandId = band.BandId;
bandGenre.GenreId = _currentGenre.GenreId;
_db.Band_Genres.InsertOnSubmit(bandGenre);
_db.SubmitChanges();


2. band_genre, band ve genre tablolarının tümüne kayıt yapar. (yani aynı band ve genre birden fazla kez eklenebilir.):

var bandGenre = new Band_Genre {Band = band, Genre = _currentGenre};
_db.Band_Genres.InsertOnSubmit(bandGenre);
_db.SubmitChanges();

related jquery autocomplete controls

Error Handling in Asp.Net


All applications should have error handling. This we all know. We can't always be notified of an unhandled error (and usually aren't) when one occurs on a client's machine. The advantage we have on the Web is that we can always be notified when an unhandled error occurs. With the advent of ASP.NET, there are some great new ways to handle errors. There are some differences in .NET in not only how to handle the error, but how the information is provided to you. For example, classic ASP uses Server.GetLastError to return an ASPError object. You can and should still use Server.GetLastError in .NET, but this now returns a type System.Exception. I must give Microsoft credit for making almost everything consistent in .NET, which is quite a welcome change.
download source code
The Problem
Errors will occur in our applications. We try to trap for most errors using try-catch blocks (or the only possibility in tradional ASP 'on error resume next'); however, we usually don't cover every possible exception. What happens when an unhandled error occurs? Usually the user is brought to IIS's default error pages (usually located in c:\winnt\help\iishelp\common). The downsides are you have no idea when this occurs and the page doesn't have your site's look and feel. Errors are a development fact, but we strive to eliminate or handle them gracefully. With this in mind, we need to know:

  1. When an error occurs
  2. Where it occurred
  3. What the error is
Having a central location such as the event log, database or some other log file to log errors is essential for debugging this problem later (I call this forensics debugging).
IIS provides great error-handling capabilities (see my article at http://www.15seconds.com/issue/020821.htm). There are some problems with these though. Sometimes we know an error will occur, and we can't always trap for it in a nice way without overriding the site's (done in the IIS custom errors Page; see the article mentioned above) default error redirection page. For example, upon access to a resource that requires authentication, we may need to redirect to an application's login page. Also, a very common problem exists with Web hosts. If you have a hosted Web site, you usually have no control over its IIS configuration. Thus, setting up custom error pages can be next to impossible in traditional ASP. This is elimiated with ASP.NET, as you will learn as you read on.
The Solution
For such a list of problems, the solution is actually pretty simple. There are three places in ASP.NET to define what happens to these unhandled errors.

  1. In the web.config file's customErrors section.
  2. In the global.asax file's Application_Error sub.
  3. On the aspx or associated codebehind page in the Page_Error sub.
The actual order of error handling events is as follows:

  1. On the Page itself, in the Page_Error sub (this is default, you can name it anything because it specificed Handles MyBase.Error)
  2. The global.asax Application_Error sub
  3. The web.config file
Note: To cancel the bubbling up of the error at anytime for the Page_Error or Application_Error, call the "Server.ClearError" function in your sub. Each method has its own uses, as I will explain.
When an exception occurs in your application, it should be an object inherited from type System.Exception, and as such will have the following public members:

HelpLinkGets or sets a link to the help file associated with this exception.
InnerExceptionGets the Exception instance that caused the current exception.
MessageGets a message that describes the current exception.
SourceGets or sets the name of the application or the object that causes the error.
StackTraceGets a string representation of the frames on the call stack at the time the current exception was thrown.
TargetSiteGets the method that throws the current exception.

Using the Page_Error or OnError sub
The first line of defense in error handling happens at the page level. You can override the MyBase.Error sub as such: (Visual Studio will complete the code if you click either the Overrides or BaseClass events in the editor). The two functions you can use (one or the other, both will not work as only one will get called)

    Private Sub Page_Error(ByVal sender As Object, ByVal e As System.EventArgs) 
Handles MyBase.Error
    
    End Sub

Or you can use this one:
  
 Protected Overrides Sub OnError(ByVal e As System.EventArgs)

    End Sub

Handling errors in these subs is a simple process. Just call Server.GetLastError to return the error. If you want to redirect to a specific page here you can just call Response.Redirect ("HandleError.aspx") or whatever your page may be. This method of handling errors is good for several reasons.
  1. If you need to override the Application_Error or the customErrors setup in the web.config file
  2. If each page must implement it's own error handling If you need to log specific information and then carry on, just code for your logging or whatever here, and that is all. If you need to cancel the error processing here (so it doesn't go to the Application_Error or customErrors) simply call Server.ClearError in this sub.
Using the global.asax File
The global.asax file contains the next line of defense against errors. When an error occurs, the Application_Error sub is called. This location happens to be my favorite place to log errors because it is the most functional. For most of my applications in .NET, I don't handle too many custom errors at the page level. I handle them at the application level. The only two locations that actually give you access to Server.GetLastError are in the Page_Error and Application_Error subs.
After the Page_Error is called, the Application_Error sub is called. Here you can also log the error and redirect to another page. I won't explain anything else about it because it is basically the same as the Page_Error but happens to be at the application level rather than the page level.
Using the web.config File
The customErrors element of the web.config file is the last line of defense against an unhandled error. If you have other error handlers in place, like the Application_Error of Page_Error subs, these will get called first. Provided they don't do a Response.Redirect or a Server.ClearError, you should be brought to the page(s) defined in the web.config. In the web.config file, you can handle specific error codes (500, 404, etc), or you can use one page to handle all errors. This is a major difference between this method and the others (although you can emulate this by doing various Response.Redirects using the other methods). Open up your web.config file. The customErrors section uses this format:


   


Here is some important information about the "mode" attribute:"On" specifies that custom errors are enabled. If no defaultRedirect is specified, users see a generic error.
"Off" specifies that custom errors are disabled. This allows display of detailed errors.
"RemoteOnly" specifies that custom errors are shown only to remote clients, and ASP.NET errors are shown to the local host. This is the default.
By default, the section looks like this when you create a Web application.



This will show a generic page to users. To redirect it to one of your own pages, you would change it to this:



Now all errors that occur will be brought to the error.htm page.To handle specific errors, and redirect to the error page for everything else you can specify the error code you want specially handled like so:


    
    
    
 

There is a problem here with this solution. Once the redirect is done, your error information is no longer available on the redirected page. This is because IIS (via the .net framework) performs a plain old GET request to the error page and does not do a "Server.Transfer" like the built-in IIS error handling does.The only information available to you at this time is the URL that caused this error to be raised. This is located on the querystring as "aspxerrorpath": http://localhost/ErrorHandling/error500.aspx?aspxerrorpath=/ErrorHandling/WebForm1.aspx. The only places this information is available is the two methods described above.
Another interesting point about the above customErrors element is that you can specify different error pages for different subdirectories.
For this example, let's say you have a directory named "Customers" off of your root directory that contains a branding specific for logged in customers but is not in its own application. As such you want to define a different set of pages for errors. Please note that these pages specified in the "redirect" attribute are relative to the "Customers" subdirectory and not the root path of your site. I have also included a security rule which says only MYDOMAIN\Customers can access these files. You can define rules for these errors in the web.config file:


   
      ...
      ...
   

   
   
      
   
  
  
  
  
        
 
  
  
 
      
   

Note: One thing I found in development is there seems to be an inheritance order for these errors. What I mean by this is if you have a 500 error defined for the root site, but none defined for the customers directory, but you DO have a defaultRedirect set for the customer directory, the 500 handler defined at the root level will be called. So if a parent directory has a handler.Using the Code
I have created an application with settings, so you can get an idea of how to configure your code. In the zip file there is a solution containing two projects.
The first is a Web project that has some buttons to cause different errors. It also shows an example of handling the error through the page, global.asax, and web.config file. There will also be a DotNetErrorLog.sql you can run in query analyzer to create a database (and user) to start logging errors ASAP.
You will notice in my web.config I have the following:

 
   
   
   
   
   
      
  

This is where I keep specific settings for an application. You do not have to worry about keeping it in the registry, and this is great for moving your applications between development, integration, and production environments (if you are blessed with that). For better security, you can incorporate the encryption classes in .NET to encrypt the database connection info and store that information in the web.config rather than the plain text connectstring, but that obviously isn't the purpose of this article. The settings pretty much are as follows:
  1. To log to a db:
    1. ErrorLoggingLogToDB - Set to "True" to tell the app you want to log info into the db
    2. ErrorLoggingConnectString - The connect string to connect to the database to store errors
  2. To log to the event log:
    1. ErrorLoggingLogToEventLog - Set to "True" to tell the app you want to log error information to the event log
    2. ErrorLoggingEventLogType - The name of the event log to log to (ex. System, Application, etc etc.). You can even create your own log just for web errors too, which could be ideal for large sites!
  3. To log to a text file:
    1. ErrorLoggingLogToFile - Set to "True" to tell the app you want to log info to a text file
    2. ErrorLoggingLogFile - The path of the file to log errors to
Here is a sample of what to expect in the log file or the event log:
-----------------12/20/2002 3:00:36 PM-----------------
SessionID:qwyvaojenw1ad1553ftnesmq
Form Data:
__VIEWSTATE - dDwtNTMwNzcxMzI0Ozs+4QI35VkUBmX1qfHHH8i25a/4g4A=
Button1 - Cause a generic error in the customer directory
1: Error Description:Exception of type System.Web.HttpUnhandledException was thrown.
1: Source:System.Web
1: Stack Trace: at System.Web.UI.Page.HandleError(Exception e)
1: at System.Web.UI.Page.ProcessRequestMain()
1: at System.Web.UI.Page.ProcessRequest()
1: at System.Web.UI.Page.ProcessRequest(HttpContext context)
1: at System.Web.CallHandlerExecutionStep.Execute()
1: at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
1: Target Site:Boolean HandleError(System.Exception)
2: Error Description:Object reference not set to an instance of an object.
2: Source:ErrorHandling
2: Stack Trace: at ErrorHandling.WebForm2.Button1_Click(Object sender, EventArgs e) in C:\Inetpub\wwwroot\ErrorHandling\Customers\WebForm2.aspx.vb:line 26
2: at System.Web.UI.WebControls.Button.OnClick(EventArgs e)
2: at System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
2: at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
2: at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
2: at System.Web.UI.Page.ProcessRequestMain()
2: Target Site:Void Button1_Click(System.Object, System.EventArgs)

First, the date and time is logged. Secondly, the user's session id is logged. These session ids look quite different than classic asp session ids which were all numeric. The next line contains any form data on the page. This is great especially if they filled in information on the page, and that information caused your app to bomb. All of the lines with "1" in front of it are the first error. This contains the description, source, stack track and what function caused the error. Starting at the "2"s, this is the error generated before #1. Error #2 here is the "InnerException" to error one. This is a new idea here (from classic asp or vb) since it allows error information to have a hierarchy to it. Some errors can be trapped, and rethrown with a new error giving more specific information.
Another idea is to use the SMTP component to e-mail you when an error occurs, enabling you to be proactive for errors. This would be a simple addition to the appSettings section above to hold an e-mail address and simply use the CErrorLog.GetErrorAsString to get the text needed to send an e-mail out.
Special Notes
- I read somewhere on the Net that someone recommended taking the error number and then looking up the proper message in a database to display to the user.
I like this idea; however, the downside is if an unexpected database error occurs, then you have just lost your errorpage ability.
- A quick note about performing a redirection inside a try-catch block:
If you want to redirect to a page within a given try-catch block in your code (custom error handlers included), understand this can fail under certain circumstances because a Response.Redirect calls Response.End within its internal code, creating problems. You must call Response.Redirect("pagename.aspx",False") which specifies the redirect call and will not call Response.End, thus, preventing the exception.
Good luck and happy error logging!

http://15seconds.com/issue/030102.htm

asp.net security tools

Microsoft güvenlik alanında ki vizyonunu değiştirdikten sonra, geliştiricilerin güvenli kod yazmasına ciddi şekilde yarar sağlayan bir çok araç çıkardı. Özellikle ASP.NET ve Visual Studio .NET için dağıttığı araçlar bir çok web uygulamasının güvenli ve belli bir kalitede çalışmasına önayak oldu. Teşekkürler derim.

Bir çok uygulamada benimde kendi açıklarımı kapatmamı sağlayan bu uygulamaları hatırlatmak istedim/isterim. (Gerçi bu bahane. Arayınca kolay bulmak için yazıyorum ^_^)

Microsoft Source Code Analyzer for SQL Injection
ASP scriptlerinizde Sql Injection sömürüsüne olanak veren kod olup olmadığını kontrol eden güzel bir uygulama.

Microsoft Anti-Cross Site Scripting Library V1.5
Cross-Site Scripting (XSS) 'e karşı daha güvenli kod yazmanıza olanak tanıyan .NET Sınıf kütüphanesi.

Microsoft Threat Analysis & Modeling v2.1.2 (İzlemelik)
Uygulamalarınızda güvenli olmayan Threat leri ve risk taşıyan metodları analiz edip ürününüzü daha güvenli tasarlamanıza yarayan bir araç.

XSS Detect Beta Code Analysis Tool
ASP.NET web projenize debug anında entegre olup XSS sömürüsüne olanak veren kod parçalarını gösterir ve düzeltmeniz için uyarır. Başarılı bir çalışma VS.NET 2005 için bir eklendi ama VS.NET 2008'de çalışması için Microsoft.ACE.XSSDetect.AddIn dosyasını açıp version node'unu 9.0 yapmanız gerekir.



http://www.oguzhan.info/bak.asp?458/ASP.NET+i%E7in+g%FCvenlik+ara%E7lar%FD.

Web Uygulamalarında Tehdit Modelleme ve Güvenlik


Tehdit Modelleme
.NET ve ASP.NET tarafından sağlanan güvenlik çatısı güçlü olsa da bazı temel prensipleri akılda tutmak ve bu özellikleri doğru bir şekilde ve doğru zamanda kullanmak gereklidir. Bunun için güvenlik öğelerini, uygulama geliştirmenin ilk aşamasından itibaren kullanmak gereklidir.

Güvenli (secure) mimariler dizayn etmek için uygulama ortamının çok iyi bilinmesi gerekir. Mesela uygulamamıza kimler erişecek ve muhtemel kötü niyetli ataklar nereden gelebilir vb. Dolayısıyla güvenli uygulama mimarileri ve dizaynları geliştirmede en önemli faktör, çevresel öğeleri çok iyi anlamaktır. Bunlar kullanıcılar, uygulamadaki giriş noktaları ve muhtemel atak noktalarıdır.

Bu yüzden Tehdit modelleme, günümüz yazılım mimarisinde önemli bir yer teşkil etmektedir. Tehdit modelleme (Threat modelling) muhtemel tehditler, bu tehditleri önem sırasına koyma ve sonra bu tehditleri temel alanhafifletme tekniklerine (mitigation techniques) karar verme üzerine uygulamamızın öğelerini analiz etmenin yapısal bir yoludur. Tehdit modelleme başka bir yönden de önem arz etmektedir. Bildiğimiz gibi bütün potansiyel tehditler, authentication ve authorization gibi güvenlik teknolojileri ile hafifletilemiyor. Bir başka deyişle bazı tehditler teknik yollarla çözüme kavuşturulamıyor. Mesela bir bankanın online şubesi, web sitesi üzerindeki trafiği güvenlik altına almak için SSL kullanıyor (Secure Socket Layer). Fakat kullanıcı, sayfanın bankanın gerçek sayfası olduğunu, bir hacker"ın sahte sitesi olmadığını nasıl anlayacak? Bunun tek bir yolu var: SSL kanalını kurmak için kullanılan sertifikaya bakmak. Ancak her kullanıcının bunun farkında olması düşük bir ihtimaldir; dolayısıyla kullanıcıları bilgilendirmeliyiz. Bu senaryodakine benzer hafifletme teknikleri, birer güvenlik teknolojisi değillerdir. Bu, bütün kayıtlı (registered) kullanıcıların sertifikaya nasıl bakmaları gerektiğini bildiklerinden emin olmayı gerektirir (Tabi ki onları bunun için zorlayamayız; fakat bilgileri doğru şekilde dizayn edersek bir çoğuna bunu yaptırabiliriz). Tehdit modelleme, sadece teknik konuları değil bu gibi durumları belirlemeye yardım eden bir analiz metodudur.
Güvenli kod yazmanın temel prensipleri

Kullanıcıların kontroller vasıtasıyla yaptıkları girişlere asla güvenilmemelidir... Tersi ispatlanana kadar bütün kullanıcılar birer şeytandır prensibini de unutmamak gerekir. Dolayısıyla girişler, çok kuvvetli bir şekilde doğrulanmalıdır (validation). En doğru olan, sadece girilmesi gereken değerlere izin vermektir.

SQL ifadeleri yazarken asla string birleştirme kullanılmamalıdır... Sql"den iğne yemek istemiyorsanız (sql injection) her zaman parametrelendirilmiş sorgular kullanılmalısınız. Aynı zamanda sql cümlelerin olduğu yerlerde try-catch bloğu sonucu kullanıcıya verilecek hata mesajında kendi özel mesajımızı kullanmak daha güvenlidir; çünkü Exception ya da Exception türevi sınıfların Message özelliği ile kullanıcıya veritabanımız hakkında bilgi gösterilebilir.
Kullanıcıdan alınan bilgiler, doğrulanmadan ve encode edilmeden; yani doğrudan web sayfasında gösterilmemelidir... Kullanıcı bazı HTML parçaları girebilir (mesela bir script). Bu yüzden her zaman HttpUtility.HtmlEncode() kullanarak < ve > gibi karakterlerden kaçmakda fayda vardır. Alternatif olarak bu geçerlilik kontrolünü yapacak bir web kontrolü kullanılabilir.
Sayfanın gizli alanlarında (hidden field) önemli, değerli, iş bilgisi taşıyan ya da akışı etkileyecek veri saklamamak gerekir. (Gizli alanlar tarayıcıdaki kaynak sayfaya bakılarak kolayca görülebilir, değiştirilebilir, kaydedilebilirler. Ardından da tarayıcı eklentileri (browser plug-in) ile mail gönderir gibi sunucuya gönderilebilirler)
View-state içerisinde önemli, kritik veri saklanmamalıdır (Çünkü view-state, bir gizli alandır. Kolayca decode edilebilir. Bu arada eğer sayfada @Page etiketinde EnableViewStateMac = true yapılırsa view-state şifrelenir).
Cookie"ler korunmalıdır... Forms authentication kullanılırken cookie"ler olabildiğince geç oluşturulup ihtiyaç kalmadığında silinmesi için timeout süresine sahip olmalıdır.
SSL kullanılmalıdır... Eğer web sitemiz, genel olarak hassas veriler içeriyorsa bütün siteyi SSL kullanarak koruma altına almak gerekir. Ayrıca direk SSL tarafından korunamayan resim ve diğer dosyaları da korumayı unutmamak lazım.

ASP.NET GateKeeper"ları ve Sorumlulukları


Uygulamamızın güvenliğini artırmanın güzel bir yolu, yerinde birçok bileşenle güvenliği sağlamaktır. Gatekeepers (takipçiler, koruyucular), güvenlik altyapısına bir yol bir boru hattı modeli yerleştiren kavramsal bir oluşumdur. Bu model, güvenliği artırmamıza yardımcı olur. Gatekeeper modeli şunu savunur ki; uygulamaya gerektiğinden fazla güvenlik mekanizmaları koymak gerekir. Bu mekanizmalardan her birine güvenlikle ilişkili bazı koşullara zorlamaktan sorumlu gatekeeper adı verilir.Eğer gatekeeperlardan biri başarısız olursa, hacker kaynaklara giden yoldaki diğer gatekeeper"la karşılaşacaktır. Ne kadar çok gatekeeper varsa, hacker"ın hayatı o kadar zorlaşır. Bu model, güvenli uygulamalar geliştirmek için zorunlu prensipleri desteklemektedir: Olabildiğince güvenli ol, hacker"ların hayatını olabildiğince zorlaştır. Yolun sonunda kaynaklara ulaşmak için gereken gatekeeperlar aşıldığında belki sadece sayfamızın kodları vardır, ancak yine de bu güvenlik prensipleri uygulanmalıdır. Bu şekilde merkezi bir güvenlik bileşeni uygulamak iyi bir fikir olabilir. Aynı şeklide iş katmanı da güvenli hale getirilebilir. ASP.NET uygulama altyapısı, bunu güzel bir şekilde uygulamaktadır.
Bir web sitesinde güvenliği uygulamanın yolları genelde aynıdır (Ayrıca tehdit modellemede bizim belirleyeceğimiz seviyeler bunlara eklenebilir).

Authentication : Öncelikle kullanıcıların kimliklerini doğrulamak gereklidir. Authentication şu soruyu sorar: Uygulamayı kullanan kim?
Authorization : Uygulamamızla çalışanın kim olduğunu öğrendikten sonra o kullanıcının hangi operasyonları gerçekleştirebileceğini ve hangi kaynaklara erişebileceğine karar vermek gereklidir. Yani authorization şu soruyu sorar; Senin geçiş iznin ne?

Güvenilirlik : Kullanıcı uygulama üzerinde çalışırken kimsenin kullanıcı tarafından işlenen hassas verileri görmediğinden emin olmak gerekir. Bu yüzden kullanıcı tarayıcısı ile web sunucumuz arasındaki kanalı şifrelemek gerekir (SSL). Dahası, arka plandaki verileri de şifrelemek gerekir. Mesela kullanıcı makinesine atılan cookieleri... Aynı zamanda veritabanı yöneticisi ve uygulamanın yayınlandığı (host edildiği) şirketin çalışanlarının da görmemesi için verileri şifrelemek gereklidir.

Tutarlılık : Tarayıcı ve sunucu arasında gidip gelen verinin illegal aktörler tarafından değiştirilmediğinden emin olmak gerekir. Bu tarz tehditleri hafifletmenin bir yolu dijital imza kullanmaktır.

ASP.NET, authentication ve authorization için bize basit bir altyapı sunar. Ayrıca .NET Framework ile gelen temel sınıf kütüphanesinde, System.Security isim alanı altında veriyi şifreleme ve imzalama için bazı sınıflar bulunmaktadır.

Authentiction

ASP.NET"de 4 tür kimlik doğrulama sistemi mevcuttur. Bunlar :

1) Windows authentication
2) Forms authentication
3) Passport authentication
4) Custom authentication

Mesela windows işletim sistemi, login olan her kullanici için 96-bit bir numara kullanır, buna SID (Security identifier) denir. Bütün authentication çeşitleri, sunucuya talepte bulunan kişinin kim olduğunu bilmemizi sağlar ki bundan kişiselleştirme için faydalanılabilir. Çünkü kimlik (identity) bilgisini web sayfasında kişiye özel karşılama mesajı göstermek için veya sayfanın görünüşünü değiştirmek için kullanabiliriz. Yine de kullanıcının uygulama içerisinde yapacaklarını kısıtlamak için authentication yeterli değildir. Bunun için authorization gereklidir.
Güvenilirlik ve Uyumluluk için Şifreleme
Güvenilirlik (Confidentiality), verinin ağ (network) üzerinde sunucu ve istemci tarayıcısı arasında gidip gelirken ya da bir veri kaynağına kaydedilirken başka kullanıcılar tarafından görülmemesidir.
Uyumluluk (Integrity) ise, yine ağ (network) üzerindeki ya da veri kaynağına kaydedilen verinin başka kullanıcılar tarafından değiştirilmediğinden emin olunmasıdır. Her ikisi de şifreleme (encryption) tabanlıdır. Şifreleme, veriyi karıştırmak, dolayısıyla bir kullanıcı tarafından okunmasını engellemek demektir. ASP.NET"de şifreleme, authentiction ve authorization"dan tamamen farklı bir özelliktir. Şifrelemeyi tek başına da, diğer özelliklerle bir arada da kullanabiliriz. Bir web uygulamasında şirelemeyi iki sebebten dolayı kullanmak isteyebiliriz:

1. Ağ üzerindeki verinin iletişimini korumak için: Mesela internet ortamında bir e-ticaret sitesinden alış-veriş yaparken bu ortamda bulunabilecek bir dinleyicinin (eavesdropper) kredi kartı no"mu okuyamadığından emin olmak isteyebilirim. Endüstriyel standartların yaklaşımına göre bunun çözümü SSL (Secure socket layer)"dir. SSL aynı zamanda tutarlılığı sağlamak adına dijital imza da sağlamaktadır. SSL, ASP.NET tarafından sağlanmaz, bu IIS"e entegre edilebilecek bir özellikir.
2. Veritabanı ya da bir dosyadaki kalıcı bilgileri korumak için:  Mesela gelecekte kulanmak üzere  kullanıcının kredi kartı no"sunu veritabanına kaydetmek istiyoruz. Bunu açık metin (plain text) olarak kaydedebilmemize rağmen, çok da iyi bir fikir değildir. Bunun yerine veritabanına kaydetmeden önce .NET framework tarafından bize sağlanan tipler yardımıyla veri şifrelenebilir.
Şu ana kadar anlatılanları bir araya getirirsek :
Kullanıcı bir siteye girdiğinde isimsiz bir kullanıcıdır (anonymous user). Yani uygulamamız gelenin kim olduğunu bilmez ve bu onu ilgilendirmez. Onu doğrulamadığımız (authenticate etmediğimiz) sürece de öyle kalacaktır. Varsayılan olarak isimsiz kullanıcılar bütün ASP.NET web sayfalarına erişebilirler. Fakat isimsiz erişimi olmayan bir siteye girildiği zaman şu aşamalar gerçekleşir:
1) Talep web sunucusuna gönderilir. Bu aşamada kullanıcının kimliği (identity) bilinmediği için ona login olması söylenir. (Bunun için özel bir web sayfası hazırlanabilir) Login sürecindeki ayrıntılar, authentication türüne bağlı olarak değişir.
2) Kullanıcı güvenlik bilgilerini verir ve ardından eğer form authentication kullanılıyorsa uygulamamız tarafından, windows authentication kullanılıyorsa IIS tarafından kontrol edilir.
3) Eğer bilgiler doğruysa kullanıcı talep ettiği sayfaya yönlendirilir. Verilen bilgiler doğru değilse kullanıcı yeniden log-in sayfasına yada Erişim reddedildi mesajı içeren bir web sayfasına yönlendirilir.
Kullanıcı sadece belli kullanıcılara ya da belli role sahip kullanıcılara açık bir web sayfası talep ederse yukarıda anlatılan aynı süreçten geçer fakat bu sefer fazladan bir adım vardır. Kullanıcı eğer bilgilerini doğru girmişse, talep ettiği sayfaya giriş hakkı olup olmadığı da kontrol edilir. Bu da sürecin authorization kısmıdır. Eğer kullanıcının talep ettiği kaynağa hakkı yoksa Erişim reddedildi mesajı içeren bir web sayfasına yönlendirilir.


http://www.bilgininadresi.net/Madde/791/Web-Uygulamalarında-Tehdit-Modelleme-ve-Güvenlik

lightbox ile onay penceresi açmak

1. notice/details.aspx'e bir hyperlink ekle.
2. navigateurl'ine notice dizinindeki delete.aspx'i
delete.aspx?nid=[noticeid]&rurl=[redirecturl]
biçiminde ver.

javascript tips tricks

1. fonksiyonu kullanılan js kütüphanesine, bu fonksiyondan önce referans verilmelidir:
kütüphane:
script src="js/jquery-1.3.2.js" type="text/javascript"

fonksiyon:
script type="text/javascript"
$(document).ready(function() {
...
});
/script

2. script type="text/javascript" src=' ResolveUrl("~/Scripts/jquery-1.2.6.min.js") '

add html link to dropdownlist

script type="text/javascript" language="javascript"
function JumpToIt(list, url) {
var newPage = url + list.options[list.selectedIndex].value
if (newPage != "None") {
// location.href = newPage
window.open(newPage)
}
}
/script


public bool AddHtmlLink { get; set; }
public string HtmlLinkUrl { get; set; }


if (AddHtmlLink)
       DropDownList1.Attributes.Add("onChange", "JumpToIt(this, '" + HtmlLinkUrl + "')");

http://www.mcfedries.com/JavaScript/linklist2.asp

Making sure Lightbox still works in Ajax UpdatePanel


I recently updated the homepage portfolio section with an Ajax filtering dropdown, allowing readers to filter my portfolio with different technologies and themes. However, that caused my old lightbox effect to lose ground somehow. After days of debugging, I found a way to deal with it, that is I had to manually reinstantiate the lightbox object on page load (clientside), because whenever Ajax fires up a postback, it wipes of the Lightbox entity that was created.

<script type="text/javascript">
    function pageLoad() {
        $('#gallery a.image-thumb').lightBox({ fixedNavigation: true });
    }
script>

yani:

script type="text/javascript"
$(document).ready(function() {
$("a[rel='example1']").colorbox();
});
/script

ek olarak;

script type="text/javascript"
function pageLoad() {
$("a[rel='example1']").colorbox();
}
/script

yazmak gerekecek.

http://www.alectang.com/Blog/Archive/2009/09/17/Making-sure-Lightbox-still-works-in-Ajax-UpdatePanel-53.aspx

http://stackoverflow.com/questions/520645/jquery-datepicker-ms-ajax-updatepanel-doesnt-work-after-post-back

http://www.mail-archive.com/jquery-en@googlegroups.com/msg37808.html

ASP.NET Ajax Control toolkit – Common Problems


Problem 1 : This page is missing a HtmlHead control which is required for the CSS stylesheet link that is being added. Please add
Solution :  make your HEAD tag  to
problem 2 : The Controls collection cannot be modified because the control contains code blocks (i.e. ).
Solution:  Looks like you are using <% tags in your HEAD section code like Javascript code etc…. To fix it wrap your head section with

  and

colorbox jquery çakışması

adım 1:

script type="text/javascript"
$j = jQuery.noConflict();
script

adım 2:

$j("a[rel='example1']").colorbox();

http://www.cemkefeli.com/post/2009/10/12/ColorBox-kullananlar-icin-jQuery-cakismasinin-cozumu.aspx

not: şu anki projede çalışmadı! (script.js dosyası kullanan jquery tab bulunuyor projede ve colorbox'ın ve autocomplete'in çalışmasını önlüyor)

invalid postback or callback argument

Invalid postback or callback argument. Event validation is enabled using in configuration or in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.

çözüm:

pages enableeventvalidation="true"



ilginç durumlar:
1. bu hata bir sunucuda oluşmazken, bir diğerinde oluştu.
2. hata chrome'da görülmezken, ie7'de görülüyordu.

masterpage'e css ve js bağlama

js ve css dizinleri kök dizinde.


1. durum:

Default.aspx ile MasterPage.master kök dizinde.
MasterPage'deki css ve js dosyaları şu şekilde bağlanmalı:


href="css/colorbox.css"
src="js/jquery.colorbox-min.js"


html çıktı: (Default.aspx)
href="css/colorbox.css"
src="js/jquery.colorbox-min.js"


2. durum:
Default.aspx kök dizinde, MasterPage.master kök dizindeki Shared dizininde. Yani bir alt dizinde.

href="../css/colorbox.css"
src="js/jquery.colorbox-min.js"


html çıktı: (Default.aspx)
href="css/colorbox.css"
src="js/jquery.colorbox-min.js"

Dikkat edilirse, js'nin path'i değişmedi.

derived object'e databinding'de erişmek

gridview'e user list'i bağlarken, user'dan türemiş company nesnesinin (user'da olmayan) name özelliğine nasıl erişilir?
benim bu user nesnesini company'ye dönüştürmem gerek. fakat eval("xxx")'ten başka bir yol bilmiyorum özelliklere veya nesnelere erişim için.

kayıt silmede foreign key engeli nasıl aşılır

foreign key nedeniyle silinemeyen kayıtlar için şu bir çözüm olabilir mi:

1. durum:
örneğin product için en fazla 1 category belirtilebilecek bile olsa, bunu product_category tablosunda tutarak, istendiğinde category'yi silebiliriz ve product çekilirken category çekilmez, bu da herhangi bir sorun oluşturmaz.

cascade bir çözüm olabilir mi?

bir category sileceğim diye bu category'deki bütün product'ları silmenin anlamı var mı?

2. durum:
prod_usagearea tablosu için örnek:
prodid ve usageareaid foreignkey

The DELETE statement conflicted with the REFERENCE constraint "FK_Prod_UsageArea_UsageArea1". The conflict occurred in database "Himerpa", table "dbo.Prod_UsageArea", column 'UsageAreaID'.
The statement has been terminated.

çözüm: delete rule : cascade

sql - update table with join

-- 2 related tables

update t1
set t1.Field = t2.Field
from Table1 t1
join Table2 t2 on t1.id = t2.id

-- 3 related tables


update t1 p
set t1.f1 =
(
select distinct t3.f3
from t3
inner join t2 on t2.f2 = t3.f3
where t2.f2 = t1.f1
order by t3.f3
)

search this blog (most likely not here)