tag:blogger.com,1999:blog-52534958506244112262024-03-18T21:01:46.840-07:00C# Adjustment - ASP.NETUseful C# Classes and methods to IMPROVE your knowledge easily.Amir Akhoundpourhttp://www.blogger.com/profile/09321829496260407874noreply@blogger.comBlogger12125tag:blogger.com,1999:blog-5253495850624411226.post-71819676915994757482012-06-11T21:42:00.000-07:002012-06-11T22:28:53.657-07:00Display Label for your model in ViewLet's see what was annoying in old fashion aspx pages before and how MVC helps us to overcome it.<br />
Consider you want to show the <span style="color: blue;">"Product Name"</span> as a label in some pages in aspx pages , there was different possibilities to achieve it , best way to create a usercoontrol for the product and add a label <span style="color: blue;">"Product Name" <span style="color: black;">yes it it , but what if you want to show product name in other places as well like another control or another page, yes you need to write it again, this is a simple example but when it comes into a complex project maintaining this simple thing could be a nightmare.</span></span><br />
<br />
<span style="color: blue;"><span style="color: black;">I remember once in our company somebody mistakenly name a label "<span style="color: #990000;">Blah blah</span>" just for testing and that code mistakenly went into the production, but If we defined these labels in our model level, if you name something wrong you can easily change it in one place and there is more possibilities to catch it sooner at least not on production </span></span><br />
<br />
<span style="color: blue;"><span style="color: black;"></span></span><br />
Model----------<br />
<span style="color: blue;">public class</span> <span style="color: #45818e;">MyModel</span><br />
{<br />
[<span style="color: #45818e;">DisplayName</span>("<span style="color: blue;">Product Name</span>")]<br />
<span style="color: blue;"> public string</span> ItemName{ <span style="color: blue;">get</span>; <span style="color: blue;">set</span>; }<br />
}<br />
<br />
View-----------<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg5HSh0ORPcFNHbfwiRStcXicSuggVPuWoW0UC_6dBHBEivvT75rvNpHi3swLvgG-QZ9FHBEdbPPMiZiO7keK-0e7ceBlzkMN5iYz4xZmwa6JdSkbDoZ19nd49ku_33siQpr6EebtBUmsQ/s1600/ItemName.PNG" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" height="28" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg5HSh0ORPcFNHbfwiRStcXicSuggVPuWoW0UC_6dBHBEivvT75rvNpHi3swLvgG-QZ9FHBEdbPPMiZiO7keK-0e7ceBlzkMN5iYz4xZmwa6JdSkbDoZ19nd49ku_33siQpr6EebtBUmsQ/s640/ItemName.PNG" width="640" /></a></div>
This is so basic and interesting of using Model metadata.Amir Akhoundpourhttp://www.blogger.com/profile/09321829496260407874noreply@blogger.com0tag:blogger.com,1999:blog-5253495850624411226.post-14717589569546401962012-06-11T18:35:00.003-07:002012-06-13T16:29:00.600-07:00Using JSON response in JQUERY in MVCI've found that using JSON in MVC is very handy and useful , Consider you have a template of a usercontrol/control and when an event triggers on the page you want to load the new data in your control, there are many ways to do it , one of the good ways is returns the usercontrol/control with new data completely on the page and add it again and also remove the previous one, but a question is when you already have the userontrol/control on the page and only difference is showing new data on it do you think a faster is just to load the new data and bind it into the usercontrol/control? for sure yes it is.<br />
<br />
loading the data and bind it to your control can be handle in different ways as well , but I like JSON format better.<br />
<br />
Let's start calling a controller to return a simple int[] but in JSON format and see how it works.<br />
<br />
Consider we have a method in our any controller such as PersonController to return a list of person and use it in the VIEW.<br />
<br />
model------<br />
<span style="color: blue;">public class</span> <span style="color: #45818e;">Person</span><br />
{<br />
<span style="color: blue;">public string</span> FirstName { <span style="color: blue;">get</span>; <span style="color: blue;">set</span>; }<br />
<span style="color: blue;">public string</span> LastName { <span style="color: blue;">get</span>; <span style="color: blue;">set</span>; }<br />
<span style="color: blue;">public int</span> PersonID { <span style="color: blue;">get</span>; <span style="color: blue;">set</span>; }<br />
}<br />
<br />
controller--------<br />
[<span style="color: #45818e;">HttpPost</span>]<br />
<span style="background-color: white; color: blue;">public </span><span style="color: #45818e;">ActionResult </span>GetPeople(<span style="color: blue;">string </span>CountryCode)<br />
{<br />
<span style="color: #76a5af;">List</span><<span style="color: blue;">Person</span>> people=<span style="color: blue;">new </span><span style="color: #45818e;">List</span><<span style="color: blue;">Person</span>>();<br />
<br />
for (int i = 0; i < 10; i++)<br />
{<br />
people.Add(new Person() { FirstName =
string.Format("Name-{0}",i),LastName =
string.Format("Family-{0}",i),PersonID = i});<br />
}<br />
<br />
//creating a JSON response format , so you can see the "res" object<br />
JsonResult res = Json(people);<br />
<span style="color: blue;">return </span>res;<br />
}<br />
<br />
Now you have an action which returns a list of person in JSON format, the only thing is call this action via JQUERY and read it and bind it to your object, since my focuse on this exercise is just to read JSON format data with JQUERY , I'm not talking about the specific control you may need.<br />
<br />
Consider an event in your page triggers(like clicking on btnRefresh) and you want to call GetPeople action , this Action may need some parameters like CountryCode<br />
NOTE: when you are calling <b> $.post </b>you are able to specify the format of the data you expect after defining the action parameter , here for this example sine I know the action returns JSON data format, so in <b> $.post</b> we should specify the <b>'json' </b>as data format of the response.<br />
<br />
<span style="color: #cc0000;">JQuery in your VIEW</span><br />
<br />
$(btnRefresh).unbind("click").click(function() { <br />
<br />
<b>$.post</b>('Person\GetPeople', { CountryCode: 'en-US'}, function(data) {<br />
//data is people<br />
$(data).each(function(index, <span style="color: blue;">person</span>) {<br />
<br />
//alerting people info or you can repopulate your specific control based on this data<br />
alert('FName:' + person.FirstName+ ', LName:'+person.LastName+', PersonID:'+person.PersonID.toString() );<br />
});<br />
<br />
},<span style="color: blue;"> 'json'</span>);<br />
<br />
});<br />
<br />Amir Akhoundpourhttp://www.blogger.com/profile/09321829496260407874noreply@blogger.com0tag:blogger.com,1999:blog-5253495850624411226.post-20114013123047144812012-06-05T16:58:00.003-07:002012-06-06T03:04:09.828-07:00MVC - UserControl and passing data from a page to itUsing UserControl makes your application pretty powerful, because you can reuse some stuff that you already created easily.<br />
<br />
In MVC , View talks with controller to return Model as data. this is a general concept in MVC and I dont want to discuss about lots of possibilities we may have in .<br />
<br />
<br />
Let's start creating our UserControl on PartialView in MVC , Consider we want to put productDetail information in a usercontrol and then wherever we need productInfo then easily use our existing usercontrol.<br />
<br />
View----------------<br />
1- Add a folder under View and name it Product.<br />
2- Add a PartialView(UserControl) name it ProductDetailInfo.ascx.this is a strongly typedusercontrol means if you see it is inheriting from ProductModels.ProductInfo , if it was not inheriting from anything it was not strongly typed then you can not say Model.ID then you needed to use ViewData["ProductInfo.ID"]<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiQQIrCzibwvUHe3rHEz8LyFmMWig8MZDTU-HJ-UbZEirW43smlpBt5k2XFhM9bRU3ObNrih-g4dHR60qjQ9Ijo6fENw6zVVWsJ52FhoVVTIuRwjafzG4dcJB8GxWIg4ReEKsX2UJKs0PM/s1600/UC.PNG" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" height="91" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiQQIrCzibwvUHe3rHEz8LyFmMWig8MZDTU-HJ-UbZEirW43smlpBt5k2XFhM9bRU3ObNrih-g4dHR60qjQ9Ijo6fENw6zVVWsJ52FhoVVTIuRwjafzG4dcJB8GxWIg4ReEKsX2UJKs0PM/s400/UC.PNG" width="400" /></a></div>
<br />
<br />
<br />
<br />
<br />
<br />
<br />
3- Add a View(Page) name it <span style="font-size: x-small;">Detail</span>.(just need to put ProductDetailInfo.ascx. into the page.) the name if the page is the same as the controller method name in productController or in the productController when it wants to return the data we could specify the view to return as well.<br />
in the page just add the following line to add usercontol into the page<br />
<b>This page is responsible to get the data and pass the required data to the usercontrol.</b> in this example it passes all model to the usercontrol.<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj4VMkzxlJv_YnOGxnb4jBJPlGu_1x_JnYd-73TcCc5w-cjQakPMp7mPIqt1Xpv30Yz2iVmyzK5zWfSP1_8bHPqeMwDu0_35U3QlSzyJgSgMuMjJaG9a9A8RUKjBKkdHYt3o08Ad-WCztg/s1600/page.PNG" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" height="155" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj4VMkzxlJv_YnOGxnb4jBJPlGu_1x_JnYd-73TcCc5w-cjQakPMp7mPIqt1Xpv30Yz2iVmyzK5zWfSP1_8bHPqeMwDu0_35U3QlSzyJgSgMuMjJaG9a9A8RUKjBKkdHYt3o08Ad-WCztg/s400/page.PNG" width="400" /></a></div>
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
Controller---------<br />
1- Add a controller class for product name it ProductController.<br />
2- Add a new Method in the class with the following structure<span style="font-size: x-small;"></span><br />
<span style="font-size: x-small;"> </span><span style="color: blue; font-size: x-small;"><span style="color: blue; font-size: x-small;">public</span></span><span style="font-size: x-small;"> </span><span style="color: blue; font-size: x-small;"><span style="color: blue; font-size: x-small;">class</span></span><span style="font-size: x-small;"> </span><span style="color: #2b91af; font-size: x-small;"><span style="color: #2b91af; font-size: x-small;">ProductController</span></span><span style="font-size: x-small;"> : </span><span style="color: #2b91af; font-size: x-small;"><span style="color: #2b91af; font-size: x-small;">Controller</span></span><br />
<span style="font-size: x-small;">{</span><br />
<span style="color: blue; font-size: x-small;"><span style="color: blue; font-size: x-small;"> public</span></span><span style="font-size: x-small;"> </span><span style="color: #2b91af; font-size: x-small;"><span style="color: #2b91af; font-size: x-small;">ActionResult</span></span><span style="font-size: x-small;"> Detail(</span><span style="color: blue; font-size: x-small;"><span style="color: blue; font-size: x-small;">int</span></span><span style="font-size: x-small;"> productID)</span><br />
<span style="font-size: x-small;">
</span><span style="font-size: x-small;"> {</span><br />
<span style="font-size: x-small;">
</span><span style="color: #2b91af; font-size: x-small;"><span style="color: #2b91af; font-size: x-small;"> ProductModels</span></span><span style="font-size: x-small;">.</span><span style="color: #2b91af; font-size: x-small;"><span style="color: #2b91af; font-size: x-small;">ProductInfo</span></span><span style="font-size: x-small;"> productInfo = </span><span style="color: blue; font-size: x-small;"><span style="color: blue; font-size: x-small;">new</span></span><span style="font-size: x-small;"> </span><span style="color: #2b91af; font-size: x-small;"><span style="color: #2b91af; font-size: x-small;">ProductModels</span></span><span style="font-size: x-small;">.</span><span style="color: #2b91af; font-size: x-small;"><span style="color: #2b91af; font-size: x-small;">ProductInfo</span></span><span style="font-size: x-small;">();</span><br />
<span style="font-size: x-small;">
</span><br />
<span style="font-size: x-small;"> productInfo.Price = 18;</span><br />
<span style="font-size: x-small;"> productInfo.ID = 1;</span><br />
<span style="font-size: x-small;"> productInfo.Name = "Monitor";</span><br />
<span style="color: blue; font-size: x-small;"><span style="color: blue; font-size: x-small;"> return</span></span><span style="font-size: x-small;"> View(</span><span style="font-size: x-small;">productInfo);</span><br />
<span style="font-size: x-small;">
</span><br />
<span style="font-size: x-small;"> }<br />
}</span><br />
<br />
Model-----------<br />
1- Add a new Model name it ProductModels<br />
2- Add a new Class into it wit the following info<br />
<br />
<span style="color: blue; font-size: x-small;"><span style="color: blue; font-size: x-small;"><span style="font-size: x-small;"> public class <span style="color: #76a5af;">ProductModels</span><br /> {<br /> public class <span style="color: #76a5af;">ProductInfo</span><br /> {<br /> public int <span style="color: black;">ID {</span> set; get; <span style="color: black;">}</span><br /><br /> public string <span style="color: black;">Name {</span> set; get; <span style="color: black;">}</span><br /><br /> public int <span style="color: black;">Price {</span> set; get; <span style="color: black;">}</span><br /> }<br /> }</span></span></span><br />
<br />
<span style="color: blue; font-size: x-small;"><span style="color: blue; font-size: x-small;"><span style="font-size: x-small;"><span style="color: black;">Now Its time to press F5 and see what you have done.</span></span></span></span><br />
<span style="color: blue; font-size: x-small;"><span style="color: blue; font-size: x-small;"><span style="font-size: x-small;"><span style="color: black;"> </span> </span></span></span>Amir Akhoundpourhttp://www.blogger.com/profile/09321829496260407874noreply@blogger.com1tag:blogger.com,1999:blog-5253495850624411226.post-80168237836668277732009-09-30T10:50:00.000-07:002009-09-30T10:58:30.848-07:00Open Outlook with New email - Console Application<div style="color: #666666;">Although there are some methodes in System.Web.Mail namespace for sending email , but sometimes customers like to open outlook automatically with a new mail inside and let user to complete the mail before sending, here I write a sample console application to do it, <br />
</div><br />
<div style="color: red;">note: add outlook com reference manually to your project.<br />
</div><span style="font-family: Arial; font-size: x-small;"> <br />
</span><br />
<span style="font-size: x-small;"><span style="color: blue; font-size: x-small;">using</span> System;</span><span style="color: blue; font-size: x-small;"><span style="color: blue; font-size: x-small;"> </span></span><br />
<span style="color: blue; font-size: x-small;"><span style="color: blue; font-size: x-small;">using </span></span><span style="font-size: x-small;"> System.Collections.Generic;</span><span style="color: blue; font-size: x-small;"><span style="color: blue; font-size: x-small;"> </span></span><br />
<span style="color: blue; font-size: x-small;"><span style="color: blue; font-size: x-small;">using </span></span><span style="font-size: x-small;"> System.Text;</span><span style="color: blue; font-size: x-small;"><span style="color: blue; font-size: x-small;"> </span></span><br />
<span style="color: blue; font-size: x-small;"><span style="color: blue; font-size: x-small;">using </span></span><span style="font-size: x-small;"> System.Diagnostics;</span><span style="color: blue; font-size: x-small;"><span style="color: blue; font-size: x-small;"> </span></span><br />
<span style="color: blue; font-size: x-small;"><span style="color: blue; font-size: x-small;">using </span></span><span style="font-size: x-small;"> Outlook = Microsoft.Office.Interop.Outlook; </span><br />
<span style="font-size: x-small;"></span><span style="color: blue; font-size: x-small;"><span style="color: blue; font-size: x-small;"> </span></span><br />
<span style="color: blue; font-size: x-small;"><span style="color: blue; font-size: x-small;">namespace </span></span><span style="font-size: x-small;"> Openoutlook </span><br />
<span style="font-size: x-small;">{</span><br />
<span style="font-size: x-small;"></span><span style="color: blue; font-size: x-small;"><span style="color: blue; font-size: x-small;">class</span></span><span style="font-size: x-small;"> </span><span style="color: #2b91af; font-size: x-small;"><span style="color: #2b91af; font-size: x-small;">Program</span></span><span style="font-size: x-small;"> </span><br />
<span style="font-size: x-small;">{</span><br />
<span style="font-size: x-small;"></span><span style="color: blue; font-size: x-small;"><span style="color: blue; font-size: x-small;">static</span></span><span style="font-size: x-small;"> </span><span style="color: blue; font-size: x-small;"><span style="color: blue; font-size: x-small;">void</span></span><span style="font-size: x-small;"> Main(</span><span style="color: blue; font-size: x-small;"><span style="color: blue; font-size: x-small;">string</span></span><span style="font-size: x-small;">[] args) </span><br />
<span style="font-size: x-small;">{</span><br />
<span style="font-size: x-small;">Outlook.</span><br />
<span style="font-size: x-small;"></span><span style="color: #2b91af; font-size: x-small;"><span style="color: #2b91af; font-size: x-small;">Application</span></span><span style="font-size: x-small;"> objOutlk = </span><span style="color: blue; font-size: x-small;"><span style="color: blue; font-size: x-small;">new</span></span><span style="font-size: x-small;"> Outlook.</span><span style="color: #2b91af; font-size: x-small;"><span style="color: #2b91af; font-size: x-small;">Application</span></span><span style="font-size: x-small;">(); </span><br />
<span style="font-size: x-small;"></span><span style="color: blue; font-size: x-small;"><span style="color: blue; font-size: x-small;">object</span></span><span style="font-size: x-small;"> objMail = </span><span style="color: blue; font-size: x-small;"><span style="color: blue; font-size: x-small;">new</span></span><span style="font-size: x-small;"> </span><span style="color: blue; font-size: x-small;"><span style="color: blue; font-size: x-small;">object</span></span><span style="font-size: x-small;">(); </span><br />
<span style="font-size: x-small;">Outlook.</span><br />
<span style="font-size: x-small;"></span><span style="color: #2b91af; font-size: x-small;"><span style="color: #2b91af; font-size: x-small;">MailItem</span></span><span style="font-size: x-small;"> mic = (Outlook.</span><span style="color: #2b91af; font-size: x-small;"><span style="color: #2b91af; font-size: x-small;">MailItem</span></span><span style="font-size: x-small;">)(objOutlk.CreateItem(Outlook.</span><span style="color: #2b91af; font-size: x-small;"><span style="color: #2b91af; font-size: x-small;">OlItemType</span></span><span style="font-size: x-small;">.olMailItem)); </span><br />
<span style="font-size: x-small;"></span><span style="color: green; font-size: x-small;"><span style="color: green; font-size: x-small;">//mic.To = //toTextBox.Text;</span></span><span style="font-size: x-small;"> </span><br />
<span style="font-size: x-small;"></span><span style="color: green; font-size: x-small;"><span style="color: green; font-size: x-small;">//mic.CC = ccTextBox.Text;</span></span><span style="font-size: x-small;"> </span><br />
<span style="font-size: x-small;"></span><span style="color: green; font-size: x-small;"><span style="color: green; font-size: x-small;">//mic.BCC = bccTextBox.Text;</span></span><span style="font-size: x-small;"> </span><br />
<span style="font-size: x-small;">mic.Subject =</span><span style="color: #a31515; font-size: x-small;"><span style="color: #a31515; font-size: x-small;">"Test Subject"</span></span><span style="font-size: x-small;">;</span><span style="color: green; font-size: x-small;"><span style="color: green; font-size: x-small;">// subjectTextBox.Text;</span></span><span style="font-size: x-small;"> </span><br />
<span style="font-size: x-small;">mic.Importance = Outlook.</span><br />
<span style="font-size: x-small;"></span><span style="color: #2b91af; font-size: x-small;"><span style="color: #2b91af; font-size: x-small;">OlImportance</span></span><span style="font-size: x-small;">.olImportanceNormal;</span><br />
<span style="font-size: x-small;"> </span><br />
<span style="font-size: x-small;"></span><span style="color: green; font-size: x-small;"><span style="color: green; font-size: x-small;">// mic.HTMLBody = sb.ToString();</span></span><span style="font-size: x-small;"> </span><br />
<span style="font-size: x-small;"></span><span style="color: green; font-size: x-small;"><span style="color: green; font-size: x-small;">// Adds Attachment to the Mail Message. </span></span><span style="font-size: x-small;"> </span><br />
<span style="color: green; font-size: x-small;"><span style="color: green; font-size: x-small;"></span></span><br />
<span style="font-size: x-small;"></span><span style="color: green; font-size: x-small;"><span style="color: green; font-size: x-small;">// All you need to do is to declare this relative to the number of attachments you have.</span></span><span style="font-size: x-small;"> </span><br />
<span style="color: #a31515; font-size: x-small;"><span style="color: black;">mic.Attachments.Add(</span><span style="color: #a31515; font-size: x-small;"><span style="color: black;"> </span>@"C:\temp\1.txt"</span></span><span style="font-size: x-small;">, Outlook.</span><span style="color: #2b91af; font-size: x-small;"><span style="color: #2b91af; font-size: x-small;">OlAttachmentType</span></span><span style="font-size: x-small;">.olByValue, 1, </span><span style="color: #a31515; font-size: x-small;"><span style="color: #a31515; font-size: x-small;">"Attachment Name"</span></span><span style="font-size: x-small;">); </span><br />
<span style="font-size: x-small;">mic.Attachments.Add( </span><span style="color: #a31515; font-size: x-small;"><span style="color: #a31515; font-size: x-small;">@"C:\temp\2.txt"</span></span><span style="font-size: x-small;">, Outlook.</span><span style="color: #2b91af; font-size: x-small;"><span style="color: #2b91af; font-size: x-small;">OlAttachmentType</span></span><span style="font-size: x-small;">.olByValue, 1, </span><span style="color: #a31515; font-size: x-small;"><span style="color: #a31515; font-size: x-small;">"Attachment Name"</span></span><span style="font-size: x-small;">); </span><br />
<span style="color: green; font-size: x-small;"><span style="color: green; font-size: x-small;">//Open outlook and display new msg mail<br />
</span></span><br />
<span style="font-size: x-small;">mic.Display(mic);</span><br />
<span style="color: green; font-size: x-small;"><span style="color: green; font-size: x-small;"></span></span><br />
<span style="color: green; font-size: x-small;"><span style="color: green; font-size: x-small;"></span></span><span style="font-size: x-small;"> </span><br />
<span style="font-size: x-small;">}</span><br />
<span style="font-size: x-small;">}</span><br />
<span style="font-size: x-small;">}</span><br />
<span style="font-size: x-small;">----------------------------</span><br />
<span style="font-size: x-small;"><span style="color: #666666;">I did not fill all field such as </span><b style="color: #666666;">body</b><span style="color: #666666;"> , </span><b style="color: #666666;">To</b><span style="color: #666666;"> or </span><b style="color: #666666;">CC</b><span style="color: #666666;"> , you can fill the by your self.</span><br />
</span><br />
<span style="font-size: x-small;"></span>Amir Akhoundpourhttp://www.blogger.com/profile/09321829496260407874noreply@blogger.com0tag:blogger.com,1999:blog-5253495850624411226.post-5085147860012874482009-09-27T08:49:00.000-07:002009-09-27T09:33:33.920-07:00Adding Row Number to GridView - ASP.NETGridView is a control which is used in all applications, most of the time showing a Row number in the left side of each row is needed. after adding a gridview on your aspx page then you should add template column , do the following things.<br />
As the picture shows , you should set "<span style="color: blue;">Container.DataItemIndex + 1</span>" to Text property of <span style="background-color: white;"><span style="color: blue;">Label</span> </span>within a<span style="color: blue;"> asp:TemplateField </span>in <span style="color: blue;">Columns </span>.<br />
<br />
<div class="separator" style="clear: both; text-align: center;"><br />
</div><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgqzlsUS_xc0UKJqLubPUsBRGEhnfkiNh4x6PxJNRDrHrupbdiD-xbYQNvxTJWXL35t7L7tYnh8V6TrMX_NMGbxTm28jVrEjM-X5p3XRTae4JRGMW3hR5ObXQQfxzsxGsTiVfdUXr4Qyoc/s1600-h/RowNumber.jpg" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgqzlsUS_xc0UKJqLubPUsBRGEhnfkiNh4x6PxJNRDrHrupbdiD-xbYQNvxTJWXL35t7L7tYnh8V6TrMX_NMGbxTm28jVrEjM-X5p3XRTae4JRGMW3hR5ObXQQfxzsxGsTiVfdUXr4Qyoc/s400/RowNumber.jpg" /></a><br />
</div>Amir Akhoundpourhttp://www.blogger.com/profile/09321829496260407874noreply@blogger.com0tag:blogger.com,1999:blog-5253495850624411226.post-8717786109182767202009-09-27T06:15:00.003-07:002009-09-27T09:33:53.607-07:00Clear Form method - Windows Form<div class="gmail_quote"><span style="color: #333333;">Clearing form data is one the methodes that developers sould write over and over, in this case writing a method which can be used in all forms is helpful, via this is a recursive method and depend on control type (textbox or dropdownlist ,...) it clear it's data.</span><br />
<br />
<span style="color: #3333ff;">public </span>static void ClearForm(Control parent)<br />
{<br />
foreach (System.Windows.Forms.Control ctrControl in parent.Controls)<br />
{<br />
<span style="color: #009900;"> //Loop through all controls </span><br />
if (object.ReferenceEquals(ctrControl.GetType(), typeof(System.Windows.Forms.TextBox)))<br />
{<br />
<span style="color: #009900;"> //Check to see if it's a textbox </span><br />
((System.Windows.Forms.TextBox)ctrControl).Text = string.Empty;<br />
<span style="color: #009900;"> //If it is then set the text to String.Empty (empty textbox) </span><br />
}<br />
else if (object.ReferenceEquals(ctrControl.GetType(), typeof(System.Windows.Forms.RichTextBox)))<br />
{<br />
<span style="color: #009900;"> //If its a RichTextBox clear the text</span><br />
((System.Windows.Forms.RichTextBox)ctrControl).Text = string.Empty;<br />
}<br />
else if (object.ReferenceEquals(ctrControl.GetType(), typeof(System.Windows.Forms.ComboBox)))<br />
{<br />
<span style="color: #009900;"> //Next check if it's a dropdown list </span><br />
((System.Windows.Forms.ComboBox)ctrControl).SelectedIndex = -1;<br />
//If it is then set its SelectedIndex to 0<br />
}<br />
else if (object.ReferenceEquals(ctrControl.GetType(), typeof(System.Windows.Forms.CheckBox)))<br />
{<br />
<span style="color: #009900;"> //Next uncheck all checkboxes</span><br />
((System.Windows.Forms.CheckBox)ctrControl).Checked = false;<br />
}<br />
else if (object.ReferenceEquals(ctrControl.GetType(), typeof(System.Windows.Forms.RadioButton)))<br />
{<br />
<span style="color: #009900;">//Unselect all RadioButtons</span><br />
((System.Windows.Forms.RadioButton)ctrControl).Checked = false;<br />
}<br />
if (ctrControl.Controls.Count > 0)<br />
{<br />
<span style="color: #009900;">//Call itself to get all other controls in other containers </span><br />
ClearForm(ctrControl);<br />
}<br />
}<br />
}<br />
<br />
</div>Amir Akhoundpourhttp://www.blogger.com/profile/09321829496260407874noreply@blogger.com0tag:blogger.com,1999:blog-5253495850624411226.post-68155140259701849562009-09-26T09:36:00.000-07:002009-09-27T09:34:22.300-07:00Convert TIF file to JPG(s) - ASP.NET<span style="color: #333333;">Sometimes showing a buch of JPG images is easier than a TIF file on your site, or sometimes you want to show the first page of a TIF file to give the better sense of the contain of TIF file, so you see this Conversion help you for more suitable designing your asp.net applicaion.</span><br />
<span style="color: #333333;">For creating a jpg file ftom a multiple page tif file you shouldn't go though While loop and just convert the first page. <br />
</span><br />
<span style="color: red;">Note: In this example I could'nt use "<" or ">" tage and use "/" instead :)<br />
</span><span style="color: #3333ff;">public</span> class ConvertImages<br />
{<br />
<span style="color: #3333ff;">public</span> ConvertImages()<br />
{<br />
<span style="color: #33cc00;"></span>}<br />
<span style="color: #33cc00;">/// <summary><br />
/// This function return list of images which is converted from a TIF file<br />
/// for using this function,the best way to itarate on returned list is using for each statement<br />
/// within the iteration you should Dispose each image.<br />
/// </summary><br />
/// </span><br />
<span style="color: #33cc00;"></span><br />
<span style="color: #33cc00;"><param name="TIFFillFullName" /></span><span style="color: #33cc00;"></span><span style="color: #33cc00;">Full path of TIF file such as :\Temp\MyFile.tif<br />
/// </span><br />
<span style="color: #33cc00;"></span><br />
<span style="color: #33cc00;"><param name="OutPutFolder" /></span><span style="color: #33cc00;"></span><span style="color: #33cc00;">the path folder which the images should be create<br />
/// <returns></returns><br />
</span><span style="color: #3333ff;">public</span> static List /Image/ ConvertTIFtoJPGs(string TIFFileFullName,string OutPutFolder)<br />
{<br />
System.Drawing.Image objImage,NewImage;<br />
Guid objGuid;<br />
System.Drawing.Imaging.FrameDimension objDimension;<br />
List<system.drawing.image> ImageList;<br />
string OutputFileName;<br />
int TotalFrames = 0;<br />
int ItemIndex = 0;<br />
objImage = Image.FromFile(TIFFileFullName);<br />
objGuid = objImage.FrameDimensionsList[0];<br />
objDimension = new System.Drawing.Imaging.FrameDimension(objGuid);<br />
TotalFrames = objImage.GetFrameCount(objDimension);<br />
ImageList = new List / image/ (TotalFrames);<br />
while (ItemIndex < TotalFrames) { objImage.SelectActiveFrame(objDimension, ItemIndex); OutputFileName = OutPutFolder + @"\" + Guid.NewGuid().ToString() + ".JPG"; objImage.Save(OutputFileName, System.Drawing.Imaging.ImageFormat.Jpeg); NewImage = Image.FromFile(OutputFileName); ImageList.Add(NewImage); ItemIndex++; } objImage.Dispose(); return ImageList; } } <span style="color: #3333ff;"><span style="color: #009900;">//Here I write a test procedure in another class to test above class</span><br />
private <span style="color: black;">void Test_TIF2JPGConversion()</span><br />
<span style="color: black;">{</span><br />
<br />
<span style="color: black;">List/Image/ imageList;</span><br />
<span style="color: black;">imageList =ConvertImages.ConvertTIFtoJPGs(@"C:\Temp\MyTIF.JPG", C:\Temp\Images"); foreach (Image imageItem in imageList)<br />
{</span><br />
<span style="color: #33cc00;">//Do something with images, such as storing or anything else<br />
</span><br />
<span style="color: #33cc00;">//Remember to dispose each image</span><br />
imageItem.Dispose();<br />
}<br />
<br />
</span></system.drawing.image>Amir Akhoundpourhttp://www.blogger.com/profile/09321829496260407874noreply@blogger.com0tag:blogger.com,1999:blog-5253495850624411226.post-14742631884386302962009-09-25T11:32:00.001-07:002009-09-25T22:35:00.408-07:00Storing Application Message Staticly - ASP.NET - C#<span style="color:#333333;">Having a list of messages is always required within application, there are many ways to implement a message list. First of all you should categorized the messages such as Info ,Warnings , Errors , ... . may be you think the best way is saving messages in database but what if the database is down ,so we couldnt access to our messages, or saving all messages in XML file, what if the XML file is deleted , so you see we should prepare a general solution to satisfy all of the situations, here I'm going to implement a list of messages in the application staticly to store a critical messages ,in this case we could sure the list is always available. later I will implement a general solution which consists Database/XML Message list and types and Static message list in the application.<br /><br />First of all we should prepare SystemMessage Class which contains messages, then we you should prepare the EntityBase class which inherits from Web.UI.page class and has a private SystemMessage member, then all of the other classes and pages should be inherited from BaseEntityClass. Here is the sample Class Diagram and Code :</span> <p><img style="TEXT-ALIGN: center; MARGIN: 0px auto 5px; WIDTH: 317px; DISPLAY: block; HEIGHT: 173px; CURSOR: hand" id="BLOGGER_PHOTO_ID_5385490753204333762" border="0" alt="Class Diagram for Message List" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhvmecqNvrmz1DNft7u9AVXvFXOXqi0Xk6vP6Gv1_S5DJhp_wqeGhYnvIdYc8gGensRMKG5erGi8cSCdwXYhgR5YQpjYI-3Rp2gLHzJgL8gGQHrS_ex4loQfA8lJNqfyUXnoJ_75Rtf26c/s320/MessageList1.jpg" /><span style="color:#3366ff;">public</span> class BaseEntity: System.Web.UI.Page<br />{<br /><span style="color:#3366ff;">private</span> SystemMessage sm;<br /><span style="color:#3366ff;">protected </span>BaseEntity()<br />{<br />sm = new SystemMessage();<br />}<br /><span style="color:#33cc00;">/// <summary><br />/// Define Message by index<br />/// <returns></returns></span><br /><span style="color:#3366ff;">public</span> string Message(int MessageIndex)<br />{<br />return sm[MessageIndex];<br />}<br />}<br /><br /><span style="color:#33cc00;">//--------------------------------------------------</span><br /><br /><span style="color:#3366ff;">public</span> class SystemMessage<br />{<br /><span style="color:#3366ff;">private</span> static System.Collections.Generic.Dictionary<int,> _MessageList=null;<br /><span style="color:#3366ff;">public</span> SystemMessage()<br />{<br />_MessageList = new System.Collections.Generic.Dictionary<int,>();<br />_MessageList.Add(1, "Error #16576");<br />_MessageList.Add(2, "Add record to database");<br />_MessageList.Add(3, "Warning , this field already exist in database");<br />_MessageList.Add(4, "Try later!");<br />}<br /><br /><span style="color:#33cc00;">//Define Readonly indexer for this class</span><br />public string this[int index]<br />{<br />get<br />{<br />if (_MessageList.ContainsKey(index) == true)<br />return _MessageList[index];<br />return index.ToString() + " does not exist in the message list";<br />}<br />}<br />}<br /><br /><span style="color:#33cc00;">//-----------------------------------------------</span><br /><span style="color:#33cc00;">//Now we are in Default.aspx.cs class can access our message list by typing just Message( MessageIndex )</span><br /><br /><span style="color:#3366ff;">public</span> partial class _Default : BaseEntity<br />{<br /><span style="color:#3366ff;">protected</span> void Page_Load(object sender, EventArgs e)<br />{<br />Response.Write(Message(2));<br />}<br />} </p><p><span style="color:#333333;">Then you should see "<span style="color:#660000;">Add record to database</span>" text in your page.<br /><br />In the EntityBase class you could add other methods which are required in the application such as check user access or Logging methods.</span> </p>Amir Akhoundpourhttp://www.blogger.com/profile/09321829496260407874noreply@blogger.com0tag:blogger.com,1999:blog-5253495850624411226.post-67649847665214644052009-09-25T04:19:00.000-07:002009-09-25T22:36:06.856-07:00Authenticate user via Active Directory - ASP.NET - C#<div style="color:#cc0000;"><span style="color:#333333;">Authentication is one of most important process of asp.net application ,there are four modes which can be defined in web.config file, "Passport", "Windows", "Forms" and "None".<br /></span></div><span style="color:#333333;">many applications use Forms Mode which means you should design a login.aspx page and user enter username and password , however many useres suffer to memorize many user name and password for working with applications, one of the most suitable way to release from this problem is used the same user name and password which users use to logon to his/her computer , I mean the same user name and password in Active Directory. using this class provides this facility for the application. just create an instance of the class and call IsExistedDomainUser function.<br /></span><br /><span style="color:#3d85c6;">using</span> System;<br /><span style="color:#3d85c6;">using</span> System.Configuration;<br /><span style="color:#3d85c6;">using</span> System.Web;<br /><span style="color:#3d85c6;">using</span> System.Web.Security;<br /><span style="color:#3d85c6;">using</span> System.DirectoryServices;<br /><br /><br /><span style="color:#6aa84f;">/// <summary></summary></span><br /><span style="color:#6aa84f;">/// User can be authenticated with existing User Name and password in Active Directory</span><br /><span style="color:#6aa84f;">/// LdapPath such as LDAP://ServerName/DC=MyCompany,DC=COM</span><br /><span style="color:#6aa84f;">/// </span><br /><span style="color:#3d85c6;">public</span> class LDAPAuthentication<br />{<br />string _LdapPath;<br />string _FilterAttribute;<br /><br /><br /><span style="color:#3d85c6;">public</span> LDAPAuthentication(string LdapPath)<br />{<br />_LdapPath = LdapPath;<br /><br />}<br /><br /><span style="color:#3d85c6;">public</span> bool IsExistedDomainUser(System.Web.HttpResponse Response, string strUsername, string strDomain, string strPassword, bool isCookiePersistent)<br />{<br /><br />if (IsAuthenticated(strDomain, strUsername, strPassword) == true)<br />{<br /><br /><span style="color:#6aa84f;">//Create the ticket, and add the groups. </span><br />FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, strUsername, DateTime.Now, DateTime.Now.AddMinutes(60), isCookiePersistent, FormsAuthentication.FormsCookiePath);<br /><br /><span style="color:#6aa84f;">//Encrypt the ticket.</span><br />string strEncryptedTicket = FormsAuthentication.Encrypt(authTicket);<br /><br /><span style="color:#6aa84f;">//Create a cookie, and then add the encrypted ticket to the cookie as data.</span><br />HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, strEncryptedTicket);<br /><br />if (isCookiePersistent == true)<br />authCookie.Expires = authTicket.Expiration;<br /><br /><span style="color:#6aa84f;">//Add the cookie to the outgoing cookies collection.</span><br />Response.Cookies.Add(authCookie);<br /><br /><span style="color:#6aa84f;">//If user registerd in Doamin</span><br />return true;<br />}<br />else<br /><span style="color:#6aa84f;">//If user does not registerd in Doamin </span><br />return false;<br /><br />}<br /><br /><span style="color:#3d85c6;">private</span> bool IsAuthenticated(string domain, string username, string pwd)<br />{<br />string domainAndUsername = domain + "\\" + username;<br />DirectoryEntry entry = new DirectoryEntry(_LdapPath, domainAndUsername, pwd);<br />try<br />{<br />object obj = entry.NativeObject;<br />DirectorySearcher search = new DirectorySearcher(entry);<br />search.Filter = "(SAMAccountName=" + username + ")";<br />search.PropertiesToLoad.Add("cn");<br />SearchResult result = search.FindOne();<br />if ((result == null))<br />{<br />return false;<br />}<br />_LdapPath = result.Path;<br />_FilterAttribute = ((string)result.Properties["cn"][0]);<br />}<br />catch<br />{<br />throw new Exception("Incorrect User name or passowrd, try again!");<br />}<br />return true;<br />}<br />}<br /><div style="COLOR: #6aa84f">//-----------------------------------------------------------------<br /></div><div style="color:#cc0000;"><span style="color:#333333;">changing Web.Config and set your logon form name with the following syntax<br />Logon page in this example is Logon.aspx in the</span> <span style="color:#3366ff;">authentication</span> <span style="color:#333333;">tag<br /></span><span style="color:#666666;">forms name="AuthCookie" loginUrl="Logon.aspx"</span></div>Amir Akhoundpourhttp://www.blogger.com/profile/09321829496260407874noreply@blogger.com0tag:blogger.com,1999:blog-5253495850624411226.post-39243934680084194042009-09-25T01:20:00.000-07:002009-09-27T09:34:40.671-07:00Add CopyRight Label to the Images - ASP.NET<span style="color: #333333;">Add CopyRight label to the images in the site sometimes is mandatory, you can change all images and add copyright label on some programs such as microsoft paint /adobe photoshop and ... and you should always do the same thing in this way, there is another way in .NET which help you not to do this fraustraiting job and use the following class in your project ,add specific Copyright label to the image, and everytime the user requests an image call the following function whithin a class. <span style="color: #993399;">This sample is my favorite one :-)<br />
</span>Sample Image :</span><span style="color: red;"><br />
</span><br />
<div class="separator" style="clear: both; text-align: center;"><br />
</div><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjENHsC7Cjr4J32Cpz4TRdVXwIHAsO0KNSlosmCVD4-SZzRHr-ESwbk1AZiFPinjKi4Vu8swAP4ZqYl6vzi4ntk5qqW-tkOISPy0R-B4MqtOjn-q05_EGj4LTSA2HNeLkLw9Hc2tgVUiAs/s1600-h/945c4c90-e109-4e7f-aa8f-cc1290b64060.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img alt="Adding copyright label to the image" border="0" iq="true" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjENHsC7Cjr4J32Cpz4TRdVXwIHAsO0KNSlosmCVD4-SZzRHr-ESwbk1AZiFPinjKi4Vu8swAP4ZqYl6vzi4ntk5qqW-tkOISPy0R-B4MqtOjn-q05_EGj4LTSA2HNeLkLw9Hc2tgVUiAs/s320/945c4c90-e109-4e7f-aa8f-cc1290b64060.jpg" /></a><br />
</div><br />
<span style="color: #3366ff;">public</span> class ChangeImage<br />
{<br />
<span style="color: #3366ff;">public</span> System.Drawing.Image AddCopyRightToImage(System.Drawing.Image img)<br />
{<br />
<br />
<span style="color: #33cc00;">// Define the Bitmap, Graphics, Font, and Brush for copyright logo<br />
</span>Graphics g = Graphics.FromImage(img);<br />
Font f = new Font("Arial", 9);<br />
<br />
<span style="color: #33cc00;">// Create the foreground text brush<br />
</span>Brush b = new SolidBrush(Color.White);<br />
<br />
<span style="color: #33cc00;">// Create the backround text brush<br />
</span>Brush bb = new SolidBrush(Color.White);<br />
<br />
<span style="color: #33cc00;">// Add the copyright text background<br />
</span>string ct = "Copyright 2009, Company Name , Inc.";<br />
<br />
<span style="color: #33cc00;">//Set Label Alighnment<br />
</span>StringFormat sf = new StringFormat();<br />
sf.Alignment = StringAlignment.Center;<br />
<br />
<span style="color: #33cc00;">// Add the copyright text foreground </span><br />
g.DrawString(ct, f, b, img.Width / 2, 20, sf);<br />
<br />
g.DrawImage(img, new Rectangle(0, 0, img.Width, img.Height), new Rectangle(0, 0, img.Width, img.Height), GraphicsUnit.Pixel);<br />
<br />
return img;<br />
<br />
}<br />
}Amir Akhoundpourhttp://www.blogger.com/profile/09321829496260407874noreply@blogger.com1tag:blogger.com,1999:blog-5253495850624411226.post-49134693460489149342009-09-24T22:27:00.000-07:002009-09-27T09:34:56.257-07:00Impersonate User in Active Directory - ASP.NET<span style="color: #333333;">Via the following class you can athenticate s specific user to specific domain and after that you access the resources (such as Doc or anything else) , and finally call UndoImpersotae function to disconnect athenticated user.<br />
<br />
<b>For inctance</b> your application is installed on AppServer.WemDomain.local and you need to access some resources on FileServer.FileDomain.local , so you should have a user in FileDomain.local and then authenticate it and access to the resources and then close athentication proccess all these thing is happened in background and the user could not understand where the file come from.<br />
</span><br />
<span style="color: #3366ff;">public</span> class ImpersonateUser_ActiveDirectory<br />
{<br />
<br />
<span style="color: #3366ff;">public </span>const int LOGON32_LOGON_INTERACTIVE = 9;<br />
<span style="color: #3366ff;">public</span> const int LOGON32_PROVIDER_DEFAULT = 0;<br />
WindowsImpersonationContext impersonationContext;<br />
[DllImport("advapi32.dll")]<br />
<span style="color: #3366ff;">public</span> static extern int LogonUserA(String lpszUserName,<br />
String lpszDomain,<br />
String lpszPassword,<br />
int dwLogonType,<br />
int dwLogonProvider,<br />
ref IntPtr phToken);<br />
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]<br />
<span style="color: #3366ff;">public</span> static extern int DuplicateToken(IntPtr hToken,<br />
int impersonationLevel,<br />
ref IntPtr hNewToken);<br />
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]<br />
<span style="color: #3366ff;">public</span> static extern bool RevertToSelf();<br />
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]<br />
<span style="color: #3366ff;">public</span> static extern bool CloseHandle(IntPtr handle);<br />
<br />
<span style="color: #33cc00;">//Athenticate specific user in Active Directory</span><br />
<span style="color: #3366ff;">public</span> bool impersonateValidUser(String userName, String domain, String password)<br />
{<br />
WindowsIdentity tempWindowsIdentity;<br />
IntPtr token = IntPtr.Zero;<br />
IntPtr tokenDuplicate = IntPtr.Zero;<br />
if (RevertToSelf())<br />
{<br />
if (LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE,<br />
LOGON32_PROVIDER_DEFAULT, ref token) != 0)<br />
{<br />
if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)<br />
{<br />
tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);<br />
impersonationContext = tempWindowsIdentity.Impersonate();<br />
if (impersonationContext != null)<br />
{<br />
CloseHandle(token);<br />
CloseHandle(tokenDuplicate);<br />
return true;<br />
}<br />
}<br />
}<br />
}<br />
if (token != IntPtr.Zero)<br />
CloseHandle(token);<br />
if (tokenDuplicate != IntPtr.Zero)<br />
CloseHandle(tokenDuplicate);<br />
return false;<br />
}<br />
<br />
<span style="color: #33cc00;">//Undo authentication for authenticated user<br />
</span><span style="color: #3366ff;">private</span> void undoImpersonation()<br />
{<br />
impersonationContext.Undo();<br />
}<br />
}<br />
<br />
--------------------------------------------------------<br />
<br />
<span style="color: red;">you can save user info and domain info in Web.config and read these information with the following syntax</span><br />
<br />
string UserName = ConfigurationSettings.AppSettings["<span style="color: #cc0000;">UserName</span>"];Amir Akhoundpourhttp://www.blogger.com/profile/09321829496260407874noreply@blogger.com0tag:blogger.com,1999:blog-5253495850624411226.post-41341637001110577592009-09-24T10:19:00.000-07:002009-09-27T09:35:26.805-07:00Changing Image Scale And Resolution - ASP.NET<span style="color: red;"><span style="color: #333333;">Storing image on a optimized size and resolution(network administrator sense it) or transfering optimized images on a limited network capacity allways affect the application performace(Network administrator and all Users sense it).</span></span><br />
<br />
<br />
<span style="color: #3366ff;">using </span>System;<br />
<span style="color: #3366ff;">using</span> System.Collections.Generic;<br />
<span style="color: #3366ff;">using</span> System.Text;<br />
<span style="color: #3366ff;">using</span> System.Drawing;<br />
<span style="color: #3366ff;">using</span> System.Drawing.Imaging;<br />
<span style="color: #3366ff;">using</span> System.Drawing.Drawing2D;<br />
<br />
<span style="color: #3366ff;">namespace</span> ChangingImage<br />
{<br />
<span style="color: #3366ff;">public</span> <span style="color: #3366ff;">class</span> ImageResize<br />
{<br />
<span style="color: #3366ff;">private</span> ImageResize() { }<br />
<span style="color: #33cc00;">//Scale the image to a percentage of its actual size. </span><br />
<span style="color: #3366ff;">public</span> static Image ScaleByPercentage(Image img, double percent)<br />
{<br />
double fractionalPercentage = (percent / 100.0);<br />
int outputWidth = (int)(img.Width * fractionalPercentage);<br />
int outputHeight = (int)(img.Height * fractionalPercentage);<br />
return ImageResize.ScaleImage(img, outputWidth, outputHeight);<br />
}<br />
<span style="color: #33cc00;">//Scale down the image till it fits the given size.</span><br />
<span style="color: #3366ff;">public</span> static Image ScaleDownTillFits(Image img, Size size)<br />
{<br />
Image ret = img;<br />
bool bFound = false;<br />
if ((img.Width > size.Width) (img.Height > size.Height))<br />
{<br />
for (double percent = 100; percent > 0; percent--)<br />
{<br />
double fractionalPercentage = (percent / 100.0);<br />
int outputWidth = (int)(img.Width * fractionalPercentage);<br />
int outputHeight = (int)(img.Height * fractionalPercentage);<br />
if ((outputWidth < bfound =" true;" ret =" ImageResize.ScaleImage(img," ret =" ImageResize.ScaleImage(img," color="#33cc00">//Scale an image by a set width. The height will be set proportionally.<br />
<span style="color: #3366ff;">public</span> static Image ScaleByWidth(Image img, int width)<br />
{<br />
double fractionalPercentage = ((double)width / (double)img.Width);<br />
int outputWidth = width;<br />
int outputHeight = (int)(img.Height * fractionalPercentage);<br />
return ImageResize.ScaleImage(img, outputWidth, outputHeight);<br />
}<br />
<span style="color: #33cc00;">//Scale an image by a set height. The width will be set proportionally.<br />
</span><span style="color: #3366ff;">public</span> static Image ScaleByHeight(Image img, int height)<br />
{<br />
double fractionalPercentage = ((double)height / (double)img.Height);<br />
int outputWidth = (int)(img.Width * fractionalPercentage);<br />
int outputHeight = height;<br />
return ImageResize.ScaleImage(img, outputWidth, outputHeight);<br />
}<br />
<span style="color: #33cc00;">//Scale an image by a set Height and set Specific Resolution. The width will be set </span><span style="color: #33cc00;">proportionally. </span><br />
<span style="color: #3366ff;">public</span> static Image ScaleByHeightAndResolution(Image img, int height,float Resolution)<br />
{<br />
double fractionalPercentage = ((double)height / (double)img.Height);<br />
int outputWidth = (int)(img.Width * fractionalPercentage);<br />
int outputHeight = height;<br />
return ImageResize.ScaleImageAndResolution(img, outputWidth, outputHeight,Resolution);<br />
}<br />
<span style="color: #33cc00;">//Scale an image to a given width and height.<br />
</span><span style="color: #3366ff;">public </span>static Image ScaleImage(Image img, int outputWidth, int outputHeight)<br />
{<br />
Bitmap outputImage = new Bitmap(outputWidth, outputHeight, img.PixelFormat);<br />
outputImage.SetResolution(img.HorizontalResolution, img.VerticalResolution);<br />
Graphics graphics = Graphics.FromImage(outputImage);<br />
graphics.InterpolationMode = InterpolationMode.Bilinear;<br />
graphics.DrawImage(img, new Rectangle(0, 0, outputWidth, outputHeight), new Rectangle(0, 0, img.Width, img.Height), GraphicsUnit.Pixel);<br />
graphics.Dispose();<br />
return outputImage;<br />
}<br />
<br />
<span style="color: #33cc00;">//Change image scale by Width and Height and Set New Resoltion too.<br />
</span><span style="color: #3366ff;">public</span> static Image ScaleImageAndResolution(Image img, int outputWidth, int outputHeight,float Resolution)<br />
{<br />
Bitmap outputImage = new Bitmap(outputWidth, outputHeight, img.PixelFormat);<br />
outputImage.SetResolution(Resolution, Resolution);<br />
Graphics graphics = Graphics.FromImage(outputImage);<br />
Graphics.InterpolationMode = InterpolationMode.Bilinear;<br />
graphics.DrawImage(img, new Rectangle(0, 0, outputWidth, outputHeight), new Rectangle(0, 0, img.Width, img.Height), GraphicsUnit.Pixel);<br />
graphics.Dispose();<br />
return outputImage;<br />
}<br />
}<br />
}Amir Akhoundpourhttp://www.blogger.com/profile/09321829496260407874noreply@blogger.com1