Pages

Wednesday, January 26, 2011

Managing Application Pools in IIS 7

http://technet.microsoft.com/en-us/library/cc753449%28WS.10%29.aspx

  • In IIS 7, application pools run in one of two modes: integrated mode and classic mode
Most managed applications should run successfully in application pools with integrated mode, but you may have to run in classic mode for compatibility reasons. Test the applications that are running in integrated mode first to determine whether you really need classic mode.


Application Pool Identity Accounts

Worker processes in IIS 6.0 and IIS 7 run as NETWORKSERVICE by default. NETWORKSERVICE is a built-in Windows identity. It doesn't require a password and has only user privileges; that is, it is relatively low-privileged. Running as a low-privileged account is a good security practice because then a software bug can't be used by a malicious user to take over the whole system.
However, a problem arose over time as more and more Windows system services started to run as NETWORKSERVICE. This is because services running as NETWORKSERVICE can tamper with other services that run under the same identity. Because IIS worker processes run third-party code by default (Classic ASP, ASP.NET, PHP code), it was time to isolate IIS worker processes from other Windows system services and run IIS worker processes under unique identities. The Windows operating system provides a feature called "Virtual Accounts" that allows IIS to create unique identities for each of its Application Pools. Click here for more information about Virtual Accounts.

Securing Resources

Whenever a new Application Pool is created, the IIS management process creates a security identifier (SID) that represents the name of the Application Pool itself. For example, if you create an Application Pool with the name "MyNewAppPool," a security identifier with the name "MyNewAppPool" is created in the Windows Security system. From this point on, resources can be secured by using this identity. However, the identity is not a real user account; it will not show up as a user in the Windows User Management Console.
You can try this by selecting a file in Windows Explorer and adding the "DefaultAppPool" identity to the file's Access Control List (ACL).
  1. Open Windows Explorer
  2. Select a file or directory.
  3. Right click the file and select "Properties"
  4. Select the "Security" tab
  5. Click the "Edit" and then "Add" button
  6. Click the "Locations" button and make sure you select your machine.
  7. Enter "IIS AppPool\DefaultAppPool" in the "Enter the object names to select:" text box.
  8. Click the "Check Names" button and click "OK".
By doing this, the file or directory you selected will now also allow the "DefaultAppPool" identity access.

Sunday, January 23, 2011

SQL commands

osql -L 
//for browsing all SQL instances

Tuesday, January 18, 2011

Monday, January 17, 2011

JQuery XML parsing

<script type="text/javascript">
        $(document).ready(function () {
 
            $.each(($.browser), function (i, val) {
 
            });
 
            $("#btnlookup").click(function () { lookup(); });
 
 
        });
           if (!$.browser.msie) {
                alert('this utility is available only for IE, please try JSONP for other browsers');
                 return;
            }
            var addressURL = "http://maps.googleapis.com/maps/api/geocode/xml?address=" + $("#txtAddress").val() + "&sensor=false";             alert(addressURL);             $("#output").text("");             $.ajax({                 url: addressURL,                 dataType: "xml",                 success: function (response) {                     if (!$.isXMLDoc(response)) {                         var outputStr = "Result is not valid XML Format";                         $(outputStr).appendTo($("#output"));                     }                     $.each($(response).find('result'), function () {                         var outputStr = "
" + "" + $(this).find('formatted_address').text() + " lat:" + $(this).find("location").find("lat").text() + ", lng" + +$(this).find("location").find("lng").text() + " " + "
"
;                         $(outputStr).appendTo($("#output"));                     });                 }, //sccess                 error: function (response) {                     var outputStr = "" + response.status + "";                     $(outputStr).appendTo($("#output"));                 }             }//ajax options                             );         }     script>

JSON via webservices Using JSONP

//Step1  add ScriptService  for the class & [ScriptMethod(UseHttpGet = true)]
//to the method
/// 
/// Summary description for RatingService_JSONP
/// 
[WebService(Namespace = "http://ws.cli.det.nsw.edu.au/ns/Web2Services/RattingService",
           Description = "Ratting service, this service will be plugable in any application, to support rating with comments, including reports and summaries")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class RatingService_JSONP : RatingService
{
    }
    [WebMethod(Description = @"Sample Please remove it")]
    [ScriptMethod(UseHttpGet = true)]
    public string[] Sample()
    {
        return new string[] { "AAA""BBB""CCC""DDD" };
    }
 
}
 
//Step2 
// use format=json  for json format
// use callback=?    for JSONP
  
 $(document).ready(function () {
            $("#btnlookup").click(function () { lookup(); });
        });
        function lookup() {
            var addressURL = "http://localhost/Web2Services/WebServices/JSON/RatingService_JSONP.asmx/Sample?format=json&callback=?";
            var outputStr = "";
            $("#output").text(outputStr);
            $.getJSON(addressURL, nullfunction (response) {
                $.each(response.d, function (i, val) {
                    outputStr = "
" + val.toString() + "
"
;                                          $(outputStr).appendTo("#output");                 });             });     // getJson

Friday, January 14, 2011

MVC JNSON

// ContactController class -----------------------------------------------
public ActionResult GetContactsJSON(string id)
{
if (string.IsNullOrEmpty(id))
{
return Json(_ctx.Contacts.OrderBy(cnt => cnt.FirstName).Take(100).ToList(), JsonRequestBehavior.AllowGet);
}
else
{

return Json(_ctx.Contacts.Where(cnt => cnt.FirstName.StartsWith(id)).OrderBy(cnt => cnt.FirstName).Take(100).ToList(), JsonRequestBehavior.AllowGet);

}
}
public ActionResult GetContactJSON(int id)
{

return Json(_ctx.Contacts.SingleOrDefault(cnt => cnt.ContactID == id), JsonRequestBehavior.AllowGet);

}
// Master Page  -----------------------------------------------
// add the jquery script reference
//+ add ContentPlcaHolder to allow content page to write the script block
<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server" />title>
<link href="../../Content/Site.css" rel="stylesheet" type="text/css" />
 <script src="../../Scripts/jquery-1.4.1.js" type="text/javascript">script>
<asp:ContentPlaceHolder ID="HeaderPlaceHolder" runat="server"/>
head>
// Detail Page  -----------------------------------------------
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Details
asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="HeaderPlaceHolder" runat="server">
<script type="text/javascript">

$(document).ready(function () {

//alert("Test");

// $.getJSON("/Contact/GetContactsJSON", null, function (data) {
$.getJSON("/Contact/GetContactsJSON", null, function (data) {

for (i = 0; i < data.length; i++) {

$('#db_contacts').append($("").attr("value", data[i].ContactID).text(data[i].ShortFormat));
} //for

$('#db_contacts').change(function (data) {
populate($("#db_contacts option:selected").attr('value'));

}); //change

}); //getJSON

$("#txt_search").keyup(populateList);

$("#btn_search").click(populateList);

});      //ready


function populateList() {
$.getJSON("/Contact/GetContactsJSON/" + $("#txt_search").val(), null, function (data) {
$('#db_contacts').find('option').remove();
for (i = 0; i < data.length; i++) {

$('#db_contacts').append($("").attr("value", data[i].ContactID).text(data[i].ShortFormat));
} //for

}); //getJSON

} //populateList
function populate(key) {
$.getJSON("/Contact/GetContactJSON/" + key.toString(), null, function (data) {
$('#ContactID').text(data.ContactID);
$('#NameStyle').text(data.NameStyle);
$('#Title').text(data.Title);
$('#FirstName').text(data.FirstName);
$('#MiddleName').text(data.MiddleName);
$('#LastName').text(data.LastName);
}); // getJSON
} //opulate

script>
<style type="text/css">
#Select1
{
width: 275px;
}
style>
asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<p>
search <span width="30px"/> <input id="txt_search" type="text" /> <span width="30px"/>
<input id="btn_search" type="button" value="search" />
p>
<select id="db_contacts" name="db_contacts">
select>
<h2>
Detailsh2>
<fieldset>
<legend>Fieldslegend>
<div class="display-label">
ContactIDdiv>
<div class="display-field" id="ContactID">
<%: Model.Current.ContactID %>div>
<div class="display-label">
NameStylediv>
<div class="display-field" id="NameStyle">
<%: Model.Current.NameStyle %>div>
<div class="display-label">
Titlediv>
<div class="display-field" id="Title">
<%: Model.Current.Title %>div>
<div class="display-label">
FirstNamediv>
<div class="display-field" id="FirstName">
<%: Model.Current.FirstName %>div>
<div class="display-label">
MiddleNamediv>
<div class="display-field" id="MiddleName">
<%: Model.Current.MiddleName %>div>
<div class="display-label">
LastNamediv>
<div class="display-field" id="LastName">
<%: Model.Current.LastName %>div>
<div class="display-label">
Suffixdiv>
<div class="display-field">
<%: Model.Current.Suffix %>div>
<div class="display-label">
EmailAddressdiv>
<div class="display-field">
<%: Model.Current.EmailAddress %>div>
<div class="display-label">
EmailPromotiondiv>
<div class="display-field">
<%: Model.Current.EmailPromotion %>div>
<div class="display-label">
Phonediv>
<div class="display-field">
<%: Model.Current.Phone %>div>
<div class="display-label">
PasswordHashdiv>
<div class="display-field">
<%: Model.Current.PasswordHash %>div>
<div class="display-label">
PasswordSaltdiv>
<div class="display-field">
<%: Model.Current.PasswordSalt %>div>
<div class="display-label">
AdditionalContactInfodiv>
<div class="display-field">
<%: Model.Current.AdditionalContactInfo %>div>
<div class="display-label">
rowguiddiv>
<div class="display-field">
<%: Model.Current.rowguid %>div>
<div class="display-label">
ModifiedDatediv>
<div class="display-field">
<%: String.Format("{0:g}", Model.Current.ModifiedDate) %>div>
<div class="display-label">
ShortFormatdiv>
<div class="display-field">
<%: Model.Current.ShortFormat %>div>
fieldset>
<p>
<%: Html.ActionLink("Edit", "Edit", new { id=Model.Current.ContactID }) %>
|
<%: Html.ActionLink("Back to List", "Index") %>
p>
asp:Content>

MVC Controller

using System;

using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using EFCore.Data;

namespace MVCUI.Controllers
{

// Contact is the Controller
public class ContactController : Controller
{
AdventureWorksEntities _ctx = new AdventureWorksEntities();
//
// GET: /Contact/
// For Pagination
public ActionResult Index(int? startRowIndex, int? maxRows)
{
if (startRowIndex == null || maxRows == null)
{

return RedirectToAction("Index", "Contact", new { startRowIndex = 0, maxRows = 20 });

}

ContactViewModel viewModel = new ContactViewModel
{

ContactList = _ctx.Contacts.OrderBy(cnt => cnt.ContactID).Skip(startRowIndex.Value).Take(maxRows.Value).ToList(),
Current = null,
TotalCount = _ctx.Contacts.Count(),
PageIndex = startRowIndex.Value / maxRows.Value,
NextPageIndex = GetNextPage(startRowIndex.Value, maxRows.Value, _ctx.Contacts.Count()),
PrevPageIndex = GetPrevPage(startRowIndex.Value, maxRows.Value)
};
return View(viewModel);
}

//
// GET: /Contact/Details/5

public ActionResult Details(int id)
{
return View(new ContactViewModel { Current = _ctx.Contacts.Single(cnt => cnt.ContactID == id) });
}

//
// GET: /Contact/Create

public ActionResult Create()
{
return View();
}

//
// POST: /Contact/Create
// POST: you can get all values manually via Form collection in the request objector from collection parameter
//
[HttpPost]
public ActionResult Create(FormCollection collection)
{
ContactViewModel model = new ContactViewModel
{
Current = new Contact()
};
// this.ModelState.AddModelError()
TryUpdateModel(model);
if (ModelState.IsValid)
{
model.Current.PasswordHash = "e32e324=";
model.Current.PasswordSalt = "w";
model.Current.rowguid = Guid.NewGuid();
model.Current.ModifiedDate = DateTime.Now;
_ctx.Contacts.AddObject(model.Current);
_ctx.SaveChanges();
model.Current = _ctx.Contacts.OrderByDescending(cnt => cnt.ContactID).FirstOrDefault();
return RedirectToAction("Details", new { id = model.Current.ContactID });
}
else
{
return View(model);

}


}





//
// GET: /Contact/Edit/5

public ActionResult Edit(int id)
{
return View(_ctx.Contacts.Single(cnt => cnt.ContactID == id));

}

//
// POST: /Contact/Edit/5

[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{

Contact contact = _ctx.Contacts.SingleOrDefault(cnt => cnt.ContactID == id);

if (string.IsNullOrEmpty(collection["FirstName"]))
{
ModelState.AddModelError("FirstName", "First name should not be Null");
}
if (ModelState.IsValid)
{
TryUpdateModel(contact);
_ctx.SaveChanges();

return RedirectToAction("Details", new { id = id });
}
else
{
return View(contact);

}


}

//
// GET: /Contact/Delete/5

public ActionResult Delete(int id)
{
return View();
}

//
// POST: /Contact/Delete/5

public ActionResult GetContactsJSON(string id)
{
if (string.IsNullOrEmpty(id))
{
return Json(_ctx.Contacts.OrderBy(cnt => cnt.FirstName).Take(100).ToList(), JsonRequestBehavior.AllowGet);
}
else
{

return Json(_ctx.Contacts.Where(cnt => cnt.FirstName.StartsWith(id)).OrderBy(cnt => cnt.FirstName).Take(100).ToList(), JsonRequestBehavior.AllowGet);

}
}
public ActionResult GetContactJSON(int id)
{

return Json(_ctx.Contacts.SingleOrDefault(cnt => cnt.ContactID == id), JsonRequestBehavior.AllowGet);

}
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
// TODO: Add delete logic here

return RedirectToAction("Index");
}
catch
{
return View();
}
}

private int GetPrevPage(int startRowIndex, int maxRows)
{
try
{
var result = startRowIndex - maxRows;
return result <= 0 ? 0 : result; } catch { return 0; }
}

private int GetNextPage(int startRowIndex, int maxRows, int totalCount)
{
try
{
var result = startRowIndex + maxRows;

return result >= totalCount ? totalCount - maxRows : result;
}
catch
{

return 0;
}
}
}

public class ContactViewModel
{
public long TotalCount { get; set; }
public List<Contact> ContactList { get; set; }
public Contact Current { get; set; }
public int PageIndex { get; set; }
public int NextPageIndex { get; set; }
public int PrevPageIndex { get; set; }


}
}