Friday, December 1, 2017

Base64 to Image in c#



///
        /// This function convert data url to Image and return saved image path
        ///
        ///
        ///
        public string Base64ToImage(string data)
        {
            string ret = "";
            var base64Data = Regex.Match(data, @"data:image/(?.+?),(?.+)").Groups["data"].Value;
            var binData = Convert.FromBase64String(base64Data);

            using (var stream = new MemoryStream(binData))
            {
                using (Image img = new Bitmap(stream))
                {
                    string basePath = Server.MapPath("~/UserFiles/PhotoPrint");
                    ret = Guid.NewGuid().ToString() + ".png";
                    img.Save(basePath + "\\" + ret, ImageFormat.Png);
                }
            }

            return ret;
        }

Friday, March 7, 2014

GridView with JQuery




http://www.jquerybyexample.net/2012/05/gridview-and-jquery-in-aspnet.html

Friday, May 22, 2009

Indexer

Defining an indexer allows you to create classes that act like "virtual arrays." Instances of that class can be accessed using the [] array access operator. Defining an indexer in C# is similar to defining operator [] in C++, but is considerably more flexible. For classes that encapsulate array- or collection-like functionality, using an indexer allows the users of that class to use the array syntax to access the class.

Example

The following example shows how to declare a private array field, myArray, and an indexer. Using the indexer allows direct access to the instance b[i]. The alternative to using the indexer is to declare the array as a public member and access its members, myArray[i], directly.

// cs_keyword_indexers.cs
using System;
class IndexerClass
{
private int [] myArray = new int[100];
public int this [int index] // Indexer declaration
{
get
{
// Check the index limits.
if (index <>= 100)
return 0;
else
return myArray[index];
}
set
{
if (!(index <>= 100))
myArray[index] = value;
}
}
}

public class MainClass
{
public static void Main()
{
IndexerClass b = new IndexerClass();
// Call the indexer to initialize the elements #3 and #5.
b[3] = 256;
b[5] = 1024;
for (int i=0; i<=10; i++)
{
Console.WriteLine("Element #{0} = {1}", i, b[i]);
}
}
}

Abstract Class in OOPs

Hi,

i find so many times developers confusing with the term Abstract or abstraction in OOPS. Here's a perfect description and definition of abstraction in OOPs. Hope it will help u better understanding of Abstract and OOPs.

Abstraction
Abstraction is another good feature of OOPS. Abstraction means to show only the necessary details to the client of the object. Do you know the inner details of the Monitor of your PC? What happen when you switch ON Monitor? Does this matter to you what is happening inside the Monitor? No Right, Important thing for you is weather Monitor is ON or NOT. When you change the gear of your vehicle are you really concern about the inner details of your vehicle engine? No but what matter to you is that Gear must get changed that’s it!! This is abstraction; show only the details which matter to the user.
Let’s say you have a method "CalculateSalary" in your Employee class, which takes EmployeeId as parameter and returns the salary of the employee for the current month as an integer value. Now if someone wants to use that method. He does not need to care about how Employee object calculates the salary? An only thing he needs to be concern is name of the method, its input parameters and format of resulting member, Right?
So abstraction says expose only the details which are concern with the user (client) of your object. So the client who is using your class need not to be aware of the inner details like how you class do the operations? He needs to know just few details. This certainly helps in reusability of the code.
As I have generally seen developers are not very much comfortable with the database programming. Let’s say you are designing a class that is used to interact with the database and to perform some of database operations. Now client of your class need not to be aware of database programming, he just need to be aware of some of the details of your class and easily can perform the database operations exposed by your class without deep knowledge of database programming.
The best thing of abstract is that this decouples the user of the object and its implementation. So now object is easy to understand and maintain also. As if there is any change in the process of some operation. You just need to change the inner details of a method, which have no impact on the client of class.



============================




Abstraction means that you have some class that is more common than others that extend it. By example, if you have classes Triangle and Rectangle:
class Triangle
{
public double a;
public double b;
public double c;

public double Area
{
get { return triangle's area }
}
}

class Rectangle
{
public double a;
public double b;

public double Area
{
get { return rectangle's area }
}
}
These classes have something in common - they have property called Area plus also sides (a and b) but I don't see any reason to make sides abstract. Let's add also Circle and we have no point of sides at all. Now let's generalize these classes and let's create one more common class called Shape. Also, let's make it abstract class so this class cannot be created separately - it can be created only through extending.
public abstract class Shape
{
public double Area();
}
And now let's write previous classes so they extend Shape class.
class Triangle : Shape
{
public double a;
public double b;
public double c;

public double Area
{
get { return triangle's area }
}
}

class Rectangle : Shape
{
public double a;
public double b;

public double Area
{
get { return rectangle's area }
}
}
So, what's the win, you may ask? Okay, not of these classes use Shape as their base class. So does Circle. In the context where we don 't care about specific properties of object we can handle all extended objects as Shape. By example, let's calculate total area of Shapes in list.
List shapes = ListShapes() // contains circles, triangles and rectangles
double area = 0;

foreach(Shape shape in shapes)
area += shape.Area;

// do something useful with area here
Without extending Shape class we should write separate loop for each shape type. And also we have to have separate methods to get different types of shapes. Now we had only one method to list shapes and one loop to handle them as one - we didn't cared about lengths of sides or radiuses or any other specific properties. Same way you can make many other abstractions. By example, you can add coordinates to Shape class if shape's positioning is required.




========================


Abstraction in the object oriented world generalizes the characteristics and behaviours. The following classes describe this

public class Mammal

{

public string m_color; // Abstract Charactersistic 1

public string m_height; // Abstract Charactersistic 2

public string m_weight; // Abstract Charactersistic 1

public Mammal()

{

}

public void Move()

{

// Abstract behaviour

}

}

// Elephant is a Mammal hence it extends abstract class Mammal

public class Elephant : Mammal

{

public string m_color = "gray"; // Gray color

public int m_height = 120; // 10 feet or 120 inches

public int m_weight = 1500; // 1500 pounds

public Elephant()

{

}

public void Move()

{

// Implement the Elephant Walks Behaviour

}

}

// A whale is also a mammal hence it extends the Mammal class

public class Whale: Mammal

{

public string m_color = "darkgray"; // Dark Gray color

public int m_height = 60; // 5 feet or 60 inches

public int m_weight = 2000; // 2000 pounds

public Whale()

{

}

public void Move()

{

// Implement the way a Whale swims

}

}

Saturday, March 21, 2009

Multiple Selection DropDownList for asp.net

Hi,

I have developed Multiple selection dropdownlist Custom Control. Below are the preview of control. This is a Custom Control which you can use in asp.net.

Features :

  • Allow multiple selection.
  • Support Design Time Data Binding.
  • Quick Search through the list.
  • Select / Unselect all items
  • Persist value after postback.
  • Multiple control can be use in the same page.

Download Here









------------
















-----------
















-------------







------------








-------------























Download Here




Regards
Deepak Rai
+919823138839
deep.k.rai@gmail.com




Friday, March 6, 2009

Dropdownlist width in IE

DEMO


In IE, the dropdown-list takes the same width as the dropbox (i hope i am making sense) whereas in Firefox the dropdown-list's width varies according to the content.

This basically means that i have to make sure that the dropbox has to be wide enough to display the longest selection possible. this makes my page look very ugly :(

Is there any workaround for this problem? How can i uses CSS to set different widths for dropbox and the dropdownlist?




Creating your own drop down list is more of a pain than it's worth. You can use some javascript to make the IE drop down work.

Check out this solution here: http://www.hedgerwow.com/360/dhtml/ui_select_with_fixed_width/demo.php

http://www.hedgerwow.com/360/dhtml/ui_select_with_fixed_width/ie-select-width-fix.js

It uses a bit of the YUI library and a special extension for fixing IE select boxes.

You will need to include the following and wrap your elements in a

Put these before the body tag of your page:


<script src="http://us.js2.yimg.com/us.js.yimg.com/lib/common/utils/2/yahoo_2.0.0-b3.js" type="text/javascript">
script>
<script src="http://us.js2.yimg.com/us.js.yimg.com/lib/common/utils/2/event_2.0.0-b3.js" type="text/javascript">
script>
<script src="http://us.js2.yimg.com/us.js.yimg.com/lib/common/utils/2/dom_2.0.2-b3.js" type="text/javascript">
script>
<script src="ie-select-width-fix.js" type="text/javascript">
script>
<script>
// for each select box you want to affect, apply this:
var s1 = new YAHOO.Hack.FixIESelectWidth( 's1' ); // s1 is the ID of the select box you want to affect
script>


Creating your own drop down list is more of a pain than it's worth. You can use some javascript to make the IE drop down work.

Check out this solution here: http://www.hedgerwow.com/360/dhtml/ui_select_with_fixed_width/demo.php

http://www.hedgerwow.com/360/dhtml/ui_select_with_fixed_width/ie-select-width-fix.js

It uses a bit of the YUI library and a special extension for fixing IE select boxes.

You will need to include the following and wrap your elements in a

Put these before the body tag of your page:

<script src="http://us.js2.yimg.com/us.js.yimg.com/lib/common/utils/2/yahoo_2.0.0-b3.js" type="text/javascript">
script>
<script src="http://us.js2.yimg.com/us.js.yimg.com/lib/common/utils/2/event_2.0.0-b3.js" type="text/javascript">
script>
<script src="http://us.js2.yimg.com/us.js.yimg.com/lib/common/utils/2/dom_2.0.2-b3.js" type="text/javascript">
script>
<script src="ie-select-width-fix.js" type="text/javascript">
script>
<script>
// for each select box you want to affect, apply this:
var s1 = new YAHOO.Hack.FixIESelectWidth( 's1' ); // s1 is the ID of the select box you want to affect
script>

Post acceptance edit:

You can also do this without the YUI library and Hack control. All you really need to do is put an onmouseover="this.style.width='auto'" onmouseout="this.style.width='100px'" (or whatever you want) on the select element. The YUI control gives it that nice animation but it's not necessary. This task can also be accomplished with jquery and other libraries (although, I haven't found explicit documentation for this)

-- amendment to the edit: IE has a problem with the onmouseout for select controls (it doesn't consider mouseover on options being a mouseover on the select). This makes using a mouseout very tricky. The first solution is the best I've found so far.

Exporting Euro symbol in excel from asp.net.

I was working with exporting GridView to Excel. GridView contains one column that has currency symbols. After exporting to excel all currency were displaying correctly but Euro(€) symbols got converted to something other characters like this "รข‚¬" . After searching on internet i got solution. below is the solution.


public void ExportExcel(string filename, GridView gv)
{
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=" + filename + ".xls");
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gv.RenderControl(htw);
string output = sw.ToString();
//////////////////////
byte[] euroByte = new byte[1];
euroByte[0] = (byte)128;
bool isAfterFirst = false;
foreach (string item in output.Split('€'))
{
if (isAfterFirst)
{
Response.OutputStream.Write(euroByte, 0, 1);
}
Response.Write(item);
Response.Flush();
isAfterFirst = true;
}
Response.Write("\r\n");
//////////////////////
Response.End();
}

Wednesday, March 4, 2009

Count the record returned by SQLDataSource

protected void SqlDataSource3_Selected(object sender, SqlDataSourceStatusEventArgs e)
{
GVNO.Text = "0";
string gridViewTotalRowCount = e.AffectedRows.ToString();
GVNO.Text = gridViewTotalRowCount;

}


Thursday, December 27, 2007

Disable Selection in Web page

Thursday, November 29, 2007

Writing all data from Dataset to XML (with null value too).

Imports Microsoft.VisualBasic

Imports System.Data


Imports
System.Data.OracleClient


Public Class DatasetToXML

Inherits
System.Web.UI.Page


Dim con As New
OracleConnection(" DATA SOURCE=ORACLE;PERSIST
SECURITY INFO=TRUE;USER ID=DF_TRUCK;PASSWORD=DF_TRUCK;UNICODE=TRUE "
)



Public Function DS2XML(ByVal
ds As DataSet) As
Boolean

Dim xs As New
System.Xml.XmlWriterSettings

xs.Indent = True

Dim xw As System.Xml.XmlWriter =
System.Xml.XmlWriter.Create(Server.MapPath("~/IEData/abc.xml"),
xs)

xw.WriteStartElement("DF_TRUCK") 'Name
of schema

For Each dt As DataTable In ds.Tables

For
Each dr As
DataRow In ds.Tables(dt.TableName).Rows

xw.WriteStartElement(ds.Tables(dt.TableName).TableName)

For
i As Integer =
0 To ds.Tables(dt.TableName).Columns.Count - 1

xw.WriteElementString(ds.Tables(dt.TableName).Columns(i).ColumnName,
IIf(IsDBNull(dr.Item(i)), String.Empty,
dr.Item(i)))

Next

xw.WriteEndElement()

Next

Next

xw.WriteEndElement()

xw.Flush()

xw.Close()

End Function



End Class

Wednesday, August 8, 2007

Solution of MsgBox in ASP.net



You can't use MessageBox
in ASP.NET. You don't have any graphical user

interface, so there is nowhere that you can display the messagebox.



If you were allowed to use a messagebox in ASP.NET, it would pop up on

the web server where noone would see it, and IIS
would hang indefinitely

waiting for someone to click it.





Remember that this code is running on
the web server in a process that is not running as the currently logged on
(to the server) user. Therefore the process will be running under its own
Window Station, and will not be able to interact with the desktop in any way.
Consequently, you cannot display a MessageBox on the
server without setting the flags to indicate that you want to display it on the
currently logged in user's Window Station (effectively the
default desktop).



Typically, displaying message
boxes on servers is regarded as a very bad thing, as a lot of servers are
locked in computer rooms and there is no user to dismiss them. Therefore, are
you really sure that you want to do this, or would you really prefer to display
a message box on the browser (using client-side JavaScript)?





Here I
am showing another way to display the MsgBox in page.





This
shows an alert on page_load (or else).

No need to create an instance of the class.

Example:


Protected Sub Page_Load(ByVal
sender As Object, ByVal e As System.EventArgs)
Handles Me.Load

cmsgbox.Client_Alert_OnLoad("Hello
world")

End Sub



Note that you won't need to 'format' special characters like \ and " etc..






Public Shared Sub Client_Alert_OnLoad(ByVal sMessage As String,
Optional ByVal sURL As
String = "")

On Error Resume Next

Dim str As String

Dim P As System.Web.UI.Page
= CType(System.Web.HttpContext.Current.Handler,
System.Web.UI.Page)

Dim sb As New StringBuilder(Len(sMessage) * 5)

sMessage = sMessage.Replace(Chr(0),
"")

For Each c As String In sMessage
: sb.Append("\x" & Right("0"
& Hex(Asc(c)), 2)) : Next

str = vbCrLf & "<script language=javascript>"
& vbCrLf

str = str & " alert('" & sb.ToString &amp; "');" & vbCrLf


If Len(sURL) > 0
Then str = str & "
window.location='" & sURL &amp; "';" & vbCrLf


str = str & "</script>" & vbCrLf

P.ClientScript.RegisterStartupScript(P.GetType, "", str)

End Sub















Example:

cmsgbox.Client_Confirm_OnButton(Me.Button1, Chr(34)
& "hello world \/-=" & Chr(34)
& vbCrLf & "ok to format c:?")





Public Shared Sub Client_Confirm_OnButton(ByRef oButton As System.Web.UI.WebControls.Button, ByVal
sMessage As String)

On Error Resume Next

Dim str
As String

Dim sFunction
As String = ("msgbox_confirm_" & oButton.ClientID).Replace("$", "_")

Dim sb
As New StringBuilder(Len(sMessage)
* 5)

sMessage
= sMessage.Replace(Chr(0),
"")

For Each c As String In sMessage : sb.Append("\x"
& Right("0" & Hex(Asc(c)), 2)) :
Next

str
= vbCrLf & "<script language=javascript>" & vbCrLf


str
= str & "" & vbCrLf


str
= str & "function " & sFunction &amp; "()" & vbCrLf


str = str
& " if ( !window.confirm('"
& sb.ToString &amp; "') ) {"

str
= str & " window.event.returnValue
= false;" & vbCrLf

str
= str & " return 0;" & vbCrLf

str
= str & " }" & vbCrLf

str
= str & "}" & vbCrLf


str
= str & "</script>" & vbCrLf

oButton.OnClientClick
= "javascript:" & sFunction
&amp; "();"

oButton.Page.ClientScript.RegisterStartupScript(oButton.Page.GetType, sFunction, str)

End Sub








Thursday, July 26, 2007

Sending E-Mail from your .NET application using your GMail Account

Introduction



Most independent developers like to include a msg sending feature in their application.
Well atleast I tried to.. Of course it is not a problem for a user with a smtp server
access or a registered domain with an smtp server access. But unfortunately I had
none of them. I use msn, gmail and yahoo for my mailing needs. Unfortunately yahoo
does not offer smtp or pop access for their general/basic/free users. And msn it
is not that reliable coz I was expecting a lot of mails to be sent and also to recive
and as far as I know they also donot give you pop/smtp access!.



Typical Example you will find in internet



So I really Hunted for a code segment that help me use my free gmail account to
send E-MAIL from my .NET account. http://www.systemwebmail.com/
is a complete referance library and FAQ's regarding to the System.Web.Mail
namespase. And my code is basically I joined different pieces together. And Came
up with succes. Normally you will find thousands of sites offering the code below
which has a very little use. Like



MailMessage mail = new MailMessage();
mail.To = "xxxx@mailserver.com";
mail.Bcc = "yyyy@mailserver.com; user3@mailserver.net";
mail.From = "your email or name";
mail.Subject = "your subject";
mail.Body = "your subject";
SmtpMail.SmtpServer = "10.4.1.2"; //your
real server goes here or

//you can add the address like "smtp.mailserver.com"
SmtpMail.Send(mail);




Well most smtp server require authentication and sometimes SSL connection so what
then? The code above is USELESS. So what are the things you need
to add? There you go.






//This is fully working tested code. Copy and paste the code
//Edit some parts(UserName, password) and ENJOY!
public string sendMail (string from, string to, string cc, string bcc, string subject, string body) {
// Mail initialization
MailMessage mailMsg = new MailMessage();
mailMsg.From = from;
mailMsg.To = to;
mailMsg.Cc = cc;
mailMsg.Bcc = bcc;
mailMsg.Subject = subject;
mailMsg.BodyFormat = MailFormat.Text;
mailMsg.Body = body;
mailMsg.Priority = MailPriority.High;
// Smtp configuration
SmtpMail.SmtpServer = "smtp.gmail.com";
// - smtp.gmail.com use smtp authentication
mailMsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");
mailMsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", "myemail@gmail.com");
mailMsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", "mypassword");
// - smtp.gmail.com use port 465 or 587
mailMsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", "465");
// - smtp.gmail.com use STARTTLS (some call this SSL)
mailMsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", "true");
// try to send Mail
try
{
SmtpMail.Send(mailMsg);
return "";
}
catch (Exception ex)
{
return ex.Message;
}
}


How to use



Copy the above methods and paste in visual studio IDE or any text editor you use.
Add a referance to System.Web or System.Web.Mail dll change your account
info like your mail address, password, etc and Enjoy



Explanation to the code



So what is happening on the example? See

step 1: Create a mail msg object and asign the basic parts like from, To,
cc, bcc subject, body.

step 2: Add some config settings in fields collection of the mailMessage
object. Type of authentication we use basic authentication and your user name, password,
smtp servers port number that you will be using. for example:



//basic authentication
mailMsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");
//sender email address
mailMsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", "myemail@gmail.com");
//plaintext password.
//you can encrypt your password and keep in a config file
when you parse just decrypt it

mailMsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", "mypassword");
// port number - smtp.gmail.com use port 465 or 587. use anyone
of them

you can even make some grouping so different groups use different port to share
the load on server

mailMsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", "465");

gmail username require full gmail address as username and you can use /connect
to any of the port.


step 3: This is the coolest and most important part that I had a lot of time
to spend to discover.

mailMsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", "true");
//Cool. Ha? Donot Change! This part is a must if you want to
access GMAIL's SMTP server

This line says/declares that your smtp server requires SSL connection which is very
much true/necessary for accessing to gmail's SMTP server.

step 4: assign the smtp server name in System.Web.Mail.SmtpMail class's Smtp
server object like:

SmtpMail.SmtpServer = "smtp.gmail.com";

you can also set the priority of your mail by

mailMsg.Priority = MailPriority.High;// MailPriority is an
enum. It has High,Low, Normal option

step 5: call the send method of System.Web.Mail.SmtpMail. e.g.

System.Web.Mail.SmtpMail.Send(myMailMsg);




.NET2.0 Version



Some Changes are required for .NET v2.0 as .NET2.0 Mail is much organised and stable
and so many extrafeatures. So In the Update I am including .NET2.0 version of my
code.




using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
//Mime is Not necerrary if you dont change the msgview and

//if you dont add custom/extra headers
using System.Threading;

namespace SendMailUsingGmail
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

static bool mailSent = false;

public void SendMail()
{
//Builed The MSG
System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
msg.To.Add("reciver@gmail.com");
msg.To.Add("another.reciver@yahoo.com");
msg.From = new MailAddress("dummy@gmail.com", "One Ghost",System.Text.Encoding.UTF8);
msg.Subject = "Test mail using .net2.0";
msg.SubjectEncoding = System.Text.Encoding.UTF8;
msg.Body = "This is my msg Body";
msg.BodyEncoding = System.Text.Encoding.UTF8;
msg.IsBodyHtml = false;
msg.Priority = MailPriority.High;

//Add the Creddentials
SmtpClient client = new SmtpClient();
client.Credentials = new System.Net.NetworkCredential("dummy@gmail.com", "SecretPass");
client.Port = 587;//or use
587

client.Host = "smtp.gmail.com";
client.EnableSsl = true;
client.SendCompleted += new SendCompletedEventHandler(client_SendCompleted);
object userState=msg;
try
{
//you can also call client.Send(msg)
client.SendAsync(msg, userState);
}
catch (System.Net.Mail.SmtpException ex)
{
MessageBox.Show(ex.Message, "Send Mail Error");
}
}

void client_SendCompleted(object sender, AsyncCompletedEventArgs e)
{
MailMessage mail = (MailMessage)e.UserState;
string subject = mail.Subject;

if (e.Cancelled)
{
string cancelled = string.Format("[{0}] Send canceled.", subject);
MessageBox.Show(cancelled);
}
if (e.Error != null)
{
string error = String.Format("[{0}] {1}", subject, e.Error.ToString());
MessageBox.Show(error);
}
else
{
MessageBox.Show("Message sent.");
}
mailSent = true;
}

private void button1_Click(object sender, EventArgs e)
{
this.SendMail();
}
}
}



Limitation of this code



This code may/will not work with .NET framework v1.0. Because the MailMessage object
of .NETv1.0 does not have the MailMessage.Fields Collection. This was added
in .NETv1.1. So it works fine with .NETv1.1 and v2.0.



conclusion



The send method does not return anything. But you can add some mechanism(like counter)
to keep track of send message or even keep the return type of your method as a mailmessage
type so that u can save to database for security reasons.