tag:blogger.com,1999:blog-68237012626977050132024-02-20T18:22:15.226-08:00Sumesh ParakkatI do my thing and you do yours. I am not in this world to live up to your expectations, and you are not in this world to live up to mine. You are you and I am I, and if by chance we find each other, then it is beautiful. If not, it can't be helped.Anonymoushttp://www.blogger.com/profile/04793789893946649568noreply@blogger.comBlogger18125tag:blogger.com,1999:blog-6823701262697705013.post-16422524542913186512012-08-05T00:45:00.001-07:002012-08-07T05:19:55.813-07:00Javascript Anonymous Functions And The Module PatternOne of the most annoying things about JavaScript is that it has no scope for variables. Any variable, function, array or object you define that is not inside another function is global, which means that other scripts on the same page can access—and will usually override— them.
<br />
The workaround is to encapsulate your variables in an anonymous function and call that function immediately after you define it. For example, the following definition would result in three global variables and two global functions:
<br />
<br />
<pre class="brush:js">var name = 'Chris';
var age = '34';
var status = 'single';
function createMember(){
// [...]
}
function getMemberDetails(){
// [...]
}
</pre>
<br />
Any other script on the page that has a variable named <b><i>status </i></b>could cause trouble. If we wrap all of this in a name such as <i><b>myApplication</b></i>, then we work around that issue:
<br />
<br />
<pre class="brush:js"> var myApplication = function(){
var name = 'Chris';
var age = '34';
var status = 'single';
function createMember(){
// [...]
}
function getMemberDetails(){
// [...]
}
}();</pre>
This, however, doesn't do anything outside of that function. If this is what you need, then great. You may as well discard the name then:
<br />
<br />
<pre class="brush:js"> (function(){
var name = 'Chris';
var age = '34';
var status = 'single';
function createMember(){
// [...]
}
function getMemberDetails(){
// [...]
}
})();</pre>
If you need to make some of the things reachable to the outside, then you need to change this. In order to reach <b><i>createMember() </i></b>or <b><i>getMemberDetails()</i></b>, you need to return them to the outside world to make them properties of <b><i>myApplication</i></b>:
<br />
<br />
<pre class="brush:js">var myApplication = function(){
var name = 'Chris';
var age = '34';
var status = 'single';
return{
createMember:function(){
// [...]
},
getMemberDetails:function(){
// [...]
}
}
}();
// myApplication.createMember() and
// myApplication.getMemberDetails() now works.</pre>
<p>
<br />
This is called a module pattern or singleton. It was mentioned a lot by Douglas Crockford and is used very much in the<a href="http://yuilibrary.com/" target="_blank"> Yahoo User Interface Library YUI</a>. What ails me about this is that I need to switch syntaxes to make functions or variables available to the outside world. Furthermore, if I want to call one method from another, I have to call it preceded by the <b><i>myApplication </i></b>name. So instead, I prefer simply to return pointers to the elements that I want to make public. This even allows me to shorten the names for outside use:
<br />
<pre class="brush:js"> var myApplication = function(){
var name = 'Chris';
var age = '34';
var status = 'single';
function createMember(){
// [...]
}
function getMemberDetails(){
// [...]
}
return{
create:createMember,
get:getMemberDetails
}
}();
//myApplication.get() and myApplication.create() now work.</pre>
<br />
Reffer: "<a href="http://christianheilmann.com/2007/08/22/again-with-the-module-pattern-reveal-something-to-the-world/" target="_blank">revealing module pattern.</a>"
<br />
<a href="http://coding.smashingmagazine.com/2010/04/20/seven-javascript-things-i-wish-i-knew-much-earlier-in-my-career/" target="_blank">http://coding.smashingmagazine.com/2010/04/20/seven-javascript-things-i-wish-i-knew-much-earlier-in-my-career/</a>Anonymoushttp://www.blogger.com/profile/04793789893946649568noreply@blogger.com0tag:blogger.com,1999:blog-6823701262697705013.post-24008495687649210472012-07-27T03:10:00.001-07:002012-07-27T03:10:38.692-07:00Map SqlReader to Bussiness Entity Collection using Reflection C#<p>
<a href="http://msdn.microsoft.com/en-us/library/ms173183(v=vs.80).aspx">Reflection</a>
provides objects (of type Type) that encapsulate assemblies, modules and types.
You can use reflection to dynamically create an instance of a type, bind the type
to an existing object, or get the type from an existing object and invoke its methods
or access its fields and properties. If you are using attributes in your code, Reflection
enables you to access them. For more information
</p>
<h4>
Map Data To Business Entity Collection</h4>
<p>
MapDataToBusinessEntityCollection is a generic Reflective method. We pass in the
data-type for the objects to be mapped as a generic parameter along with a data
reader. We use reflection to find the properties in this type and we use the meta
data in the DataReader to find the fields.
</p>
<p>
Whenever we find a field from the data reader that has a matching writable property
in the generic type, we pull the value from the DataReader and assign it to a newly
created object. Regardless of how many properties are in T, this method will map
every property that has a matching field in the DataReader. Any properties that
are not in the DataReader will be unmapped. Any fields in the data reader that do
not have a matching property will be ignored. The validation logic is handled in
the implementation of the properties in T.</p>
<pre class="brush:csharp">
public static List<T> MapDataToBusinessEntityCollection<T>(IDataReader dr)
where T : new()
{
Type businessEntityType = typeof (T);
List<T> entitys = new List<T>();
Hashtable hashtable = new Hashtable();
PropertyInfo[] properties = businessEntityType.GetProperties();
foreach (PropertyInfo info in properties)
{
hashtable[info.Name.ToUpper()] = info;
}
while (dr.Read())
{
T newObject = new T();
for (int index = 0; index < dr.FieldCount; index++)
{
PropertyInfo info = (PropertyInfo)
hashtable[dr.GetName(index).ToUpper()];
if ((info != null) && info.CanWrite)
{
info.SetValue(newObject, dr.GetValue(index), null);
}
}
entitys.Add(newObject);
}
dr.Close();
return entitys;
}
</pre>
<div>
Reefference
<ul>
<li><a href="http://www.simple-talk.com/dotnet/.net-framework/a-defense-of-reflection-in-.net/">
http://www.simple-talk.com/dotnet/.net-framework/a-defense-of-reflection-in-.net/</a>
</li>
<li><a href="http://msdn.microsoft.com/en-us/library/ms173183(v=vs.80).aspx">http://msdn.microsoft.com/en-us/library/ms173183(v=vs.80).aspx</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/kyaxdd3x.aspx">http://msdn.microsoft.com/en-us/library/kyaxdd3x.aspx</a></li>
</ul>
</div>Anonymoushttp://www.blogger.com/profile/04793789893946649568noreply@blogger.com0tag:blogger.com,1999:blog-6823701262697705013.post-58063990185487759852012-07-25T00:10:00.000-07:002012-07-25T00:19:17.579-07:00Working With Cookies In Javascript<p>
<strong>Cookies</strong> are variables of temporary data which is stored on the
visitors computers. They are normally used for things like remember my username
on a login form. This can be a useful way to store information about your returned
visitors without them having to log in to store information on a database.
</p>
<p>
It's worth noting that cookies should not be used to store secure information as
they are just files stored on your visitors computer.
</p>
<p>
You can set a cookie on both the server side and the client side in this article
we are going to look at the process you would set-up a cookie on the client side
using Javascript.
</p>
<div>
<h1>
Raw Javascript</h1>
<p>
Working with cookies in Javascript is not the best feature of Javascript, there
is no easy way of dealing with setting and getting cookies.</p>
<h4>
All Values</h4>
To get all the cookies which are set for the current document you need to use the
following.
<pre class="brush:js">
var allCookies = document.cookie;
</pre>
<h4>
Setting Values In Javascript</h4>
To set a cookie you need to use the Javascript variable document.cookie, to add
values to this you need to setup the data as a query string and add onto the end
of the document.cookie.
<pre class="brush:js">
document.cookie = "website=weblink";
// cookie is website=weblink
</pre>
<br />
If you want to add extra data to the cookie then you just need to repeat the above
step.
<pre class="brush:js">
document.cookie = "secondwebsite=second-site-demo";
// cookie is website=weblink;secondwebsite=second-site-demo;
</pre>
<br />
Now this seems easy to set data but this will not deal with expiring the cookie
or domain for the cookie. To set the expiry of the cookie you need to add the expiry
on the end of the document.cookie.
<pre class="brush:js">
document.cookie += "; expires="+date.toGMTString();
</pre>
<br />
To set the domain path of the cookie you then need to set the path on the end of
the document.cookie.
<pre class="brush:js">
document.cookie += "; path=/";
</pre>
<br />
With these factors you can add to just setting data on the cookie it can be difficult
to handle you need to write a function to handle the setting of the cookie.
<pre class="brush:js">
function setCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
</pre>
<h4>
Getting Values</h4>
<p>
As you can see there is a lot you need to do to set the values on the document.cookie
but you will need to do even more to get values out of the document.cookie.
<br />
If you want to get a certain value you have set you can't just call the key of the
data to get the value you have to use a function which will do a reg ex search to
get the value of a key.
</p>
<pre class="brush:js">
function getCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
</pre>
<br />
</div>
<div>
<h1>
Easier Way Of Working With Cookies In Javascript</h1>
<p>
There must be an easier way of handling the cookie data then having to create you
own functions to deal with the different scenarios of setting, getting, all cookies,
remove cookies, empty all cookies, testing if cookies are enabled.
<br />
There is an easier way of working with cookies there is a Github project called
cookie.js, this is a simple javascript file which when included on your web page
you can easily handle the cookie data.
</p>
<h4>
Cookie.js</h4>
<p>
To use cookie.js all you have to do is download it from Github and include it on
your page, download it from <a href="https://github.com/js-coder/cookie.js">here.</a>
Then you can include it on the page by doing using the following code.
</p>
<pre class="brush:js">
<script src="cookie.min.js" > </script >
</pre>
<p>
When this file is included there will be a new cookie object to use to set and get
the data.
</p>
<h4>
Setting Cookie</h4>
<p>
To set a cookie with cookie.js all you have to do is use the method set().
</p>
<pre class="brush:js">
cookie.set( 'key', 'value' );
</pre>
<br />
If you want to add extra parameters to the cookie you can set these up as the third
argument on the method.
<pre class="brush:js">
cookie.set( 'key' , 'value', {
expires: 7,
domain: "paulund.co.uk",
path: "/",
secure: false
});
</pre>
<h4>
Getting Cookie
</h4>
<p>
To get the values from the cookie it is as easy as using the get() method, this
will return string of the value of the key.</p>
<pre class="brush:js">
cookie.get( 'key1' );
</pre>
<br />
Or you can even use a shorthand version of this by just doing.
<pre class="brush:js">
cookie( 'key1' );
</pre>
<h4>
Get All Cookies</h4>
<p>
To get all the cookies available it is very simple by using the all() method.</p>
<pre class="brush:js">
var allCookies = cookie.all();
</pre>
<h4>
Removing Cookies</h4>
<p>
It is also easy to remove the cookies by referring to the key you have setup on
the cookie, by using the remove() method.
</p>
<pre class="brush:js">
cookie.remove( 'key1' );
</pre>
<p>
You can even remove all cookies available on the domain by using the empty method.
</p>
<pre class="brush:js">
cookie.empty();
</pre>
<h4>
Cookies Enabled</h4>
<p>
Visitors can turn cookies off on the browser so you will not be able to store data
on the visitors computer, for this reason you will need to check if cookies are
enabled before you try setting up new cookies.
<br />
With cookie.js you can do this easily by using the enabled() method.
</p>
<pre class="brush:js">
if (cookie.enabled()) {
// Cookies are on you can setup cookies
} else {
// Cookies are turned off you can not use cookies
}
</pre>
<br />
</div>
ref:http://www.paulund.co.uk/cookies-with-javascriptAnonymoushttp://www.blogger.com/profile/04793789893946649568noreply@blogger.com0tag:blogger.com,1999:blog-6823701262697705013.post-84369588591350927242012-07-06T21:43:00.000-07:002012-07-06T21:43:02.329-07:00Converts a virtual path to an application absolute path - Extension Methods<p>
Converts the provided app-relative path into an absolute Url containing the full host name
</p>
<pre class="brush:csharp">
/// <param name="relativeUrl">App-Relative path</param>
/// <returns>Provided relativeUrl parameter as fully qualified Url</returns>
/// <example>~/path/to/foo to http://www.web.com/path/to/foo</example>
public static string GetAbsoluteUrl(string relativeUrl)
{
//VALIDATE INPUT
if (String.IsNullOrEmpty(relativeUrl))
return String.Empty;
//VALIDATE INPUT FOR ALREADY ABSOLUTE URL
if (relativeUrl.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || relativeUrl.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
return relativeUrl;
//VALIDATE CONTEXT
if (HttpContext.Current == null)
return relativeUrl;
//GET CONTEXT OF CURRENT USER
HttpContext context = HttpContext.Current;
//FIX ROOT PATH TO APP ROOT PATH
if (relativeUrl.StartsWith("/"))
{
relativeUrl = relativeUrl.Insert(0, "~");
}
//GET RELATIVE PATH
Page page = context.Handler as Page;
if (page != null)
{
//USE PAGE IN CASE RELATIVE TO USER'S CURRENT LOCATION IS NEEDED
relativeUrl = page.ResolveUrl(relativeUrl);
}
else //OTHERWISE ASSUME WE WANT ROOT PATH
{
//PREPARE TO USE IN VIRTUAL PATH UTILITY
if (!relativeUrl.StartsWith("~/"))
{
relativeUrl = relativeUrl.Insert(0, "~/");
}
relativeUrl = VirtualPathUtility.ToAbsolute(relativeUrl);
}
var url = context.Request.Url;
var port = url.Port != 80 ? (":" + url.Port) : String.Empty;
//BUILD AND RETURN ABSOLUTE URL
return String.Format("{0}://{1}{2}{3}",
url.Scheme, url.Host, port, relativeUrl);
}
</pre>Anonymoushttp://www.blogger.com/profile/04793789893946649568noreply@blogger.com0tag:blogger.com,1999:blog-6823701262697705013.post-24531905171761129852012-07-06T21:37:00.000-07:002012-07-06T21:37:01.865-07:00Compares to DateTimes and converts the result to an easy human readable<p>
Take this:<b>2012-07-13 17:47:33</b><br/><br/>
and turn it into this:<b>5 minutes 16 seconds ago</b> <br/>
</p>
<pre class="brush:csharp">
/// <summary>
/// Compares to DateTimes and converts the result to an easy human readable format.
/// </summary>
/// <param name="time">A past or future DateTime.</param>
/// <param name="relativeTo">Relative to this time.</param>
/// <returns></returns>
public static string ToRelativeTime(this DateTime time, DateTime relativeTo)
{
TimeSpan ts = relativeTo.Subtract(time).Duration();
string DateFormat = "d MMMM";
string dir = (relativeTo > time) ? "Ago" : "To go";
if (relativeTo.Year != time.Year)
DateFormat += " yyyy";
if (ts.Days < 360)
{
//Months
if (ts.Days >= 30)
return string.Format("{0} ({1} Months {2})", time.ToString(DateFormat), (int)(ts.Days / 30), dir);
//Days
if (ts.Days > 0)
return string.Format("{0} ({1} Days {2})", time.ToString(DateFormat), ts.Days, dir);
//hours
if (ts.Hours > 0)
return string.Format("{0} Hours {1} Minutes {2}", ts.Hours, ts.Minutes, dir);
//minutes
if (ts.Minutes > 0)
return string.Format("{0} Minutes {1} Seconds {2}", ts.Minutes, ts.Seconds, dir);
//seconds
return string.Format("{0} Seconds {1}", ts.Seconds, dir);
}
return time.ToString(DateFormat);
}
</pre>Anonymoushttp://www.blogger.com/profile/04793789893946649568noreply@blogger.com0tag:blogger.com,1999:blog-6823701262697705013.post-15839601718522322192012-07-06T21:35:00.000-07:002012-07-06T21:35:22.981-07:00Extension Methods (C# Programming)<p>
Another cool feature of C# is Extension Methods. They allow you to extend an
existing type with new functionality, without having to sub-class or recompile the
old type. For instance, you might like to know whether a certain string was a number
or not. The usual approach would be to define a function and then call it each time,
and once you got a whole lot of those kind of functions, you would put them together
in a utility class.However, with Extension Methods, you can actually extend the String class to support this directly. You do it by defining a static class, with a set of static methods that will be your library of extension methods. Here is an example:
</p>
<pre class="brush:csharp">public static class Helpers
{
public static bool isNumber(this object inputvalue)
{
if (inputvalue == null) return false;
Regex isnumber = new Regex("[^0-9]");
return !isnumber.IsMatch(inputvalue.ToString());
}
public static bool isNumeric(this string s)
{
float output;
return float.TryParse(s, out output);
}
}
</pre>
<p>
The only thing that separates this from any other static method, is the "this" keyword in the parameter section of the method. It tells the compiler that this is an extension method for the string class, and that's actually all you need to create an extension method. Now, you can call the isNumber() method directly on strings, like this:
</p>
<pre class="brush:csharp"> string test = "4";
if (test.isNumber())
Console.WriteLine("Yes");
else
Console.WriteLine("No");
</pre>
Ref:<br />
<br />
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/bb383977.aspx">http://msdn.microsoft.com/en-us/library/bb383977.aspx</a>
</li>
<li><a href="http://geekswithblogs.net/sdorman/archive/2007/08/19/C-3.0-Extension-Methods.aspx">http://geekswithblogs.net/sdorman/archive/2007/08/19/C-3.0-Extension-Methods.aspx</a>
</li>
<li><a href="http://csharp.net-tutorials.com/csharp-3.0/extension-methods/">http://csharp.net-tutorials.com/csharp-3.0/extension-methods/</a>
</li>
<li><a href="http://www.dotnetperls.com/extension">http://www.dotnetperls.com/extension</a>
</li>
</ul>
<br>Anonymoushttp://www.blogger.com/profile/04793789893946649568noreply@blogger.com0tag:blogger.com,1999:blog-6823701262697705013.post-3781887062021548602012-06-22T06:04:00.000-07:002012-06-22T06:10:24.442-07:00Crop Image in ASP.NET using JCrop, JQuery<div>
<div>
You might have seen various websites and web application giving features to Crop
your image and save it. That can be done in DHTML or in Javascript. Lets see one
example of doing it with the help of JCrop which can be download from<a href="http://deepliquid.com/content/Jcrop.html" target="_blank"> here (JCrop)</a><br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgovZ0UmnmI1bkTf4PdJZ9bFPVPUwaaELrJeXofA2xhTx0zjkQEiWtcxUJuoh73lmr3A8EVkRmxbsJjCHLGQYYcFSY0XMM2wPUh33cfy-kuDFRF96sKZCcrLVsS4CPAlH7T82gnqoO0oy4A/s1600/__Intimate+Matrimony+_Public+Users+__+Upload+Photo_1340370406959.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="320" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgovZ0UmnmI1bkTf4PdJZ9bFPVPUwaaELrJeXofA2xhTx0zjkQEiWtcxUJuoh73lmr3A8EVkRmxbsJjCHLGQYYcFSY0XMM2wPUh33cfy-kuDFRF96sKZCcrLVsS4CPAlH7T82gnqoO0oy4A/s320/__Intimate+Matrimony+_Public+Users+__+Upload+Photo_1340370406959.png" width="285" /></a></div>
<br />
<b><br /></b><br />
<b>How to start</b><br />
<div>
<h4>
1. First include the following file into your project
</h4>
<ul>
<li>jquery.Jcrop.js</li>
<li>jquery.Jcrop.min.js</li>
<li>jquery.min.js</li>
</ul>
or you can directly drag and drop the JCrop folder in your project
</div>
<div>
<h4>
2. We need to write code in our page. Include the JQuery function in the page and
also add one event for crop control for updation of the cordinates in the variable
on selection by users. Check the head section of the page given below
</h4>
</div>
<div>
<pre class="brush:js"> <head runat="server">
<title></title>
<script src="js/jquery.min.js"></script>
<script src="js/jquery.Jcrop.min.js"></script>
<link rel="stylesheet" href="css/jquery.Jcrop.css" type="text/css" />
<script language="Javascript">
jQuery(document).ready(function () {
// Create variables (in this scope) to hold the API and image size
var jcrop_api, boundx, boundy;
$('#cropbox').Jcrop({
onChange: updatePreview,
onSelect: updatePreview,
aspectRatio: 1,
boxWidth: 450,
boxHeight: 400,
maxSize: [300, 300],
minSize: [200, 200]
}, function () {
// Use the API to get the real image size
var width = $('#cropbox').width();
var height = $('#cropbox').height();
var rect = new Array();
rect[0] = 1;
rect[1] = 1;
rect[2] = width - 1;
rect[3] = height - 1;
if (width >= 300) {
rect[0] = width / 6;
rect[2] = width - 100;
}
if (height >= 300) {
rect[1] = 10;
rect[3] = height - (height / 4);
}
var bounds = this.getBounds();
boundx = bounds[0];
boundy = bounds[1];
// Store the API in the jcrop_api variable
jcrop_api = this;
jcrop_api.setSelect(rect);
});
});
function updatePreview(c) {
jQuery('#X').val(c.x);
jQuery('#Y').val(c.y);
jQuery('#W').val(c.w);
jQuery('#H').val(c.h);
if (parseInt(c.w) > 0) {
var rx = 100 / c.w;
var ry = 100 / c.h;
$('#preview').css({
width: Math.round(rx * boundx) + 'px',
height: Math.round(ry * boundy) + 'px',
marginLeft: '-' + Math.round(rx * c.x) + 'px',
marginTop: '-' + Math.round(ry * c.y) + 'px'
});
}
};
</script>
</head>
</pre>
</div>
<div>
<h4>
3. In your body section add following form to your page</h4>
</div>
<div>
<pre class="brush:html">
<div>
<asp:button id="Submit" runat="server" text="Crop Image" onclick="Submit_Click" />
<asp:image id="cropedImage" runat="server" visible="False" />
<table>
<tr>
<td>
<div>
<img src="Sunset.jpg" id="cropbox" />
</div>
</td>
<td valign="middle">
<div>
<table>
<tr>
<td class="headInnerLarger">
Thumbnail Preview:
</td>
</tr>
<tr>
<td>
<div style="width: 100px; height: 100px; overflow: hidden;">
<img src="Sunset.jpg" id="preview" />
</div>
</td>
</tr>
</table>
</div>
</td>
</tr>
</table>
<asp:hiddenfield id="X" runat="server" />
<asp:hiddenfield id="Y" runat="server" />
<asp:hiddenfield id="W" runat="server" />
<asp:hiddenfield id="H" runat="server" />
</div>
</pre>
</div>
<div>
<h4>
4. We need to handle the click event of crop button in our code and crop the image
there</h4>
</div>
<div>
<pre class="brush:csharp">
protected void Submit_Click(object sender, EventArgs e)
{
if (this.IsPostBack)
{
//Get the Cordinates
int x = Convert.ToInt32(X.Value);
int y = Convert.ToInt32(Y.Value);
int w = Convert.ToInt32(W.Value);
int h = Convert.ToInt32(H.Value);
//Load the Image from the location
System.Drawing.Image image = Bitmap.FromFile(
HttpContext.Current.Request.PhysicalApplicationPath + "Sunset.jpg");
//Create a new image from the specified location to
//specified height and width
Bitmap bmp = new Bitmap(w, h, image.PixelFormat);
Graphics g = Graphics.FromImage(bmp);
g.DrawImage(image, new Rectangle(0, 0, w, h), new Rectangle(x, y, w, h),
GraphicsUnit.Pixel);
//Save the file and reload to the control
bmp.Save(HttpContext.Current.Request.PhysicalApplicationPath + "Sunset2.jpg", image.RawFormat);
cropedImage.Visible = true;
cropedImage.ImageUrl = ".\\Sunset2.jpg";
}
}
</pre>
</div>
</div>
</div>Anonymoushttp://www.blogger.com/profile/04793789893946649568noreply@blogger.com1tag:blogger.com,1999:blog-6823701262697705013.post-3589349374292567892012-06-10T22:34:00.001-07:002012-06-22T06:10:51.266-07:00.Net Framework-Basics<div>
<h1>
Explain the .Net Framework.</h1>
The .Net framework allows infrastructural services to all the applications developed
in .net compliant language. It is an engine that provides runtime services using
its component like Common Runtime Language. It consists of two main components such
as Common Language Runtime and Framework Class Library.
</div>
<div>
<h1>
Difference between .Net 4.0 and .Net 3.5, 2.0
</h1>
<ul>
<li>ControlRenderingCompatabilityVersion Setting in the Web.config File </li>
<li>ClientIDMode Changes </li>
<li>HtmlEncode and UrlEncode Now Encode Single Quotation Marks </li>
<li>ASP.NET Page (.aspx) Parser is Stricter </li>
<li>Browser Definition Files Updated </li>
<li>System.Web.Mobile.dll Removed from Root Web Configuration File </li>
<li>ASP.NET Request Validation </li>
<li>Default Hashing Algorithm Is Now HMACSHA256 </li>
<li>Configuration Errors Related to New ASP.NET 4 Root Configuration </li>
<li>ASP.NET 4 Child Applications Fail to Start When Under ASP.NET 2.0 or ASP.NET 3.5
Applications </li>
<li>ASP.NET 4 Web Sites Fail to Start on Computers Where SharePoint Is Installed
</li>
<li>The HttpRequest.FilePath Property No Longer Includes PathInfo Values </li>
<li>ASP.NET 2.0 Applications Might Generate HttpException Errors that Reference eurl.axd
</li>
<li>Event Handlers Might Not Be Not Raised in a Default Document in IIS 7 or IIS 7.5
Integrated Mode Changes to the ASP.NET Code Access Security (CAS) Implementation
</li>
<li>MembershipUser and Other Types in the System.Web.Security Namespace Have Been Moved
</li>
<li>Output Caching Changes to Vary * HTTP Header </li>
<li>System.Web.Security Types for Passport are Obsolete </li>
<li>The MenuItem.PopOutImageUrl Property Fails to Render an Image in ASP.NET 4 </li>
<li>Menu.StaticPopOutImageUrl and Menu.DynamicPopOutImageUrl Fail to Render Images When
Paths Contain Backslashes </li>
</ul>
<div>
<b>Link to find details of all the </b><a href="http://www.asp.net/(S(ywiyuluxr3qb2dfva1z5lgeg))/learn/whitepapers/aspnet4/breaking-changes" rel="nofollow" target="_blank"><b>Major changes in .Net 4.0</b></a></div>
</div>
<div>
<h1>
Explain CLR (Common Language Runtime) and its functionalities?
</h1>
Common Language Runtime (CLR) is the engine available in .Net Framework to compile
and run the program. CLR engine does not compile the code in machine code but converts
the code in a set of instructions called Microsoft Intermediate Language (MSIL).
This MSIL is one of the section of Portable Executable (PE) file, the other being
Metadata. PE file automatically get generated when you compile the program code.
<br />
The conversion of the program code to MSIL by CLR engine, makes .Net platform and
language independent. Although at present, Microsoft does not have CLR engines for
other platforms, in future you can find .Net application being compiled in UNIX
or Linux operating system. After the conversion of the program code to MSIL, the
code is then translated to native or machine code. Instead of compiling the program
code at development time, the MSIL code gets translated 'just in time' (JIT) by
JIT compilers.
<br />
CLR helps developers in managing both allocation and deallocation of memory. This
removes two of the largest sources of programmer error: leaks and memory corruption.
<br />
CLR is also helpful for security purposes. CLR provide permissions to a component
based on what process it runs in, validates the code based on evidence such as information
about code at load time and the website from which component was obtained to assign
permissions on a component-by-component basis. Moreover, CLR checks the code to
see if it has been manipulated. The metadata in a CLR component can contain a digital
signature that can be used to verify that the component was written by genuine person
and that it has not been modified.
</div>
<div>
<h1>
Explain the components of common language runtime.</h1>
<div>
<ul>
<li><b>Class Loader:</b> is an abstract class. Its purpose is to tell JVM in what manner
a class is to be loaded at runtime.</li>
<li><b>MSIL: </b>Microsoft Intermediate Language is considered to be the lowest form
of human readable language. It is CPU independent and includes instructions of how
to load, store, initialize objects. JIT converts this MSIL into native code which
is dependent on the CPU.</li>
<li><b>Code Manager:</b> Is responsible for managing code at runtime.</li>
<li><b>Garbage Collector:</b>The .NET garbage collector enables high-speed allocation
and release of memory for the objects in managed code. Its main aim is proper memory
management.</li>
<li><b>Security Engine:</b>It ensures all the security restrictions.</li>
<li><b>Checker:</b>Type It enforces the constraints of types. It enforces strictness
in type checking.</li>
<li><b>Thread Support:</b>It allows multithreading</li>
<li><b>Debug engine:</b> It allows proper debugging of an application.</li>
<li><b>Base class library:</b> It provides all the types that an application need at
runtime.</li>
<li><b>Exception manager:</b> Handles all the exception for an application during runtime.</li>
<li><b>COM Marshaller:</b>It provides an option for interoperability for an application.</li>
</ul>
</div>
</div>Anonymoushttp://www.blogger.com/profile/04793789893946649568noreply@blogger.com0tag:blogger.com,1999:blog-6823701262697705013.post-26354554384952393092012-05-28T04:18:00.002-07:002012-06-22T06:11:43.907-07:00Operation is not valid due to the current state of the object. :ASP.Net Error<span style="font-size: medium;"><b>Issue:</b></span><br />
<div id="ErrorTitle">
<span style="font-family: 'Courier New';"><span id="ErrorType">System.InvalidOperationException</span><span id="ErrorMessage">Operation is not valid due to the current state of the
object.</span></span></div><span style="font-family: 'Courier New'; font-size: medium;">
<pre class="brush:csharp">
System.InvalidOperationException: Operation is not valid due to the current state of the object.
at System.Web.HttpRequest.FillInFormCollection()
at System.Web.HttpRequest.get_Form()
at Rhino.Commons.LongConversationManager.LoadConversationFromRequest(Boolean& privateConversation)
at Rhino.Commons.LongConversationManager.LoadConversation()
at Rhino.Commons.HttpModules.UnitOfWorkApplication.UnitOfWorkApplication_BeginRequest(Object sender, EventArgs e)
at System.Web.HttpApplication.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
</pre> </span>
<b><span style="font-size: medium;">Cause:</span></b><br />
<br />
Microsoft recently (12-29-2011) released an update to address several serious
security vulnerabilities in the .NET Framework. MS11-100 was introduced just
recently that handles potential DoS attacks.<br />
<br />
Unfortunately the fix has also broken page POSTs with very large amounts of
posted data (form fields). MS11-100 places a limit of 500 on postback items. The
new default max introduced by the recent security update is 1000.<br />
<br />
Adding the setting key to the web-config file overcomes this limitation, as in
this example increases it to 2000.<br />
<br />
<span style="font-family: 'Courier New'; font-size: medium;">
<pre class="brush:csharp">
<appSettings><br />
<add key="aspnet:MaxHttpCollectionKeys" value="2000" /><br />
</appSettings>
</pre>
</span>Anonymoushttp://www.blogger.com/profile/04793789893946649568noreply@blogger.com0tag:blogger.com,1999:blog-6823701262697705013.post-53160158937192537912012-05-26T03:34:00.000-07:002012-05-28T03:39:08.684-07:00ASP.Net Page Life CycleWhen a page request is sent to the Web server, the page is run through a series
of events during its creation and disposal. In this article, I will discuss in detail
the ASP.NET page life cycle Events
<br />
<div>
(1) <b>PreInit </b>The entry point of the page life cycle is the pre-initialization phase
called “PreInit”. This is the only event where programmatic access to master pages
and themes is allowed. You can dynamically set the values of master pages and themes
in this event. You can also dynamically create controls in this event.
<br />
EXAMPLE : Override the event as given below in your code-behind cs file of your
aspx page
<br />
<pre class="brush:csharp;">using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;using
System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_PreInit(object sender, EventArgs e)
{
// Use this event for the following:
// Check the IsPostBack property to determine whether this is the first time the page is being processed.
// Create or re-create dynamic controls.
// Set a master page dynamically.
// Set the Theme property dynamically.
}
</pre>
</div>
<hr />
<br />
<div>
(2)<b>Init </b>This event fires after each control has been initialized, each control's
UniqueID is set and any skin settings have been applied. You can use this event
to change initialization values for controls. The “Init” event is fired first for
the most bottom control in the hierarchy, and then fired up the hierarchy until
it is fired for the page itself.
<br />
EXAMPLE : Override the event as given below in your code-behind cs file of your
aspx page
<br />
<pre class="brush:csharp;">protected void Page_Init(object sender, EventArgs e)
{
// Raised after all controls have been initialized and any skin settings have been applied. Use this event to read or initialize control properties.
}
</pre>
</div>
<hr />
<br />
<div>
(3)<b>InitComplete </b>Raised once all initializations of the page and its controls have
been completed. Till now the viewstate values are not yet loaded, hence you can
use this event to make changes to view state that you want to make sure are persisted
after the next postback
<br />
EXAMPLE : Override the event as given below in your code-behind cs file of your
aspx page
<br />
<pre class="brush:csharp;">protected void Page_InitComplete(object sender, EventArgs e)
{
// Raised by the Page object. Use this event for processing tasks that require all initialization be complete.
}
</pre>
</div>
<hr />
<br />
<div>
(4)<b>PreLoad </b>Raised after the page loads view state for itself and all controls, and
after it processes postback data that is included with the Request instance
<br />
(1)Loads ViewState : ViewState data are loaded to controls Note : The page viewstate
is managed by ASP.NET and is used to persist information over a page roundtrip to
the server. Viewstate information is saved as a string of name/value pairs and contains
information such as control text or value. The viewstate is held in the value property
of a hidden <input> control that is passed from page request to page request.
<br />
(2)Loads Postback data : postback data are now handed to the page controls Note
: During this phase of the page creation, form data that was posted to the server
(termed postback data in ASP.NET) is processed against each control that requires
it. Hence, the page fires the LoadPostData event and parses through the page to
find each control and updates the control state with the correct postback data.
ASP.NET updates the correct control by matching the control's unique ID with the
name/value pair in the NameValueCollection. This is one reason that ASP.NET requires
unique IDs for each control on any given page.
<br />
EXAMPLE : Override the event as given below in your code-behind cs file of your
aspx page
<br />
<pre class="brush:csharp;">protected override void OnPreLoad(EventArgs e)
{
// Use this event if you need to perform processing on your page or control before the Load event.
// Before the Page instance raises this event, it loads view state for itself and all controls,
and then processes any postback data included with the Request instance.
}
</pre>
</div>
<hr />
<br />
<div>
(5)<b>Load </b>The important thing to note about this event is the fact that by now, the
page has been restored to its previous state in case of postbacks. Code inside the
page load event typically checks for PostBack and then sets control properties appropriately.
This method is typically used for most code, since this is the first place in the
page lifecycle that all values are restored. Most code checks the value of IsPostBack
to avoid unnecessarily resetting state. You may also wish to call Validate and check
the value of IsValid in this method. You can also create dynamic controls in this
method.
<br />
EXAMPLE : Override the event as given below in your code-behind cs file of your
aspx page
<br />
<pre class="brush:csharp;">protected void Page_Load(object sender, EventArgs e)
{
// The Page calls the OnLoad event method on the Page, then recursively does the same for each child control,
which does the same for each of its child controls until the page and all controls are loaded.
// Use the OnLoad event method to set properties in controls and establish database connections.
}
</pre>
</div>
<hr />
<br />
<div>
(6)<b>Control </b>(PostBack) event(s)ASP.NET now calls any events on the page or its controls
that caused the PostBack to occur. This might be a button’s click event or a dropdown's
selectedindexchange event, for example.These are the events, the code for which
is written in your code-behind class(.cs file).
<br />
EXAMPLE : Override the event as given below in your code-behind cs file of your
aspx page
<br />
<pre class="brush:csharp;">protected void Button1_Click(object sender, EventArgs e)
{ // This is just an example of control event.. Here it is button click event that caused the postback}
</pre>
</div>
<hr />
<br />
<div>
(7)<b>LoadComplete </b>This event signals the end of Load.
<br />
EXAMPLE : Override the event as given below in your code-behind cs file of your
aspx page
<br />
<pre class="brush:csharp;">protected void Page_LoadComplete(object sender, EventArgs e)
{ // Use this event for tasks that require that all other controls on the page be loaded.}
</pre>
</div>
<hr />
<br />
<div>
(8)<b>PreRender </b>Allows final changes to the page or its control. This event takes place
after all regular PostBack events have taken place. This event takes place before
saving ViewState, so any changes made here are saved.
<br />
For example : After this event, you cannot change any property of a button or change
any viewstate value. Because, after this event, SaveStateComplete and Render events
are called.
<br />
EXAMPLE : Override the event as given below in your code-behind cs file of your
aspx page
<br />
<pre class="brush:csharp;">protected override void OnPreRender(EventArgs e)
{
// Each data bound control whose DataSourceID property is set calls its DataBind method.
// The PreRender event occurs for each control on the page. Use the event to make final changes to the contents of the page or its controls.
}
</pre>
</div>
<hr />
<br />
<div>
(9)<b>SaveStateComplete </b>Prior to this event the view state for the page and its controls
is set. Any changes to the page’s controls at this point or beyond are ignored.
<br />
EXAMPLE : Override the event as given below in your code-behind cs file of your
aspx page
<br />
<pre class="brush:csharp;">protected override void OnSaveStateComplete(EventArgs e)
{
// Before this event occurs, ViewState has been saved for the page and for all controls. Any changes to the page or controls at this point will be ignored. // Use this event perform tasks that require view state to be saved, but that do not make any changes to controls.
}
</pre>
</div>
<hr />
<br />
<div>
(10)<b>Render </b>This is a method of the page object and its controls (and not an event).
At this point, ASP.NET calls this method on each of the page’s controls to get its
output. The Render method generates the client-side HTML, Dynamic Hypertext Markup
Language (DHTML), and script that are necessary to properly display a control at
the browser. Note: Right click on the web page displayed at client's browser and
view the Page's Source. You will not find any aspx server control in the code. Because
all aspx controls are converted to their respective HTML representation. Browser
is capable of displaying HTML and client side scripts.
<br />
EXAMPLE : Override the event as given below in your code-behind cs file of your
aspx page
<br />
</div>
<hr />
<br />
<div>
(11) <b>UnLoad </b>This event is used for cleanup code. After the page's HTML is rendered,
the objects are disposed of. During this event, you should destroy any objects or
references you have created in building the page. At this point, all processing
has occurred and it is safe to dispose of any remaining objects, including the Page
object. Cleanup can be performed on-
<br />
(a)Instances of classes i.e. objects<br />
(b)Closing opened files<br />
(c)Closing database connections.
<br />
EXAMPLE : Override the event as given below in your code-behind cs file of your
aspx page
<br />
<pre class="brush:csharp;"> protected void Page_UnLoad(object sender, EventArgs e)
{
// This event occurs for each control and then for the page. In controls,
use this event to do final cleanup for specific controls, such as closing control-specific database connections.
// During the unload stage, the page and its controls have been rendered, so you cannot make further changes to the response stream.
//If you attempt to call a method such as the Response.Write method, the page will throw an exception.
}
</pre>
</div>
<hr />
<br />
For More Reference : Follow the below links
<br />
(1)<a href="http://www.15seconds.com/issue/020102.htm">http://www.15seconds.com/issue/020102.htm</a>
<br />
(2) <a href="http://msdn.microsoft.com/en-us/library/ms178472.aspx">http://msdn.microsoft.com/en-us/library/ms178472.aspx</a>
<br />
(3) <a href="http://www.devlifestyle.net/blogs/articles/archive/2009/05/24/asp-net-internals-viewstate-and-page-life-cycle.aspx">
http://www.devlifestyle.net/blogs/articles/archive/2009/05/24/asp-net-internals-viewstate-and-page-life-cycle.aspx
</a>
<br />
<br />
Thank You...Anonymoushttp://www.blogger.com/profile/04793789893946649568noreply@blogger.com1tag:blogger.com,1999:blog-6823701262697705013.post-28541607151547468212012-05-15T22:33:00.002-07:002012-07-06T00:18:05.801-07:00ASP.Net Custom PagerCreate simple ASP.Net custom pager for List View, Grid View,etc. with SQL paging.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjnCNsGGhyRg4HWrZXSQRHyCxnmYW20Ztpg4V7BmRa6Af2ZrSrnIaDd1ZRtHWTczQ193It67OF5U9B0nVtGMe8rj93lKwj124Hiew0A-wfLG_ImAbeC5jifHoKps_ALHD-Md3VtDfhK_c33/s1600/1337143890925-uploadscreenshot-dot-com.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="156" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjnCNsGGhyRg4HWrZXSQRHyCxnmYW20Ztpg4V7BmRa6Af2ZrSrnIaDd1ZRtHWTczQ193It67OF5U9B0nVtGMe8rj93lKwj124Hiew0A-wfLG_ImAbeC5jifHoKps_ALHD-Md3VtDfhK_c33/s640/1337143890925-uploadscreenshot-dot-com.png" width="640" /></a></div>
<br />
<br />
<br />
Create a user control for Paging and add to main page
<br />
<pre class="brush:html;"><%@ Register Src="~/SysControls/SysAdminPager.ascx" TagName="DataPagerControl" TagPrefix="uc1" %>
.
.
.
</pre>
<br />
Using a simple list view for binding data.
<br />
<pre class="brush:html;"><uc1:DataPagerControl ID="sysPager" runat="server" />
<asp:ListView ID="lstView" runat="server">
<LayoutTemplate>
<table class="normal fullwidth">
<thead>
<tr style="background-color: #EEE">
<th>
ID
</th>
<th>
Name
</th>
<th>
Address
</th>
</tr>
</thead>
<tbody>
<asp:PlaceHolder ID="itemPlaceHolder" runat="server"></asp:PlaceHolder>
</tbody>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr class='<%# (Container.DataItemIndex+1)%2==0?"":"odd" %>'>
<td>
<%#Eval("ID") %>
</td>
<td>
.
.
.
</pre>
<br />
<br />
On Page Load Reginster Event handler for Pager Control.
Use Sql Paging..pass your page number and page size SP and return data and totalrow count .
Set page properties using pagenumber,pagesize and total rows
<br />
<pre class="brush:csharp;">
protected void Page_Load(object sender, EventArgs e)
{
sysPager.PageChanged += new EventHandler<PageEventArgs>(sysPager_PageChanged);
if (!IsPostBack)
{
BindData();
}
}
void sysPager_PageChanged(object sender, PageEventArgs e)
{
BindData(e.StartRowIndex, e.MaximumRows);
}
void BindData(int pagenumber = 1, int pagesize = 20)
{
SampleCollectionML lstCollection = SampleBL.SelectAll(new SampleML { PageNumber = pagenumber, PageSize = pagesize });
if (lstCollection.Count > 0)
{
lstView.DataSource = lstCollection;
lstView.DataBind();
sysPager.SetPageProperties(pagenumber, pagesize, lstCollection[0].TotalRows);
}
}
</pre>
<br />
<br />
Source code User Control For Pager
<br />
<pre class="brush:html;ruler: true;"> <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="SysAdminPager.ascx.cs"
Inherits=" GradeBook.SysControls.SysAdminPager" %>
<div class="pager-container">
<div style="float: left; margin-right: 15px; vertical-align: middle">
Page size:
<asp:DropDownList ID="ddlPageSize" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlPageSize_SelectedIndexChanged"
Style="padding: 2px;">
<asp:ListItem Value="10" Text="10"></asp:ListItem>
<asp:ListItem Value="20" Text="20"></asp:ListItem>
<asp:ListItem Value="50" Text="50"></asp:ListItem>
<asp:ListItem Value="100" Text="100"></asp:ListItem>
</asp:DropDownList>
</div>
<asp:Repeater ID="rpt" runat="server">
<HeaderTemplate>
<div class='<%# PagerCss %>'>
<div style="float: left; padding: 4px 0 2px;">
Page <b>
<%# Convert.ToInt32(TotalRowCount > 0 ? CurrentPage : 0)%>
</b>of <b>
<%# Convert.ToInt32(MaximumRows>0? Math.Ceiling((double)TotalRowCount / MaximumRows):0)%>
</b>(<%# TotalRowCount %>
item(s))
</div>
<div style="float: right; padding-top: 2px;">
<asp:LinkButton ID="lnkbFirst" CommandName="<%#PageChangedItemCommand %>" CommandArgument="1"
runat="server" ToolTip="First" CssClass="page-text">&laquo;First</asp:LinkButton>&nbsp;
<asp:LinkButton ID="lnkbPrevious" CommandName="<%#PageChangedItemCommand %>" CommandArgument="<%#PreviousPageIndex%>"
runat="server" ToolTip="Previous" CssClass="page-text">&laquo;Prev</asp:LinkButton>
&nbsp;
</HeaderTemplate>
<ItemTemplate>
<asp:LinkButton CommandName="<%#PageChangedItemCommand %>" CommandArgument='<%#DataBinder.Eval(Container.DataItem, "Page")%>'
ID="p" runat="server"><%#DataBinder.Eval(Container.DataItem, "Text")%>&nbsp;</asp:LinkButton>
</ItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="lnkbNext" CommandName='<%#PageChangedItemCommand %>' CommandArgument="<%#NextPageIndex%>"
runat="server" ToolTip="Next" CssClass="page-text">Next &raquo;</asp:LinkButton>&nbsp;
<asp:LinkButton ID="lnkbLast" CommandName="<%#PageChangedItemCommand %>" CommandArgument="<%#PagesCount%>"
runat="server" ToolTip="Last" CssClass="page-text">Last &raquo;</asp:LinkButton>
</div> </div>
</FooterTemplate>
</asp:Repeater>
<div style="float: right; margin-right: 6px">
Go to:
<asp:DropDownList ID="ddlPageNumber" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlPageNumber_SelectedIndexChanged"
Style="padding: 2px;">
</asp:DropDownList>
</div>
<div class="clear">
</div>
</div>
</pre>
<br />
<br />
A Class for holding Paging parameter
<br />
<pre class="brush:csharp;"> public class SysPager
{
public int Page { get; set; }
public string Text { get; set; }
public SysPager(int _p, string _t)
{
Page = _p;
Text = _t;
}
}
</pre>
<br />
<br />
Page Propeties for holding paging information
<br />
<pre class="brush:csharp;"> //public partial class SysAdminPager : System.Web.UI.UserControl
// {
// Summary:
// Gets the maximum number of records to display on each page.
//
// Returns:
// The maximum number of records to display on each page.
public int MaximumRows
{
get
{
return (int)(ViewState["MaximumRows"] ?? 10);
}
set
{
ViewState["MaximumRows"] = value;
}
}
//
// Summary:
// Gets the index of the first record on a page.
//
// Returns:
// The index of the first record on a page.
public int CurrentPage
{
get
{
return (int)(ViewState["CurrentPage"] ?? 1);
}
set
{
ViewState["CurrentPage"] = value;
}
}
//
// Summary:
// Gets the total number of records in the underlying data source.
//
// Returns:
// The total number of records of the underlying data source.
public int TotalRowCount
{
get
{
return (int)(ViewState["TotalRowCount"] ?? 0);
}
set
{
ViewState["TotalRowCount"] = value;
}
}
public int ButtonCount
{
get
{
return (int)(ViewState["ButtonCount"] ?? 10);
}
set
{
ViewState["ButtonCount"] = value;
}
}
private int _pagesCount;
public int PagesCount
{
get
{
if (TotalRowCount == 0)
return _pagesCount = 0;
else if (TotalRowCount % MaximumRows == 0)
return _pagesCount = (TotalRowCount / MaximumRows);
else
return _pagesCount = ((TotalRowCount / MaximumRows) + 1);
}
private set
{
_pagesCount = value;
}
}
public string PagerCss
{
get
{
return (string)(ViewState["PagerCss"] ?? "pagination-default");
}
set
{
ViewState["PagerCss"] = value;
}
}
protected int NextPageIndex { get { return CurrentPage + 1; } }
protected int PreviousPageIndex { get { return CurrentPage - 1; } }
</pre>
<br />
<br />
Page Changing Event Declaration and Invoking
<br />
<pre class="brush:csharp;"> public event EventHandler<PageEventArgs> PageChanged;
protected const string PageChangedItemCommand = "PageChanged";
private const string CurrentPageCssStyle = "current";//"font-weight:bold; font-size:15px;";
private void RaiseEvent(int currentPage)
{
if (PageChanged != null)
PageChanged(this, new PageEventArgs(currentPage, MaximumRows, TotalRowCount));
}
</pre>
<br />
<br />
Create Paging data using Totalrows,Pagesize and button count
<br />
<pre class="brush:csharp;">
protected List<SysPager> DataSource
{
get
{
List<SysPager> pages = new List<SysPager>();
int _startpage = 1;
int _endpage = PagesCount;
bool showMore_first = false;
bool showMore_last = false;
if (PagesCount > ButtonCount)
{
if (CurrentPage - (ButtonCount / 2) > 1)
{
_startpage = CurrentPage - (ButtonCount / 2);
showMore_first = true;
}
if (CurrentPage + (ButtonCount / 2) < PagesCount)
{
_endpage = CurrentPage + (ButtonCount / 2);
if (_endpage < ButtonCount)
_endpage = ButtonCount;
showMore_last = true;
}
}
if (showMore_first)
{
pages.Add(new SysPager(_startpage - 1, "..."));
}
for (int i = _startpage; i <= _endpage; i++)
{
pages.Add(new SysPager(i, i.ToString()));
}
if (showMore_last)
{
pages.Add(new SysPager(_endpage + 1, "..."));
}
return pages;
}
}
public SysAdminPager()
{
CurrentPage = 1;
MaximumRows = 1;
TotalRowCount = 1;
}
</pre>
<br />
<br />
Page Load And Other Events
<br />
<pre class="brush:csharp;"> protected void Page_Load(object sender, EventArgs e)
{
rpt.ItemCommand += new RepeaterCommandEventHandler(rpt_ItemCommand);
if (!Page.IsPostBack)
{
//CurrentPageSetCssStyle(CurrentPageCssStyle);
// SetupCommandArguments();
}
}
void rpt_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == PageChangedItemCommand)
{
CurrentPage = int.Parse(e.CommandArgument.ToString());
CurrentPageSetCssStyle(CurrentPageCssStyle);
// SetupCommandArguments();
SetPageProperties();
RaiseEvent(CurrentPage);
}
}
private void CurrentPageSetCssStyle(string style)
{
ddlPageNumber.SetDropDownSelectedValue(CurrentPage);
ddlPageSize.SetDropDownSelectedValue(MaximumRows);
foreach (RepeaterItem item in rpt.Items)
{
LinkButton lnkButton = item.FindControl("p") as LinkButton;
if (lnkButton != null)
{
if (lnkButton.CommandArgument == CurrentPage.ToString())
lnkButton.Attributes.Add("class", style);
}
}
// SetupCommandArguments();
}
void SetupCommandArguments()
{
LinkButton lnkbPrevious = rpt.Controls[0].Controls[0].FindControl("lnkbPrevious") as LinkButton;
LinkButton lnkbFirst = rpt.Controls[0].Controls[0].FindControl("lnkbFirst") as LinkButton;
if (lnkbPrevious != null)
{
if (CurrentPage == 1 || PagesCount == 0)
{
lnkbPrevious.Enabled = false;
lnkbFirst.Enabled = false;
lnkbPrevious.CommandArgument = (CurrentPage).ToString();
}
else
{
lnkbPrevious.Enabled = true;
lnkbFirst.Enabled = true;
lnkbPrevious.CommandArgument = (CurrentPage - 1).ToString();
}
}
LinkButton lnkbNext = rpt.Controls[rpt.Controls.Count - 1].Controls[0].FindControl("lnkbNext") as LinkButton;
LinkButton lnkbLast = rpt.Controls[rpt.Controls.Count - 1].Controls[0].FindControl("lnkbLast") as LinkButton;
if (lnkbNext != null)
{
if (CurrentPage == PagesCount || PagesCount == 0)
{
lnkbNext.CommandArgument = (CurrentPage).ToString();
lnkbNext.Enabled = false;
lnkbLast.Enabled = false;
}
else
{
lnkbNext.CommandArgument = (CurrentPage + 1).ToString();
lnkbNext.Enabled = true;
lnkbLast.Enabled = true;
}
}
}
internal void SetPageProperties(int _startpage, int _maxrows, int _totrows)
{
CurrentPage = _startpage;
MaximumRows = _maxrows;
TotalRowCount = _totrows;
SetPageProperties();
}
internal void SetPageProperties()
{
rpt.DataSource = DataSource;
rpt.DataBind();
SetupCommandArguments();
ddlPageNumber.Items.Clear();
for (int i = 1; i <= PagesCount; i++)
{
ddlPageNumber.Items.Add(new ListItem(i.ToString(), i.ToString()));
}
CurrentPageSetCssStyle(CurrentPageCssStyle);
}
</pre>
<br />
<br />
Dropdown LIst Changing Events
<br />
<pre class="brush:csharp;">
protected void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
MaximumRows = int.Parse(ddlPageSize.SelectedValue);
if (PagesCount < CurrentPage)
CurrentPage = PagesCount;
CurrentPageSetCssStyle(CurrentPageCssStyle);
SetPageProperties();
RaiseEvent(CurrentPage);
}
catch (Exception)
{
}
}
protected void ddlPageNumber_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
CurrentPage = int.Parse(ddlPageNumber.SelectedValue);
CurrentPageSetCssStyle(CurrentPageCssStyle);
SetPageProperties();
RaiseEvent(CurrentPage);
}
catch (Exception)
{
}
}
}
</pre>
<br />
<br />
<br />
You can change theme Gray,Blue,Red,Green.
<br />
<pre class="brush:css;ruler: true;"> /*######################################################## Pagination ########################################################*/
.pager-container {
background: -moz-linear-gradient(center top , #FBFBFB, #F5F5F5) repeat scroll 0 0 transparent;
border: 1px solid #CBC5C5;
border-radius: 5px 5px 5px 5px;
padding: 5px 8px;
}
.pagination a{font-size: 9px !important;text-transform: uppercase; /* background-color: #FFFFFF;*/border: 1px #5e90c3 solid;color: #5e90c3;padding: 1px 3px;
text-decoration: none;outline: none;}
.pagination a:hover{ color: white;background-color: #5e90c3;border: 1px #5e90c3 solid;}
.pagination a.current,.pagination a:hover{font-size: 9px;text-transform: uppercase;background-color: #5e90c3;
border: 1px solid #F2F2F2;color: white;padding: 1px 5px;text-decoration: none;outline: none;}
.pagination a[disabled=disabled]{ background-color: #CCCCCC;border: 1px solid #F2F2F2;color: #003366;}
/* $$$$$$$$$$$$$$ Default $$$$$$$$$$$$$$$$*/
.pagination-default a{
font-size: 10px !important;text-transform: uppercase;color: #606060;border: 1px solid #DDDDDD;border-radius: 4px;
padding: 2px 3px; cursor: pointer; outline: none !important; text-align: center; text-decoration: none;
/*border-color: #c0c0c0 #d4d4d4 #dbdbdb;text-shadow: 0px -1px 0px #fff;
background: -moz-linear-gradient(top,#ebebeb,#f4f4f4 50%,#fff); background: -webkit-gradient(linear, left top, left bottom, from(#ebebeb), color-stop(0.5, #f4f4f4),to(#fff));
filter: progid:DXImageTransform.Microsoft.Gradient(StartColorStr='#f4f4f4', EndColorStr='#ffffff');*/ }
.pagination-default a.current,.pagination-default a:hover { color: #606060; text-shadow: 0px 1px 0px #fff;
border-color: #D0D0D0; box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);}
.pagination-default a:hover{ background: #f1f1f1;}
.pagination-default a.current{ box-shadow:none; background-color: #e0e0e0; background: -moz-linear-gradient(top,#e0e0e0,#f4f4f4 50%,#e0e0e0));
background: -webkit-gradient(linear, left top, left bottom,from(#fff),color-stop(0.5, #f4f4f4),to(#e0e0e0));
filter: progid:DXImageTransform.Microsoft.Gradient(StartColorStr='#f4f4f4', EndColorStr='#e0e0e0');}
.pagination-default a[disabled=disabled]{ color: #aaa;}
.pagination-default a.page-text{border:none;text-decoration:underline;}
/* $$$$$$$$$$$$$$ ORANGE $$$$$$$$$$$$$$$$*/
/* $$$$$$$$$$$$$$ GRAY $$$$$$$$$$$$$$$$*/
.pagination-gray a{ font-size: 9px !important;text-transform: uppercase; border: 1px #5e90c3 solid;color: #5e90c3;padding: 1px 3px;
cursor: pointer; outline: none !important; text-align: center; text-decoration: none; -moz-border-radius: 3px;
-webkit-border-radius: 3px; -khtml-border-radius: 3px; border-radius: 3px;
-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,0.5); -webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,0.5);
-khtml-box-shadow:inset 0 1px 0 rgba(255,255,255,0.5); box-shadow:inset 0 1px 0 rgba(255,255,255,0.5);
background: #f1f1f1; background: -webkit-gradient(linear, left top, left bottom, from(#e9e9e9), to(#d1d1d1));
background: -moz-linear-gradient(top, #e9e9e9, #d1d1d1); -pie-background: linear-gradient(top, #e9e9e9, #d1d1d1);
border: 1px solid #bbb; color: #555; text-shadow: 0 1px 0 #fff;
}
.pagination-gray a.current ,.pagination-gray a:hover { background: #fff; -pie-background: #fff; color: #666;}
.pagination-gray a[disabled=disabled]{ color: #aaa;}
/* $$$$$$$$$$$$$$ WHITE $$$$$$$$$$$$$$$$*/
.pagination-white a{
font-size: 9px !important;text-transform: uppercase; /* background-color: #FFFFFF;*/border: 1px #D8D8D8 solid;color: #606060;padding: 1px 3px;
cursor: pointer; outline: none !important; text-align: center; text-decoration: none;
-moz-border-radius: 3px; -webkit-border-radius: 3px; -khtml-border-radius: 3px; border-radius: 3px;
-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,0.5); -webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,0.5); -khtml-box-shadow:inset 0 1px 0 rgba(255,255,255,0.5); box-shadow:inset 0 1px 0 rgba(255,255,255,0.5);
background: #fff; -pie-background: #fff; border: 1px solid #bbb; color: #555;
text-shadow: 0 1px 0 #fff; }
.pagination-white a.current,.pagination-white a:hover { background: #f1f1f1;background: -webkit-gradient(linear, left top, left bottom, from(#e9e9e9), to(#d1d1d1));
background: -moz-linear-gradient(top, #e9e9e9, #d1d1d1); -pie-background: linear-gradient(top, #e9e9e9, #d1d1d1);
color: #666;}
.pagination-white a[disabled=disabled]{ color: #aaa;}
/* $$$$$$$$$$$$$$ ORANGE $$$$$$$$$$$$$$$$*/
.pagination-orange a
{
font-size: 9px !important;text-transform: uppercase; /* background-color: #FFFFFF;*/border: 1px #D8D8D8 solid;color: #606060;padding: 1px 3px;
cursor: pointer; outline: none !important; text-align: center; text-decoration: none;
-moz-border-radius: 3px; -webkit-border-radius: 3px; -khtml-border-radius: 3px; border-radius: 3px;
background: #f78d1d;
background: -webkit-gradient(linear, left top, left bottom, from(#faa51a), to(#f47a20));
background: -moz-linear-gradient(top, #faa51a, #f47a20);
-pie-background: linear-gradient(top, #faa51a, #f47a20);
border: solid 1px #dd6611;
color: #fef4e9;
text-shadow: 0 1px 1px rgba(0,0,0,0.25);
}
.pagination-orange a.current,.pagination-orange a:hover {
background: #EEEEEE;
background: -webkit-gradient(linear, left top, left bottom, from(#FFFFFF), to(#EEEEEE));
background: -moz-linear-gradient(top, #FFFFFF, #EEEEEE);
-pie-background: linear-gradient(top, #FFFFFF, #EEEEEE);
border: solid 1px #F88E11;
color: #F88E11;
}
.pagination-orange a[disabled=disabled]
{
color: #d1d1d1;
}
/* $$$$$$$$$$$$$$ RED $$$$$$$$$$$$$$$$*/
.pagination-red a
{
font-size: 9px !important;text-transform: uppercase; /* background-color: #FFFFFF;*/border: 1px #D8D8D8 solid;color: #606060;padding: 1px 3px;
cursor: pointer; outline: none !important; text-align: center; text-decoration: none;
-moz-border-radius: 3px; -webkit-border-radius: 3px; -khtml-border-radius: 3px; border-radius: 3px;
background-color: #C44747;
background: -moz-linear-gradient(top, #DD5F5F 10%, #A92C2C 90%);
background: -webkit-gradient(linear, left top, left bottom, color-stop(0.1, #DD5F5F), color-stop(0.9, #A92C2C));
-pie-background: linear-gradient(top, #DD5F5F 10%, #A92C2C 90%);
border: 1px solid #A92C2C;
color: #fef4e9;
text-shadow: 0 1px 1px rgba(0,0,0,0.25);
}
.pagination-red a.current,.pagination-red a:hover {
background-color: #FFFFFF;
background: -moz-linear-gradient(top, #FFFFFF 10%, #EEEEEE 90%);
background: -webkit-gradient(linear, left top, left bottom, color-stop(0.1, #FFFFFF ), color-stop(0.9, #EEEEEE));
-pie-background: linear-gradient(top, #FFFFFF 10%, #EEEEEE 90%);
border: 1px solid #ccc;
color: #000;
}
.pagination-red a[disabled=disabled]
{
color: #CCCCCC;
}
/* $$$$$$$$$$$$$$ BLUE $$$$$$$$$$$$$$$$*/
.pagination-blue a
{
font-size: 9px !important;text-transform: uppercase; /* background-color: #FFFFFF;*/border: 1px #D8D8D8 solid;color: #606060;padding: 3px 3px;
cursor: pointer; outline: none !important; text-align: center; text-decoration: none;
-moz-border-radius: 3px; -webkit-border-radius: 3px; -khtml-border-radius: 3px; border-radius: 3px;
background: #0095cd;
background: -webkit-gradient(linear, left top, left bottom, from(#00adee), to(#0078a5));
background: -moz-linear-gradient(top, #00adee, #0078a5);
-pie-background: linear-gradient(top, #00adee, #0078a5);
border: 1px solid #034462;
color: #fff;
text-shadow: 0 1px 1px rgba(0,0,0,0.25);
}
.pagination-blue a.current,.pagination-blue a:hover {
background: #EEE;
background: -webkit-gradient(linear, left top, left bottom, from(#EEE), to(#FFF));
background: -moz-linear-gradient(top, #EEE, #FFF);
-pie-background: linear-gradient(top, #EEE, #FFF);
border: 1px solid #234;
color: #000;
}
.pagination-blue a[disabled=disabled]{ color: #ccc;}
/* $$$$$$$$$$$$$$ GREEN $$$$$$$$$$$$$$$$*/
.pagination-green a
{
font-size: 9px !important;text-transform: uppercase; /* background-color: #FFFFFF;*/border: 1px #D8D8D8 solid;color: #606060;padding: 1px 3px;
cursor: pointer; outline: none !important; text-align: center; text-decoration: none;
-moz-border-radius: 3px; -webkit-border-radius: 3px; -khtml-border-radius: 3px; border-radius: 3px;
color: #fff;
background: #8fc857;
background: -webkit-gradient(linear, left top, left bottom, from(#8fc857), to(#5c9425));
background: -moz-linear-gradient(top, #8fc857, #5c9425);
-pie-background: linear-gradient(top, #8fc857, #5c9425);
text-shadow: 0 1px 1px rgba(0,0,0,0.25);
border:1px solid #561;
}
.pagination-green a.current,.pagination-green a:hover {
background: #E9E9E9;
background: -webkit-gradient(linear, left top, left bottom, from(#E9E9E9), to(#D1D1D1));
background: -moz-linear-gradient(top, #E9E9E9, #D1D1D1);
-pie-background: linear-gradient(top, #E9E9E9, #D1D1D1);
border:1px solid #342;
}
.pagination-green a[disabled=disabled]
{
color: #ccc;
}
/* $$$$$$$$$$$$$$ PAGINATIOn END $$$$$$$$$$$$$$$$*/
</pre>Anonymoushttp://www.blogger.com/profile/04793789893946649568noreply@blogger.com0tag:blogger.com,1999:blog-6823701262697705013.post-13661508992996908472012-05-15T07:23:00.002-07:002012-06-22T06:18:30.948-07:00DateTime.ToString() Patterns<br />
<div class="left">
<div class="left_articles">
<div class="article">
<h1>
DateTime.ToString() Patterns
</h1>
<div>
<br /></div>
<div>
<a href="http://www.geekzilla.co.uk/View00FF7904-B510-468C-A2C8-F859AA20581F.htm">http://www.geekzilla.co.uk/View00FF7904-B510-468C-A2C8-F859AA20581F.htm</a></div>
<h2>
All the patterns:
</h2>
<table cellpadding="2" cellspacing="1" class="TableClass">
<tbody>
<tr>
<td class="TableCell">0</td>
<td class="TableCell">MM/dd/yyyy</td>
<td class="TableCell">08/22/2006 </td>
</tr>
<tr>
<td class="TableCell">1</td>
<td class="TableCell">dddd, dd MMMM yyyy</td>
<td class="TableCell">Tuesday, 22 August 2006 </td>
</tr>
<tr>
<td class="TableCell">2</td>
<td class="TableCell">dddd, dd MMMM yyyy</td>
<td class="TableCell">HH:mm Tuesday, 22 August 2006 06:30 </td>
</tr>
<tr>
<td class="TableCell">3</td>
<td class="TableCell">dddd, dd MMMM yyyy</td>
<td class="TableCell">hh:mm tt Tuesday, 22 August 2006 06:30 AM </td>
</tr>
<tr>
<td class="TableCell">4</td>
<td class="TableCell">dddd, dd MMMM yyyy</td>
<td class="TableCell">H:mm Tuesday, 22 August 2006 6:30 </td>
</tr>
<tr>
<td class="TableCell">5</td>
<td class="TableCell">dddd, dd MMMM yyyy</td>
<td class="TableCell">h:mm tt Tuesday, 22 August 2006 6:30 AM </td>
</tr>
<tr>
<td class="TableCell">6</td>
<td class="TableCell">dddd, dd MMMM yyyy HH:mm:ss</td>
<td class="TableCell">Tuesday, 22 August 2006 06:30:07 </td>
</tr>
<tr>
<td class="TableCell">7</td>
<td class="TableCell">MM/dd/yyyy HH:mm</td>
<td class="TableCell">08/22/2006 06:30 </td>
</tr>
<tr>
<td class="TableCell">8</td>
<td class="TableCell">MM/dd/yyyy hh:mm tt</td>
<td class="TableCell">08/22/2006 06:30 AM </td>
</tr>
<tr>
<td class="TableCell">9</td>
<td class="TableCell">MM/dd/yyyy H:mm</td>
<td class="TableCell">08/22/2006 6:30 </td>
</tr>
<tr>
<td class="TableCell">10</td>
<td class="TableCell">MM/dd/yyyy h:mm tt</td>
<td class="TableCell">08/22/2006 6:30 AM </td>
</tr>
<tr>
<td class="TableCell">10</td>
<td class="TableCell">MM/dd/yyyy h:mm tt</td>
<td class="TableCell">08/22/2006 6:30 AM </td>
</tr>
<tr>
<td class="TableCell">10</td>
<td class="TableCell">MM/dd/yyyy h:mm tt</td>
<td class="TableCell">08/22/2006 6:30 AM </td>
</tr>
<tr>
<td class="TableCell">11</td>
<td class="TableCell">MM/dd/yyyy HH:mm:ss</td>
<td class="TableCell">08/22/2006 06:30:07</td>
</tr>
<tr>
<td class="TableCell">12</td>
<td class="TableCell">MMMM dd</td>
<td class="TableCell">August 22 </td>
</tr>
<tr>
<td class="TableCell">13</td>
<td class="TableCell">MMMM dd</td>
<td class="TableCell">August 22 </td>
</tr>
<tr>
<td class="TableCell">14</td>
<td class="TableCell">yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK</td>
<td class="TableCell">2006-08-22T06:30:07.7199222-04:00 </td>
</tr>
<tr>
<td class="TableCell">15</td>
<td class="TableCell">yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK</td>
<td class="TableCell">2006-08-22T06:30:07.7199222-04:00 </td>
</tr>
<tr>
<td class="TableCell">16</td>
<td class="TableCell">ddd, dd MMM yyyy HH':'mm':'ss 'GMT'</td>
<td class="TableCell">Tue, 22 Aug 2006 06:30:07 GMT </td>
</tr>
<tr>
<td class="TableCell">17</td>
<td class="TableCell">ddd, dd MMM yyyy HH':'mm':'ss 'GMT'</td>
<td class="TableCell">Tue, 22 Aug 2006 06:30:07 GMT </td>
</tr>
<tr>
<td class="TableCell">18</td>
<td class="TableCell">yyyy'-'MM'-'dd'T'HH':'mm':'ss</td>
<td class="TableCell">2006-08-22T06:30:07 </td>
</tr>
<tr>
<td class="TableCell">19</td>
<td class="TableCell">HH:mm</td>
<td class="TableCell">06:30 </td>
</tr>
<tr>
<td class="TableCell">20</td>
<td class="TableCell">hh:mm tt</td>
<td class="TableCell">06:30 AM </td>
</tr>
<tr>
<td class="TableCell">21</td>
<td class="TableCell">H:mm</td>
<td class="TableCell">6:30 </td>
</tr>
<tr>
<td class="TableCell">22</td>
<td class="TableCell">h:mm tt</td>
<td class="TableCell">6:30 AM </td>
</tr>
<tr>
<td class="TableCell">23</td>
<td class="TableCell">HH:mm:ss</td>
<td class="TableCell">06:30:07 </td>
</tr>
<tr>
<td class="TableCell">24</td>
<td class="TableCell">yyyy'-'MM'-'dd HH':'mm':'ss'Z'</td>
<td class="TableCell">2006-08-22 06:30:07Z </td>
</tr>
<tr>
<td class="TableCell">25</td>
<td class="TableCell">dddd, dd MMMM yyyy HH:mm:ss</td>
<td class="TableCell">Tuesday, 22 August 2006 06:30:07 </td>
</tr>
<tr>
<td class="TableCell">26</td>
<td class="TableCell">yyyy MMMM</td>
<td class="TableCell">2006 August </td>
</tr>
<tr>
<td class="TableCell">27</td>
<td class="TableCell">yyyy MMMM</td>
<td class="TableCell">2006 August </td>
</tr>
</tbody></table>
<h2>
The patterns for DateTime.ToString ( 'd' ) :
</h2>
<table cellpadding="2" cellspacing="1" class="TableClass">
<tbody>
<tr>
<td class="TableCell">0</td>
<td class="TableCell">MM/dd/yyyy</td>
<td class="TableCell">08/22/2006 </td>
</tr>
</tbody></table>
<h2>
The patterns for DateTime.ToString ( 'D' ) :
</h2>
<table cellpadding="2" cellspacing="1" class="TableClass">
<tbody>
<tr>
<td class="TableCell">0</td>
<td class="TableCell">dddd, dd MMMM yyyy</td>
<td class="TableCell">Tuesday, 22 August 2006 </td>
</tr>
</tbody></table>
<h2>
The patterns for DateTime.ToString ( 'f' ) :
</h2>
<table cellpadding="2" cellspacing="1" class="TableClass">
<tbody>
<tr>
<td class="TableCell">0</td>
<td class="TableCell">dddd, dd MMMM yyyy HH:mm</td>
<td class="TableCell">Tuesday, 22 August 2006 06:30 </td>
</tr>
<tr>
<td class="TableCell">1</td>
<td class="TableCell">dddd, dd MMMM yyyy hh:mm</td>
<td class="TableCell">tt Tuesday, 22 August 2006 06:30 AM </td>
</tr>
<tr>
<td class="TableCell">2</td>
<td class="TableCell">dddd, dd MMMM yyyy H:mm</td>
<td class="TableCell">Tuesday, 22 August 2006 6:30 </td>
</tr>
<tr>
<td class="TableCell">3</td>
<td class="TableCell">dddd, dd MMMM yyyy h:mm</td>
<td class="TableCell">tt Tuesday, 22 August 2006 6:30 AM </td>
</tr>
</tbody></table>
<h2>
The patterns for DateTime.ToString ( 'F' ) :
</h2>
<table cellpadding="2" cellspacing="1" class="TableClass">
<tbody>
<tr>
<td class="TableCell">0</td>
<td class="TableCell">dddd, dd MMMM yyyy HH:mm:ss</td>
<td class="TableCell">Tuesday, 22 August 2006 06:30:07 </td>
</tr>
</tbody></table>
<h2>
The patterns for DateTime.ToString ( 'g' ) :
</h2>
<table cellpadding="2" cellspacing="1" class="TableClass">
<tbody>
<tr>
<td class="TableCell">0</td>
<td class="TableCell">MM/dd/yyyy HH:mm</td>
<td class="TableCell">08/22/2006 06:30 </td>
</tr>
<tr>
<td class="TableCell">1</td>
<td class="TableCell">MM/dd/yyyy hh:mm</td>
<td class="TableCell">tt 08/22/2006 06:30 AM </td>
</tr>
<tr>
<td class="TableCell">2</td>
<td class="TableCell">MM/dd/yyyy H:mm</td>
<td class="TableCell">08/22/2006 6:30 </td>
</tr>
<tr>
<td class="TableCell">3</td>
<td class="TableCell">MM/dd/yyyy h:mm tt</td>
<td class="TableCell">08/22/2006 6:30 AM </td>
</tr>
</tbody></table>
<h2>
The patterns for DateTime.ToString ( 'G' ) :
</h2>
<table cellpadding="2" cellspacing="1" class="TableClass">
<tbody>
<tr>
<td class="TableCell">0</td>
<td class="TableCell">MM/dd/yyyy HH:mm:ss</td>
<td class="TableCell">08/22/2006 06:30:07 </td>
</tr>
</tbody></table>
<h2>
The patterns for DateTime.ToString ( 'm' ) :
</h2>
<table cellpadding="2" cellspacing="1" class="TableClass">
<tbody>
<tr>
<td class="TableCell">0</td>
<td class="TableCell">MMMM dd</td>
<td class="TableCell">August 22 </td>
</tr>
</tbody></table>
<h2>
The patterns for DateTime.ToString ( 'r' ) :
</h2>
<table cellpadding="2" cellspacing="1" class="TableClass">
<tbody>
<tr>
<td class="TableCell">0</td>
<td class="TableCell">ddd, dd MMM yyyy HH':'mm':'ss 'GMT'</td>
<td class="TableCell">Tue, 22 Aug 2006 06:30:07 GMT </td>
</tr>
</tbody></table>
<h2>
The patterns for DateTime.ToString ( 's' ) :
</h2>
<table cellpadding="2" cellspacing="1" class="TableClass">
<tbody>
<tr>
<td class="TableCell">0</td>
<td class="TableCell">yyyy'-'MM'-'dd'T'HH':'mm':'ss</td>
<td class="TableCell">2006-08-22T06:30:07 </td>
</tr>
</tbody></table>
<h2>
The patterns for DateTime.ToString ( 'u' ) :
</h2>
<table cellpadding="2" cellspacing="1" class="TableClass">
<tbody>
<tr>
<td class="TableCell">0</td>
<td class="TableCell">yyyy'-'MM'-'dd HH':'mm':'ss'Z'</td>
<td class="TableCell">2006-08-22 06:30:07Z </td>
</tr>
</tbody></table>
<h2>
The patterns for DateTime.ToString ( 'U' ) :
</h2>
<table cellpadding="2" cellspacing="1" class="TableClass">
<tbody>
<tr>
<td class="TableCell">0</td>
<td class="TableCell">dddd, dd MMMM yyyy HH:mm:ss</td>
<td class="TableCell">Tuesday, 22 August 2006 06:30:07 </td>
</tr>
</tbody></table>
<h2>
The patterns for DateTime.ToString ( 'y' ) :
</h2>
<table cellpadding="2" cellspacing="1" class="TableClass">
<tbody>
<tr>
<td class="TableCell">0</td>
<td class="TableCell">yyyy MMMM 2006 August </td>
</tr>
</tbody></table>
<h2>
Building a custom DateTime.ToString Patterns
</h2>
The following details the meaning of each pattern character. Note the <strong>K</strong> and <strong>z</strong> character.
<br />
<table cellpadding="2" cellspacing="1" class="TableClass">
<tbody>
<tr>
<td class="TableCell"><strong>d</strong></td>
<td class="TableCell">Represents the day of the month as a number from 1 through 31. A single-digit day is formatted without a leading zero</td>
</tr>
<tr>
<td class="TableCell"><strong>dd</strong></td>
<td class="TableCell">Represents the day of the month as a number from 01 through 31. A single-digit day is formatted with a leading zero</td>
</tr>
<tr>
<td class="TableCell"><strong>ddd</strong></td>
<td class="TableCell">Represents the abbreviated name of the day of the week (Mon, Tues, Wed etc)</td>
</tr>
<tr>
<td class="TableCell"><strong>dddd</strong></td>
<td class="TableCell">Represents the full name of the day of the week (Monday, Tuesday etc)</td>
</tr>
<tr>
<td class="TableCell"><strong>h</strong></td>
<td class="TableCell">12-hour clock hour (e.g. 7)</td>
</tr>
<tr>
<td class="TableCell"><strong>hh</strong></td>
<td class="TableCell">12-hour clock, with a leading 0 (e.g. 07)</td>
</tr>
<tr>
<td class="TableCell"><strong>H</strong></td>
<td class="TableCell">24-hour clock hour (e.g. 19)</td>
</tr>
<tr>
<td class="TableCell"><strong>HH</strong></td>
<td class="TableCell">24-hour clock hour, with a leading 0 (e.g. 19)</td>
</tr>
<tr>
<td class="TableCell"><strong>m</strong></td>
<td class="TableCell">Minutes</td>
</tr>
<tr>
<td class="TableCell"><strong>mm</strong></td>
<td class="TableCell">Minutes with a leading zero</td>
</tr>
<tr>
<td class="TableCell"><strong>M</strong></td>
<td class="TableCell">Month number</td>
</tr>
<tr>
<td class="TableCell"><strong>MM</strong></td>
<td class="TableCell">Month number with leading zero</td>
</tr>
<tr>
<td class="TableCell"><strong>MMM</strong></td>
<td class="TableCell">Abbreviated Month Name (e.g. Dec)</td>
</tr>
<tr>
<td class="TableCell"><strong>MMMM</strong></td>
<td class="TableCell">Full month name (e.g. December)</td>
</tr>
<tr>
<td class="TableCell"><strong>s</strong></td>
<td class="TableCell">Seconds</td>
</tr>
<tr>
<td class="TableCell"><strong>ss</strong></td>
<td class="TableCell">Seconds with leading zero</td>
</tr>
<tr>
<td class="TableCell"><strong>t</strong></td>
<td class="TableCell">Abbreviated AM / PM (e.g. A or P)</td>
</tr>
<tr>
<td class="TableCell"><strong>tt</strong></td>
<td class="TableCell">AM / PM (e.g. AM or PM</td>
</tr>
<tr>
<td class="TableCell"><strong>y</strong></td>
<td class="TableCell">Year, no leading zero (e.g. 2001 would be 1)</td>
</tr>
<tr>
<td class="TableCell"><strong>yy</strong></td>
<td class="TableCell">Year, leadin zero (e.g. 2001 would be 01)</td>
</tr>
<tr>
<td class="TableCell"><strong>yyy</strong></td>
<td class="TableCell">Year, (e.g. 2001 would be 2001)</td>
</tr>
<tr>
<td class="TableCell"><strong>yyyy</strong></td>
<td class="TableCell">Year, (e.g. 2001 would be 2001)</td>
</tr>
<tr>
<td class="TableCell"><strong>K</strong></td>
<td class="TableCell">Represents the time zone information of a date and time value (e.g. +05:00)</td>
</tr>
<tr>
<td class="TableCell"><strong>z</strong></td>
<td class="TableCell">With <a href="http://www.geekzilla.co.uk/View00FF7904-B510-468C-A2C8-F859AA20581F.htm">DateTime</a>
values, represents the signed offset of the local operating system's
time zone from Coordinated Universal Time (UTC), measured in hours.
(e.g. +6)</td>
</tr>
<tr>
<td class="TableCell"><strong>zz</strong></td>
<td class="TableCell">As z but with leadin zero (e.g. +06)</td>
</tr>
<tr>
<td class="TableCell"><strong>zzz</strong></td>
<td class="TableCell">With <a href="http://www.geekzilla.co.uk/View00FF7904-B510-468C-A2C8-F859AA20581F.htm">DateTime</a>
values, represents the signed offset of the local operating system's
time zone from UTC, measured in hours and minutes. (e.g. +06:00)</td>
</tr>
<tr>
<td class="TableCell"><strong>f</strong></td>
<td class="TableCell">Represents the most significant digit of the
seconds fraction; that is, it represents the tenths of a second in a
date and time value. </td>
</tr>
<tr>
<td class="TableCell"><strong>ff</strong></td>
<td class="TableCell">Represents the two most significant digits of the
seconds fraction; that is, it represents the hundredths of a second in a
date and time value.</td>
</tr>
<tr>
<td class="TableCell"><strong>fff</strong></td>
<td class="TableCell">Represents the three most significant digits of
the seconds fraction; that is, it represents the milliseconds in a date
and time value.</td>
</tr>
<tr>
<td class="TableCell"><strong>ffff</strong></td>
<td class="TableCell">Represents the four most significant digits of the
seconds fraction; that is, it represents the ten thousandths of a
second in a date and time value. While it is possible to display the ten
thousandths of a second component of a time value, that value may not
be meaningful. The precision of date and time values depends on the
resolution of the system clock. On Windows NT 3.5 and later, and Windows
Vista operating systems, the clock's resolution is approximately 10-15
milliseconds. </td>
</tr>
<tr>
<td class="TableCell"><strong>fffff</strong></td>
<td class="TableCell">Represents the five most significant digits of the
seconds fraction; that is, it represents the hundred thousandths of a
second in a date and time value. While it is possible to display the
hundred thousandths of a second component of a time value, that value
may not be meaningful. The precision of date and time values depends on
the resolution of the system clock. On Windows NT 3.5 and later, and
Windows Vista operating systems, the clock's resolution is approximately
10-15 milliseconds. </td>
</tr>
<tr>
<td class="TableCell"><strong>ffffff</strong></td>
<td class="TableCell">Represents the six most significant digits of the
seconds fraction; that is, it represents the millionths of a second in a
date and time value. While it is possible to display the millionths of a
second component of a time value, that value may not be meaningful. The
precision of date and time values depends on the resolution of the
system clock. On Windows NT 3.5 and later, and Windows Vista operating
systems, the clock's resolution is approximately 10-15 milliseconds. </td>
</tr>
<tr>
<td class="TableCell"><strong>fffffff</strong></td>
<td class="TableCell">Represents the seven most significant digits of
the seconds fraction; that is, it represents the ten millionths of a
second in a date and time value. While it is possible to display the ten
millionths of a second component of a time value, that value may not be
meaningful. The precision of date and time values depends on the
resolution of the system clock. On Windows NT 3.5 and later, and Windows
Vista operating systems, the clock's resolution is approximately 10-15
milliseconds. </td>
</tr>
<tr>
<td class="TableCell"><strong>F</strong></td>
<td class="TableCell">Represents the most significant digit of the
seconds fraction; that is, it represents the tenths of a second in a
date and time value. Nothing is displayed if the digit is zero. </td>
</tr>
<tr>
<td class="TableCell"><strong>:</strong></td>
<td class="TableCell">Represents the time separator defined in the
current DateTimeFormatInfo..::.TimeSeparator property. This separator is
used to differentiate hours, minutes, and seconds. </td>
</tr>
<tr>
<td class="TableCell"><strong>/</strong> </td>
<td class="TableCell">Represents the date separator defined in the
current DateTimeFormatInfo..::.DateSeparator property. This separator is
used to differentiate years, months, and days. </td>
</tr>
<tr>
<td class="TableCell"><strong>"</strong> </td>
<td class="TableCell">Represents a quoted string (quotation mark).
Displays the literal value of any string between two quotation marks
("). Your application should precede each quotation mark with an escape
character (\). </td>
</tr>
<tr>
<td class="TableCell"><strong></strong>'</td>
<td class="TableCell">Represents a quoted string (apostrophe). Displays the literal value of any string between two apostrophe (') characters. </td>
</tr>
<tr>
<td class="TableCell"><strong>%c</strong> </td>
<td class="TableCell">Represents the result associated with a c custom
format specifier, when the custom date and time format string consists
solely of that custom format specifier. That is, to use the d, f, F, h,
m, s, t, y, z, H, or M custom format specifier by itself, the
application should specify %d, %f, %F, %h, %m, %s, %t, %y, %z, %H, or
%M. For more information about using a single format specifier, see
Using Single Custom Format Specifiers. </td>
</tr>
</tbody></table>
||<strong>\c</strong> || Represents the escape character, and
displays the character "c" as a literal when that character is preceded
by the escape character (\). To insert the backslash character itself in
the result string, the application should use two escape characters
("\\").
<br />
Any other character copies any other character to the result string, without affecting formatting. || </div>
</div>
</div>Anonymoushttp://www.blogger.com/profile/04793789893946649568noreply@blogger.com0tag:blogger.com,1999:blog-6823701262697705013.post-86426101581343596062011-10-03T22:45:00.000-07:002012-07-02T22:40:54.671-07:00How To Find Dependent Tables In SQL ServerHere's a query that will list all dependent tables and fields of a table you specify. That is, foreign keys and column names. This might be useful if you need to delete a record from the master table and have to delete records from its dependent tables first.<br />
<div>
<br />
Just replace <span style="color: blue;">myTableName</span> in the <span style="color: blue;">WHERE</span> clause accordingly.<br />
<pre class="brush:sql">SELECT
pt.COLUMN_NAME AS primaryField,
c.CONSTRAINT_NAME AS keyName,
fk.TABLE_NAME AS foreignTable,
cu.COLUMN_NAME AS foreignField
FROM
INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS c
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS fk ON
c.CONSTRAINT_NAME = fk.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk ON
c.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE cu ON
c.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
INNER JOIN (
SELECT tc.TABLE_NAME, kcu.COLUMN_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu
ON tc.CONSTRAINT_NAME = kcu.CONSTRAINT_NAME
WHERE tc.CONSTRAINT_TYPE = 'PRIMARY KEY'
) pt ON pt.TABLE_NAME = pk.TABLE_NAME
WHERE pk.TABLE_NAME = 'myTableName'
ORDER BY foreignTable ASC;</pre>
<br />
<br />
<span class="Apple-style-span" style="font-family: Georgia, serif; font-size: 16px; font-weight: bold; white-space: normal;"><br /></span><span class="Apple-style-span"><b>Output</b></span><span class="Apple-style-span" style="font-family: Georgia, serif; font-size: 16px; white-space: normal;">Here's a sample of the output you'll get:</span><br />
<div>
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiTz05rNOISGsgVu8VHxEAu6FBBWjZiHUaXyN_xVhbFj8OsE2atj6TM2y5poEkD4meVV3-gBT2CFjzYKX_L2wDN8M6YdWIp-H8RtlI6YVIkcq757TM7hiFv-5iJBwDVP7-fvB1O7Ig83Fmy/s1600/sql_query_output.png" onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}"><img alt="" border="0" id="BLOGGER_PHOTO_ID_5659509868315247138" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiTz05rNOISGsgVu8VHxEAu6FBBWjZiHUaXyN_xVhbFj8OsE2atj6TM2y5poEkD4meVV3-gBT2CFjzYKX_L2wDN8M6YdWIp-H8RtlI6YVIkcq757TM7hiFv-5iJBwDVP7-fvB1O7Ig83Fmy/s320/sql_query_output.png" style="cursor: hand; cursor: pointer; height: 172px; width: 320px;" /></a></div>
</div>
<br />
<br />
<h3>
Problem</h3>
<div>
ref: <a href="http://www.mssqltips.com/sqlservertip/1294/listing-sql-server-object-dependencies/">http://www.mssqltips.com/sqlservertip/1294/listing-sql-server-object-dependencies/</a>
</div>
<div>
<br /></div>
When developing components for SQL Server one change may affect another database object. Finding these dependent objects should be straightforward, but in most cases it is not as easy as you would think. So what is the best way to find dependency information in SQL Server?
<br />
<h3>
Solution</h3>
There are several methods of getting this information. The first approach would be to use the SQL Server Management tools.
<br />
For SQL Server 2005, right click on the table name and select "View Dependencies" as shown below we are looking at dependencies for a table.
<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<table cellpadding="0" cellspacing="0" class="tr-caption-container" style="float: left; margin-right: 1em; text-align: left;"><tbody>
<tr><td style="text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEipYwf0ybEaKhScC2udVsUhJerEIqtBxHi5azr63UTB5hgIRMt0dur1zuJVD_oo4lklFOnUjgnxPByHoGtwNSBUahWTT7_xAdyPWLqZil7YlS1KRzpIbGe1niA9NK-L_0R8Sm3LmN29uJeU/s1600/1294_sp_dep18.gif" imageanchor="1" style="clear: left; margin-bottom: 1em; margin-left: auto; margin-right: auto;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEipYwf0ybEaKhScC2udVsUhJerEIqtBxHi5azr63UTB5hgIRMt0dur1zuJVD_oo4lklFOnUjgnxPByHoGtwNSBUahWTT7_xAdyPWLqZil7YlS1KRzpIbGe1niA9NK-L_0R8Sm3LmN29uJeU/s1600/1294_sp_dep18.gif" /></a></td></tr>
<tr><td class="tr-caption" style="text-align: center;"><span style="font-size: small; text-align: -webkit-auto;">This will give you the following view so you can see objects that are dependent on the Employee table.</span> </td></tr>
</tbody></table>
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"><tbody>
<tr><td style="text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjSVTp_6z8378YM-PwZqkAVR5KwLt2uC65BjQ0dFTuFvA3RXlM9Ge-9j0tC_dXIMYoz8mp-vfrsJ_j_S5E5q-zw4sTyuzBT5_NEV1zb0Fbpo-SYNlj52WeKm3NIGVC2YpA9XkTyWz8aP2PT/s1600/1294_sp_dep1.gif" imageanchor="1" style="margin-left: auto; margin-right: auto;"><img border="0" height="156" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjSVTp_6z8378YM-PwZqkAVR5KwLt2uC65BjQ0dFTuFvA3RXlM9Ge-9j0tC_dXIMYoz8mp-vfrsJ_j_S5E5q-zw4sTyuzBT5_NEV1zb0Fbpo-SYNlj52WeKm3NIGVC2YpA9XkTyWz8aP2PT/s320/1294_sp_dep1.gif" width="320" /></a></td></tr>
<tr><td class="tr-caption" style="text-align: center;"><span style="font-size: small; text-align: -webkit-auto;">And this next screen shot shows you objects that table Employee depends upon.</span> </td></tr>
</tbody></table>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEijx9friWM-PiTHbJ97qFyu9nhFpE__Jn6Z88D3-sF4odYj7iGkO1VfOL9Na7p1FVnnhDsdSS3hbYIcMM-TcYdAY93ERiBPdLEByR69NzaQTMiVMAswPlMt6wuOWxdcgfsyF68J4gcuUrIn/s1600/1294_sp_dep2.gif" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="83" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEijx9friWM-PiTHbJ97qFyu9nhFpE__Jn6Z88D3-sF4odYj7iGkO1VfOL9Na7p1FVnnhDsdSS3hbYIcMM-TcYdAY93ERiBPdLEByR69NzaQTMiVMAswPlMt6wuOWxdcgfsyF68J4gcuUrIn/s320/1294_sp_dep2.gif" width="320" /></a></div>
<br />
<br />
<div>
To get this information, SQL Server does a lot of work to get. To see the process that SQL Server uses to generate this data for this screen <a href="http://www.mssqltips.com/tipimages/1294_sqlcode.txt">click here</a>.</div>
<div style="font-size: 13px; text-align: left;">
<br /></div>
<div>
<span style="font-family: Arial, Helvetica, sans-serif;">Although this is helpful to get the data via the GUI, what other approaches are there to get this data?</span></div>
<br />
<h4>
</h4>
<h4>
</h4>
<h4>
Method 1 - INFORMATION_SCHEMA.ROUTINES</h4>
This approach uses INFORMATION_SCHEMA.ROUTINES to search through the definition of the routine such as the stored procedure, trigger, etc...
<br />
<pre class="brush:sql">SELECT DISTINCT routine_name, routine_type FROM INFORMATION_SCHEMA.ROUTINES WHERE ROUTINE_DEFINITION LIKE '%UserPartnerPreference%'
</pre>
<h4>
Method 2 - sp_depends</h4>
This approach uses the system stored procedure sp_depends.
<br />
<pre class="brush:sql">
EXEC sp_depends @objname = N'yourTableName' ;
</pre>
<h4>
Method 3 - Using syscomments</h4>
This approach reads data from the syscomments table. This is similar to method 1.
<br />
<pre class="brush:sql">SELECT distinct so.name
FROM syscomments sc
INNER JOIN sysobjects so ON sc.id = so.id
WHERE charindex('yourTableName', text) > 0
</pre>
<h4>
Method 4 - sp_MSdependencies</h4>
This approach uses the system stored procedure sp_MSdependencies.
<br />
<pre class="brush:sql">-- Value 131527 shows objects that are dependent on the specified object
EXEC sp_MSdependencies N'yourTableName', null, 1315327
</pre>
<br />
<br />
<pre class="brush:sql">-- Value 1053183 shows objects that the specified object is dependent on
EXEC sp_MSdependencies N'yourTableName', null, 1053183
</pre>
<br />
<br />Anonymoushttp://www.blogger.com/profile/04793789893946649568noreply@blogger.com0tag:blogger.com,1999:blog-6823701262697705013.post-52513384172392278172011-08-10T00:17:00.000-07:002012-06-22T06:19:33.555-07:00C# Get ALL Image File In a Folder<pre class="brush:csharp">
<br />
<br />protected List<string> GetFilesInFolder(string folderVirtualPath)
<br />{
<br />string physicalPathToFolder = Server.MapPath(folderVirtualPath);// Get the physical path
<br />string filterExpression = "*.gif";
<br />string[] physicalPathsCollection = System.IO.Directory.GetFiles(physicalPathToFolder,
<br />filterExpression);// Get all child files of the given folder
<br />List<string> virtualPathsCollection = new List<string>();// Contains the result
<br />foreach (String path in physicalPathsCollection)
<br />{
<br />// The value of virtualPath will be similar to '~/PathToFolder/Image1.jpg
<br />string virtualPath = VirtualPathUtility.AppendTrailingSlash(folderVirtualPath) +
<br />System.IO.Path.GetFileName(path);
<br />virtualPathsCollection.Add(virtualPath);
<br />}
<br />return virtualPathsCollection;
<br />}
<br /></pre>Anonymoushttp://www.blogger.com/profile/04793789893946649568noreply@blogger.com0tag:blogger.com,1999:blog-6823701262697705013.post-87589730126331536462011-08-09T21:21:00.000-07:002012-06-22T06:20:04.029-07:00JSON:Fat-Free Data Interchange<br />
JSON stands for "JavaScript Object Notation" and is a lightweight data-interchange
format. JSON is easy to generate and parse but also easily human-readable. JSON
has a number of advantages in the JavaScript/client environment:<br />
<ul>
<li>JSON can be used as an easy-to-work-with alternative to XML.</li>
<li>JSON can be de-serialized into objects and the objects serialized back into strings.
There are API's that can do these transformations on both the client and server.</li>
<li>Webservices can return JSON automatically for immediate use within JavaScript</li>
</ul>
<br />
<div>
<br />
JSON supports the usual basic type flavors: numbers, strings, booleans, arrays,
objects and null.</div>
<br />
<div>
<br />
<span class="Apple-tab-span" style="white-space: pre;"></span>The quickest way to
understand how the JSON syntax works is to look at an example. Below is a sample
JSON object definition called "contact". It has string properties for "firstName"
and "lastName". Another property, "address" is an object that has its own properties
for "streetAddress", "city", "state" and "postalCode". These address properties
are all string except "postalCode" that contains a numeric value. The last property
"phoneNumbers" is actually an array of strings.
</div>
<br />
<h5>
[JavaScript] JSON Sample</h5>
<h5>
<br />
<pre class="brush:js">var contact = {
// string property
"firstName": "John",
"lastName": "Smith",
// address property with sub-properties
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
// numeric property
"postalCode": 10021
},
// array
"phoneNumbers": [
"212 555-1234",
"646 555-4567"
]}
;
</pre>
As you can see in the sample above, the JSON object definition appears between curly
braces. Each property and value pair are separated by a colon. Arrays are contained
within square brackets.</h5>
<h5>
<span class="Apple-style-span" style="font-size: 16px;">Using JSON Objects</span></h5>
<h5>
<span class="Apple-style-span" style="font-size: 16px; font-weight: normal;">Once the
JSON object is defined you can assign and retrieve values using the properties of
the object. In this next sample the "contact" object is assigned a new first and
last name and the second element of the phoneNumbers array is also replaced with
a new value.</span></h5>
<h5>
[JavaScript] Assigning and Retrieving JSON Properties</h5>
<pre class="brush:js">// change the name and phoneNumbers properties
contact.firstName = "Bob";
contact.lastName = "Jones";
contact.phoneNumbers[1] = "123 555-9999";
alert(contact.firstName + ' ' +
contact.lastName + ' phone: ' + contact.phoneNumbers[1]);
</pre>
<br />
<span class="Apple-style-span" style="font-family: Georgia, serif; font-size: 16px;
white-space: normal;">Running this bit of JavaScript fires the alert shown below:</span>
<br />
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhXJt9Xm5Pic5azuzpW9grr7uUC012rnwtqmeku-scWRqrNjarYeReIuq8Ln0FZE1YTCjMP0ZYrvtClENIJSVoWRx2Ou7AIuGENRbaVnFrneYjBVoNH556xsd_0jaVq9MtjHdRj17luqB6i/s1600/alertbox.png">
<img alt="" border="0" id="BLOGGER_PHOTO_ID_5639115113397290594" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhXJt9Xm5Pic5azuzpW9grr7uUC012rnwtqmeku-scWRqrNjarYeReIuq8Ln0FZE1YTCjMP0ZYrvtClENIJSVoWRx2Ou7AIuGENRbaVnFrneYjBVoNH556xsd_0jaVq9MtjHdRj17luqB6i/s320/alertbox.png"
style="cursor: hand; cursor: pointer; display: block; height: 175px; margin: 0px auto 10px;
text-align: center; width: 292px;" /></a>
<br />
<b>Serializing JSON</b>
<br />
<div>
<br />
</div>
<div>
You can also take a JSON string and transform it into an object. The ASP.NET AJAX
Library includes a JavaScriptSerializer object within the Sys.Serialization namespace
that you get for free when you include a ScriptManager on the page. If you call
the JavaScriptSerializer deserialize() method and pass a JSON string, the method
will deserialize the string into a JSON object. Call the serialize() method to transform
the a JSON object back to a string.
<br />
<br />
The sample below shows a JSON string defined for "contact". This is exactly the
same as the "contact" object defined in the last example, but surrounded with quotes.
A call to deserialize() takes the contact JSON string and transforms it into an
object representation. Following that, the contact object is converted back using
the serialize() method into its string representation.
<br />
<br />
<h5>
[JavaScript] Serialize and Deserialize</h5>
<br />
<br />
<pre class="brush:js">var contactString = '{"firstName": "John", "lastName": "Smith", ' +
'"address": {"streetAddress": "21 2nd Street",' +
'"city": "New York","state": "NY", "postalCode": 10021},' +
'"phoneNumbers": ["212 555-1234","646 555-4567"]}';
// deserialize JSON string to an object
contact =
Sys.Serialization.JavaScriptSerializer.deserialize(contactString);
// serialize the contact JSON into a string
var contactStrings =
Sys.Serialization.JavaScriptSerializer.serialize(contact);
</pre>
<br />
<h5>
[C#] Serializing and Deserializing in Code-Behind</h5>
<br />
<div>
<pre class="brush:csharp">protected void Page_Load(object sender, EventArgs e)
{
Contact contact = new Contact();
contact.FirstName = "Bob";
contact.LastName = "Smith";
contact.Address.City = "San Francisco";
contact.Address.State = "California";
contact.Address.StreetAddress = "123 Telerik Ave";
contact.Address.PostalCode = 91234;
contact.PhoneNumbers.Add("123 555-1234");
contact.PhoneNumbers.Add("444 555-9876");
JavaScriptSerializer jss = new JavaScriptSerializer();
string contactString = jss.Serialize(contact);
tbServerStatus.Text = contactString;
Contact contact2 = jss.Deserialize
<contact>(contactString);
tbServerStatus.Text += System.Environment.NewLine + System.Environment.NewLine +
contact2.FirstName + " " + contact2.LastName;
}
</pre>
<br />
</div>
<br />
<br />
</div>Anonymoushttp://www.blogger.com/profile/04793789893946649568noreply@blogger.com0tag:blogger.com,1999:blog-6823701262697705013.post-60968595910648042912011-01-13T06:06:00.000-08:002013-05-09T06:07:43.005-07:00Session Timeout with Warning and jQuery Session Refresh in ASP.NetASP.Net applications are written in such a way that after the session times out, the user is also logged out. This is sometimes to secure the application from others accessing the computer, while the real user is away from their desk. If this is the case, it’s nice to let the user know how long they’ve got left before they’re logged out due to inactivity. I got this from <a href="http://misterdai.wordpress.com/2010/06/07/cf-jquery-session-timeout-countdown/">This Site Written in Cold Fusion</a>.<br />
I Converted To work in C# and Added Progress Bar With in Message Box.<br />
<br />
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiunw0iIivfOfZSHGC7rEcs93eKWn46LaVmLZvGIUL-thgGZWTKnBXNjZ-8F0L-VgIfuS-gwjWW7l53qv3dxFMdYY5r8hRAJZO5rUFqHNDb_-b644Eau0D5nVErBEnEY2YWciHpUuuNe3f-/s1600/localhost+-+2010-11-12+-+17-27-19.png" onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}"><img alt="" border="0" id="BLOGGER_PHOTO_ID_5538631310454364770" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiunw0iIivfOfZSHGC7rEcs93eKWn46LaVmLZvGIUL-thgGZWTKnBXNjZ-8F0L-VgIfuS-gwjWW7l53qv3dxFMdYY5r8hRAJZO5rUFqHNDb_-b644Eau0D5nVErBEnEY2YWciHpUuuNe3f-/s320/localhost+-+2010-11-12+-+17-27-19.png" style="cursor: hand; cursor: pointer; display: block; height: 206px; margin: 0px auto 10px; text-align: center; width: 320px;" /></a><br />
<br />
<div style="border-bottom: 1px dotted #000000; font-weight: bold; margin-bottom: 2px;">
<h2>
<a href="https://www.box.com/s/cyrxoqu2mtxkvima0796"> Download</a></h2>
Summary</div>
<br />
- User logs in, session created.<br />
- Session set to time out (e.g. 30 minutes).<br />
- When session times out, the user is logged out.<br />
- Display a countdown so the user knows how long is left.<br />
- Inform the user when they are approaching the limit (e.g. 5 minutes left).<br />
- Let the user know that they’ve been automatically timed out due to inactivity.<br />
<br />
<div style="border-bottom: 1px dotted #000000; font-weight: bold; margin-bottom: 2px;">
Approach taken</div>
<br />
Every request to the application will set two cookies:<br />
Date / time the session will expire.<br />
Current server date / time.<br />
Our bit of JavaScript watches these cookies.<br />
Any application activity will update these cookies so we know if a second window has done something and the session timeout refreshed.<br />
<br />
<div style="border-bottom: 1px dotted #000000; font-weight: bold; margin-bottom: 2px;">
sessionTimeout()</div>
<br />
<br />
This is my first real effort at creating a jQuery plugin. It took a bit more effort wrapping everything up nicely and providing options but I think it was worth it and should make the code easier to include.<br />
<br />
<pre class="brush:js"> (function($) {
$.fn.sessionTimeout = function(options) {
var opts = $.extend({}, $.fn.sessionTimeout.defaults, options);
var inter = this.data('timer');
if (inter) {
clearInterval(inter);
}
var info = {
warned: false,
expired: false
};
processCookie(info, opts);
this.data('timer', setInterval(cookieCheck, opts.interval, this, info, opts));
cookieCheck(this, info, opts);
};
function processCookie(info, opts) {
info.serverTime = Date.parse($.fn.sessionTimeout.readCookie(opts.timeCookie));
info.sessionTime = Date.parse($.fn.sessionTimeout.readCookie(opts.sessCookie));
info.offset = new Date().getTime() - info.serverTime;
info.expires = info.sessionTime + info.offset;
info.duration = Math.floor((info.sessionTime - info.serverTime) / 1000);
};
// private
function cookieCheck(els, info, opts) {
var sessionTime = Date.parse($.fn.sessionTimeout.readCookie(opts.sessCookie));
if (sessionTime != info.sessionTime) {
processCookie(info, opts);
}
info.timeLeft = {};
var ms = info.expires - (new Date().getTime());
info.timeLeft.minutes = Math.floor(ms / 60000);
info.timeLeft.seconds = Math.floor(ms % 60000 / 1000);
info.timeLeft.onlySeconds = info.timeLeft.minutes * 60 + info.timeLeft.seconds;
info.timeLeft.minutes = info.timeLeft.minutes.toString().replace(/^([0-9])$/, '0$1');
info.timeLeft.seconds = info.timeLeft.seconds.toString().replace(/^([0-9])$/, '0$1');
if (!info.warned && info.timeLeft.onlySeconds <= opts.warningTime) {
info.warned = true;
opts.onWarning(els, info, opts);
} else if (!info.expired && info.timeLeft.onlySeconds < 0) {
info.expired = true;
opts.onExpire(els, info, opts);
}
if (!info.expired) {
opts.onTick(els, info, opts);
}
};
function onTick(els, info, opts) {
els.each(function() {
opts.onTickEach(this, info, opts);
});
};
function onTickEach(el, info, opts) {
var pval = ((info.timeLeft.minutes * 60) + parseInt(info.timeLeft.seconds)) * 100 / opts.warningTime;
$(el).html(info.timeLeft.minutes + ':' + info.timeLeft.seconds); //+ ' ' + opts.warningTime + ' ' + pval + ' ' + info.duration);
if (pval < 100) {
if (!$("#Session-TimeOut").dialog('isOpen'))
$("#Session-TimeOut").dialog('open');
$(".bar").progressbar({
value: pval
});
}
else {
if ($("#Session-TimeOut").dialog('isOpen'))
$("#Session-TimeOut").dialog('close');
}
};
function onWarning(el, info, opts) {
//alert('Warning');
$("#Session-TimeOut").dialog('open');
};
function onExpire(el, info, opts) {
window.location('Login.aspx');
//alert('Expired');
};
// public
$.fn.sessionTimeout.readCookie = function(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0)
return unescape(c.substring(nameEQ.length, c.length));
}
return null;
}
$.fn.sessionTimeout.defaults = {
timeCookie: 'SERVERTIME',//cookie
sessCookie: 'SESSIONTIMEOUT', //cookie
interval: 1000,
onTick: onTick,
onTickEach: onTickEach,
warningTime: 340, // seconds
onWarning: onWarning,
onExpire: onExpire
};
})(jQuery);</pre>
<br />
<br />
The plugin provides .sessionTimeout(options) which is used on your selected elements to display the amount of time left until session expiration. The options allow you to use different cookie names, change the execution interval and override several events.<br />
It works by setting up a periodic function to watch the cookies. Whenever the cookies are updated, we recalculate the time out and continue displaying the information. If the warning time or expiration is reached, it fires off over-ridable events that by default use “alert” to display simple messages, but could easily use something like the jQuery UI dialog plugin.<br />
If you’re wondering about the reasoning behind the server time cookie. This was to workaround the differences between the client and server clocks.<br />
<br />
<div style="border-bottom: 1px dotted #000000; font-weight: bold; margin-bottom: 2px;">
Example</div>
<br />
<br />
In the following code I’ll set the two cookies required for the plugin and use it against two different elements. One for displaying the time, another to show a progress bar (using jQuery UI, not required for the plugin). I also override the onWarning & onExpire events for the progress bar since the user wouldn’t like to be double prompted <br />
<br />
Add Jquery And Jquery UI <br />
<br />
<pre class="brush :js"> <link href="../App_Themes/TestTheme/jquery-ui-1.8.2.custom.css" rel="stylesheet"
type="text/css" />
<link href="../App_Themes/TestTheme/stylemain.css" rel="stylesheet" type="text/css" />
<script src="../JS/jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="../JS/jquery-ui-1.8.2.custom.min.js" type="text/javascript"></script>
<script src="../JS/Timeout.js" type="text/javascript"></script> </pre>
<br />
<br />
Init Session Timeout And a Dialog Box To Dispaly Alert<br />
<pre class="brush :js"> $(document).ready(function() {
$(".sessions").sessionTimeout();
$("#Session-TimeOut").dialog({
resizable: true,
height: 200,
autoOpen: false,
modal: true,
buttons: {
Ok: function() {
$(this).dialog('close');
__doPostBack('<%= Button1.UniqueID %>', '');
}
}
});
}); </pre>
<br />
<br />
<span style="font-weight: bold;"> default.aspx</span><br />
<pre class="brush: html"> <div class="content">
<div id="Session-TimeOut" title="Session Timeout?">
<span class="ui-icon ui-icon-alert" style="float: left; margin: 0 7px 20px 0;"></span>
Your session is about to Expire.<br />
<div style="width: 100%;">
<span class="sessions" style="float: left; padding: 3px;"></span> <br />
<div class="bar" style="float: left; height: 20px; width: 70%;">
</div>
</div>
</div>
<asp:scriptmanager id="ScriptManager1" runat="server">
</asp:scriptmanager><br />
<asp:updatepanel id="UpdatePanel2" runat="server">
<contenttemplate>
<asp:button id="Button1" onclick="Button1_Click" runat="server" text="Button">
</asp:button></contenttemplate>
</asp:updatepanel></div>
</pre>
<br />
<br />
add cookie on PageLoad<br />
<br />
<pre class="brush :csharp"> HttpCookie appCookie = new HttpCookie("SERVERTIME");
appCookie.Value = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
appCookie.Expires = DateTime.Now.AddDays(1);
appCookie.Path = "/";
Response.Cookies.Add(appCookie);
HttpCookie appCookie2 = new HttpCookie("SESSIONTIMEOUT");
appCookie2.Value = DateTime.Now.AddMinutes(HttpContext.Current.Session.Timeout).ToString("yyyy/MM/dd HH:mm:ss");
appCookie2.Expires = DateTime.Now.AddDays(1);
appCookie2.Path = "/";
Response.Cookies.Add(appCookie2);</pre>
<br />
<div>
Running this bit of JavaScript fires the alert shown below:</div>
<h2>
<a href="https://www.box.com/s/cyrxoqu2mtxkvima0796"> Download</a></h2>
Anonymoushttp://www.blogger.com/profile/04793789893946649568noreply@blogger.com22tag:blogger.com,1999:blog-6823701262697705013.post-18502543006499120892010-06-02T06:09:00.000-07:002012-06-22T06:20:37.074-07:00ASP.Net menu Hack for Google Chrome<p>ASP.Net menu controls breaks in Google Chrome and works fine in other browsers. Here is the hack to make it work in Google Chrome as well,</p><br /><pre class="brush: javascript; ruler: true;"><br />if (Request.UserAgent.IndexOf("AppleWebKit") > 0)<br /> Request.Browser.Adapters.Clear();<br /></pre><br /><p><br />Just add this code on your page load and the menu control will start working fine in Google Chrome as well.<br />Also some times the hover menus don’t work on IE8 to make it work on IE8 you need to set<br />“z-index”<br /></p>Anonymoushttp://www.blogger.com/profile/04793789893946649568noreply@blogger.com1tag:blogger.com,1999:blog-6823701262697705013.post-70208914418599973052009-11-13T00:57:00.000-08:002012-06-22T06:21:38.371-07:00Writing CLR Stored Procedures in C#This is the first article in a series on writing stored procedures using the Common Language Runtime (CLR). This article focuses on basic C# syntax and using Visual Studio to build a stored procedure. It's targeted at DBA's and anyone else who primarily writes in Transact-SQL and hasn't had much exposure to .NET yet. (Update: Fixed the title.)<br /><br />As SQL Server 2005 rolls out DBA's are going to be forced to learn either C# or Visual Basic or both. Until now these were client side languages and not knowing them had little impact on your job. And if you write code in these languages your going to have to learn to use Visual Studio. This article covers the basics of C# and Visual Studio using a basic stored procedure as an example.<br /><br /><br /><a href="http://www.sqlteam.com/article/writing-clr-stored-procedures-in-charp-introduction-to-charp-part-1">http://www.sqlteam.com/article/writing-clr-stored-procedures-in-charp-introduction-to-charp-part-1</a><br /><a href="http://msdn.microsoft.com/en-us/library/ms345136%28SQL.90%29.aspx">http://msdn.microsoft.com/en-us/library/ms345136%28SQL.90%29.aspx</a><br /><a href="http://www.sql-server-performance.com/articles/dev/clr_2005_p1.aspx">http://www.sql-server-performance.com/articles/dev/clr_2005_p1.aspx</a>Anonymoushttp://www.blogger.com/profile/04793789893946649568noreply@blogger.com0