Friday, December 16, 2011

Silverlight Shows the default white color on click of any button: Reason and Solution

Generally we have a problem in Wp7. When we click on any button the default White Color comes in view, Event occur and the button Shows again.
this behaviour is due to pressed visual state of silverlight button controll. So we need to modify this Visual state property to come back from this problem.

For this we will add a template in button and will modify its pressed state property. Follow the following Steps to achive the above:
  1. Create an Application and add a simple button in it by using VisualStudio 2010
  2. Select Required Image on it
  3. Save the file 
  4. Now open this Project in Expression Blend(To Open blend Right-Click on Project in solution explorer--> choose Open In Expression Blend). The project will open in Expression blend.
  5. Now select the Button--> Go to Object Menu--> Select Edit Template--> Select Edit Copy...
  6. A dialogue box (Create Style Resource)  opens
    1. Select Apply to all from Name Key
    2. Select Application from Define In (This option create the Application Resource in App.Xaml file)
    3. Click on OK
  7. Select Button Again then goto States menu on left side or on top (depends where it is present)
  8. Click on pressed state panelin CommenStates
  9. Goto Object and Timeline window--> Select the button from template
  10. Goto Properties window
  11. Open Brushes tab --> Click on the square box of Background property--> New Dialogue box opens Named Background--> Goto Template binding--> select Background
  12. It will show the Your default Image in template button
  13. Save the file.
  14. Now open Visual Studio(Do not close the expression Blend)
  15. In Visual Studio It will ask to save the all updated file outside the VS. Dont worry Click on Yes to all button.
  16. Run Your Application.
   By using this method you didnot need to set any property in button. Just use the button as we do previous.

I put my best to make this example if you got any error in above description. Please inform me with your comment. Your suggestions are always welcome.

Thanks

MaxLength property of a textbox with multiline mode doesn't work. Reason and solution

When a Textbox is in SingleLine mode, it gets rendered as a input type text  and when it is in MultiLine mode, it gets rendered as a textarea. 
As we know MaxLength property works only for input type. Thats why MaxLength property doesn't works with Textbox with multiline property
So We have many custom solution for this.
but the best solution is using
Regular expression validator for this, which will check the count of the entered character and will throw an error if it exceeds. We need to have a regular expression that will work. Let's see the code

<asp:TextBox ID="tb" 
runat="server" 
TextMode="MultiLine" >
</asp:TextBox>
//Regular Expression validator
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" 
runat="server" 
ControlToValidate="tb" 
ErrorMessage="Please enter maximum 10 charachters."
                                SetFocusOnError="true" 
ValidationExpression="^[a-zA-Z.]{0,10}$">
</asp:RegularExpressionValidator>


Note: We have used a regular expression ^[a-zA-Z.]{0,10}$, which allows all the characters with length 0 to 10.

Friday, September 23, 2011

Reading Local XML File in Silverlight







When you want to read variables from an xmlfile in Silverlight, you place that xml file in the same folder as you XAML files so that it will get embedded into your XAP file.
The Silverlight program will always grab the xml file that is within the XAP file, even if you have a local copy. You can't just change the path to point to the local copy.

If you want to read a LOCAL xmlfile instead, you have to download it into the XAP file during runtime.

To read a local copy of xmlfile, and therefore include local changes on that file in your Silverlight program, you have to do two things:

1.

Write a procedure that uses the Webclient, as follows:

void GetLocalXML()

{

WebClient client = new WebClient();

client.DownloadStringCompleted += new ;

DownloadStringCompletedEventHandler(client_DownloadStringCompleted);

Uri url = new Uri(LocalXMLFile, UriKind.Relative);

client.DownloadStringAsync(url); }



The LocalXMLFile is a string variable that holds the path/name of the xml file. You can just directly enter the path/name.

Notice that this procedure calls the next procedure when it finishes the download.



2.

void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)

{

if (e.Error == null)

{

StringReader stream = new StringReader(e.Result);

XmlReader reader = XmlReader.Create(stream);

while (reader.Read())

{
// do your code here

}

reader.Close();

}

}

Wednesday, May 4, 2011

Bind dropdownlist in gridview at run time

add one dropdownlist in templatefield
<asp:TemplateField>
<HeaderTemplate>Emp</HeaderTemplate>
<ItemTemplate ><asp:DropDownList ID="ddlStudent" runat ="server" OnLoad ="ddlStudent_load"></asp:DropDownList></ItemTemplate>
</asp:TemplateField>

Code is:
protected void ddlStudent_load(object sender, EventArgs e)
{
SqlDataAdapter da = new SqlDataAdapter("select sname,sno from student", cn);
DataTable dt = new DataTable();
da.Fill(dt);
DropDownList ddl = (DropDownList)sender;
ddl.DataSource = dt;
ddl.DataTextField = "sname";
ddl.DataValueField = "sno";
ddl.DataBind();

Monday, April 25, 2011

export data from grid to excel

In aspx file(Design view)

<table cellpadding="0px" cellspacing="0px" width="750px">
        <tr>
            <td>
                <h3 style="border-bottom: 2px ridge black;">
                    Detail Report</h3>
            </td>
        </tr>
        <tr>
            <td align="right">
                <asp:Button ID="cmdExport" runat="server" Text="Export" OnClick="cmdExport_Click" />
            </td>
        </tr>
        <tr>
            <td>
                <asp:GridView ID="GridView1" runat="server" Width="750px" CellPadding="4" ForeColor="#333333"
                    GridLines="Vertical" AutoGenerateColumns="false">
                    <RowStyle BackColor="#EFF3FB" />
                    <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                    <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
                    <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
                    <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                    <EditRowStyle BackColor="#2461BF" />
                    <AlternatingRowStyle BackColor="White" />
                    <Columns>
                        <asp:BoundField HeaderText="Reg.No." DataField="id" />
                        <asp:TemplateField HeaderText="ThumbImage">
                            <ItemTemplate>
                                <img src='user/profile_images/<%#Eval("ThumbImage") %>' width="50px" height="50px" alt="" />
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:BoundField HeaderText="Name" DataField="name" />
          
                        <asp:BoundField HeaderText="Address" DataField="address" />
                        <asp:BoundField HeaderText="EmailID" DataField="email_id" />
                    </Columns>
                </asp:GridView>
            </td>
        </tr>
    </table>


In aspx.cs


    protected void Page_Load(object sender, EventArgs e)
    {
SqlConnection conn = new SqlConnection("server=.;database=test;uid=test;pwd=test");
        if (!Page.IsPostBack)
        {
            gridBind();
        }
    }

    void gridBind()
    {
        string sqlquery = "select * from table_name";
        DataSet ds = new DataSet();
        try
        {
            SqlDataAdapter sda = new SqlDataAdapter(sqlquery , conn);
sda.Fill(ds);
            if (ds.Tables[0].Rows.Count > 0)
            {
                GridView1.DataSource = ds;
                GridView1.DataBind();
            }
        }
        catch
        {
        }

    }
    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        gridBind();
    }
    protected void cmdExport_Click(object sender, EventArgs e)
    {
        // Let's hide all unwanted stuffing
        this.GridView1.AllowPaging = false;
        this.GridView1.AllowSorting = false;
        this.GridView1.EditIndex = -1;

        // Let's bind data to GridView
        this.gridBind();
        // Let's output HTML of GridView
        Response.Clear();
        Response.ContentType = "application/vnd.xls";
        Response.AddHeader("content-disposition",
                "attachment;filename=report.xls");

        StringWriter swriter = new StringWriter();
        HtmlTextWriter hwriter = new HtmlTextWriter(swriter);

        HtmlForm frm = new HtmlForm();
        this.GridView1.Parent.Controls.Add(frm);
        frm.Attributes["runat"] = "server";
        frm.Controls.Add(this.GridView1);
        frm.RenderControl(hwriter);

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

Thursday, April 7, 2011

Making a watermark on any image

 ///Locate Image from Image folder.
        System.Drawing.Image objImage = System.Drawing.Image.FromFile(Server.MapPath("photo.jpg"));
        //Taken Actual width anf height From Image
        int height = objImage.Height;//height
        int width = objImage.Width;//Width
        //Create a Bitmap Image
        System.Drawing.Bitmap bitmapimage = new System.Drawing.Bitmap(objImage, width, height);// create bitmap with same size of Actual image
        //Convert in to a Graphics object
        System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmapimage);
        //Creating Brushe
        System.Drawing.SolidBrush brush = new System.Drawing.SolidBrush(System.Drawing.Color.FromArgb(255, 255, 255, 255));
        g.RotateTransform(-90);
        //g.TranslateTransform(150, 0);
        g.DrawString("Astromilan.com", new Font("Arial", 18, System.Drawing.FontStyle.Bold), brush, -230, 50);
        Response.ContentType = "image/jpeg";//setting ContentType
        bitmapimage.Save(Response.OutputStream, ImageFormat.Jpeg);//save image with dynamic watermark

Saturday, March 26, 2011

Rachit's Archive: Export data from Sql to Excel

Rachit's Archive: Export data from Sql to Excel

Export data from Sql to Excel


In Aspx page:

<asp:Button ID="but1" runat="server" OnClick="click_excel" />

In Cs Page:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

public partial class Sqltoexcel : System.Web.UI.Page
{
SqlConnection conn = new SqlConnection("server=.;database=test;uid=test;pwd=test");
DataTable dt = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{

}
protected void click_excel(object sender, EventArgs e)
{
String str = "select * from Emp1";
SqlDataAdapter sda = new SqlDataAdapter(str, conn);
sda.Fill(dt);
exporttosql(dt);
}
public void exporttosql(DataTable dtdata)
{
HttpContext context = HttpContext.Current;
string attach = "attachment;filename=example.xls";
context.Response.ClearContent();
context.Response.AddHeader("content-disposition",attach);
context.Response.ContentType="application/ms-excel";
string sep="";
if(dtdata!=null)
{
foreach(DataColumn dc in dtdata.Columns)
{
context.Response.Write(sep + dc.ColumnName);
sep = "\t";
}
context.Response.Write(System.Environment.NewLine);
foreach (DataRow dr in dtdata.Rows)
{
sep = "";
for(int i=0;i<dtdata.Columns.Count;i++)
{
context.Response.Write(sep + "\"" + dr.ToString() + "\"");
sep = "\t";
}
context.Response.Write(System.Environment.NewLine);
}
context.Response.End();
}
labmesg.Text = "datatransfered";
labmesg.Visible = true;
}
}

Code to logof the system

System.Diagnostics.Process.Start("shutdown", "-l -t 00")

Friday, March 11, 2011

asp menu didn't work properly in google chrome

asp menu do not work properly with google crome and Safari . To solve this problem u can put the following function before the page load function in .cs page. the function is

protected override void AddedControl(Control control, int index)
    {
        if (Request.ServerVariables["http_user_agent"].IndexOf("Safari", StringComparison.CurrentCultureIgnoreCase) != -1)
            this.Page.ClientTarget = "uplevel";

        base.AddedControl(control, index);
    }


Thanks

Friday, March 4, 2011

Use of ajax

Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Default %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <div>
        <table>
            <tr>
                <td style="width:200px;">
                    Username
                </td>
                <td>
                    <asp:TextBox ID="txtUsername" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    Password
                </td>
                <td>
                    <asp:TextBox ID="txtPassword" runat="server" TextMode="Password"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    ConfirmPassword
                </td>
                <td>
                    <asp:TextBox ID="txtConfirmPassword" runat="server" TextMode="Password"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
                        <ContentTemplate>
                            <table>
                                <tr>
                                    <td style="width:200px;">
                                        State
                                    </td>
                                    <td>
                                        <asp:DropDownList ID="ddState" runat="server" AutoPostBack="true"
                                            onselectedindexchanged="ddState_SelectedIndexChanged">
                                        </asp:DropDownList>
                                    </td>
                                </tr>
                                <tr>
                                    <td>
                                        City
                                    </td>
                                    <td>
                                        <asp:DropDownList ID="ddCity" runat="server">
                                        </asp:DropDownList>
                                    </td>
                                </tr>
                            </table>
                        </ContentTemplate>
                    </asp:UpdatePanel>
                </td>
            </tr>
            <tr>
                <td colspan="2" align="right">
                    <asp:Button ID="cmdSubmit" runat="server" Text="Submit" />
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>



Default.aspx.cs(Code Behind page) 

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

          if (!Page.IsPostBack)
        {
            // code to fill the state dropdown list
        }
    }
    protected void ddState_SelectedIndexChanged(object sender, EventArgs e)
    {
        // code to fill the city dropdownlist
    }
}

 

Thursday, February 17, 2011

Change Password


Changepassword.aspx

<table cellpadding="5" cellspacing="5"  >
        <tr>
            <td>UserName</td><td>
                <asp:TextBox ID="txtChangeUserName" runat="server" ReadOnly="true"></asp:TextBox></td>
        </tr>
        <tr>
            <td>New Password</td><td>
                <asp:TextBox ID="txtNewPassword" runat="server" TextMode="password"></asp:TextBox></td>
        </tr>
        <tr>
            <td>Confirm Password</td><td>
                <asp:TextBox ID="txtConfirmNewPassword" runat="server" TextMode="password"></asp:TextBox></td>
        </tr>
        <tr>
            <td colspan="2" align="center">
                <asp:Button ID="cmdChangePassword" runat="server" Text="Change Password" OnClientClick="return checkPassword();" OnClick="cmdChangePassword_Click" />
            </td>
        </tr>
</table>

Changepassword.aspx.cs(Code Behind)

using System.Data.SqlClient;

string sql;
    DataSet ds;
SqlConnection con = new SqlConnection(_ConnectionString);
            con.Open();
            SqlTransaction trans = con.BeginTransaction();
SqlCommand cmd = con.CreateCommand();
            cmd.Transaction = trans;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["did"] != null & Session["user"] != null)
        {

        }
        else
        {
            Response.Redirect("login.aspx");
        }
        lblUserName.Text = Session["user"].ToString();
        sql = "select * from tablename where id= "+Session["did"].ToString();
        try
            {
                cmd.CommandText = sql;                
cmd.ExecuteNonQuery();trans.Commit();
        }
        catch(Exception ex)
        {
           
trans.Rollback();
        }

        if (ds != null & ds.Tables[0].Rows.Count > 0)
        {
            txtChangeUserName.Text = ds.Tables[0].Rows[0][1].ToString();
        }
    }

    protected void cmdChangePassword_Click(object sender, EventArgs e)
    {
        sql = "update tablename set password = '" + txtNewPassword.Text.Trim() + "' where Id=" + Session["did"].ToString();
        try
            {
                cmd.CommandText = sql;
                cmd.ExecuteNonQuery();
            lblMsg.Text = "Password Change successfully.";
  trans.Commit();
            }
            catch (Exception ex)
            {
                trans.Rollback();

            }
        }

Forget Password


Forgetpassword.aspx

<table border="0" style=" background-color:#FAFFF8; font-family:Arial; font-size:12px" width="100%" cellspacing="5px">
        <tr>
            <td style="height: 20px; text-align:left;">
                <b>Forgot Password</b>
            </td>
        </tr>
        <tr>
            <td style="height: 20px;">
                <asp:Panel ID="pnlinfo" runat="server" class="pnlinfo">
                  <asp:Label ID="lblinfo" runat="server"></asp:Label>
                  </asp:Panel>
                </td>
        </tr>
       <tr><td>Just enter the Email-ID with which you registered on ballgrinder.com and click Submit. Your password will be sent to the email address entered below. Please do enter the email address associated with your account.</td></tr>
       <tr><td>
           <asp:TextBox ID="txtmailid" runat="server" style="width:300px"
               CausesValidation="True"></asp:TextBox>
           <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"  ValidationGroup="a"
               ControlToValidate="txtmailid" ErrorMessage="Please Enter your email id"></asp:RequiredFieldValidator>
           <cc1:ValidatorCalloutExtender ID="ValidatorCalloutExtender1" runat="server" TargetControlID="RequiredFieldValidator1" >
           </cc1:ValidatorCalloutExtender>
       </td></tr>
       <tr><td>
        
           </td></tr>
       <tr><td>
           <asp:Button ID="Button1" runat="server" Text="Submit" onclick="Button1_Click" ValidationGroup="a"/>
           </td></tr>
    </table>


Forgetpassword.aspx.cs

protected void Button1_Click(object sender, EventArgs e)
    {
        getpassword();
    }
    public void getpassword()
    {
        string str = "select username,password from tablename where username='"+txtmailid.Text+"' or email='"+txtmailid.Text+"'";
        SqlConnection con = new SqlConnection(_ConnectionString);
            con.Open();
            SqlTransaction trans = con.BeginTransaction();

SqlCommand cmd = con.CreateCommand();
            cmd.Transaction = trans; 
        try
        {
            cmd.CommandText = str;
                 DataSet ds = new DataSet();
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(ds);
            if (ds.Tables[0].Rows.Count > 0)
            {
                string username = ds.Tables[0].Rows[0][0].ToString();
                string password = ds.Tables[0].Rows[0][1].ToString();
                sendMailNow(username, password, txtmailid.Text);

                pnlinfo.Visible = true;
                pnlinfo.BackColor = System.Drawing.ColorTranslator.FromHtml("#EEF4FC");
                pnlinfo.BorderColor = System.Drawing.ColorTranslator.FromHtml("#7FB0E0");
                pnlinfo.BorderWidth = 1;
                lblinfo.Text = "Your Password has been sucessfully sent to your email address.";
                txtmailid.Text = "";
            }
            else
            {
                pnlinfo.Visible = true;
                pnlinfo.BackColor = System.Drawing.ColorTranslator.FromHtml("#FFDDDD");
                pnlinfo.BorderColor = System.Drawing.ColorTranslator.FromHtml("#F26060");
                pnlinfo.BorderWidth = 1;
                lblinfo.Text = "You need to create a new account.";
            }
 trans.Commit();
        }
        catch (Exception ex)
        {
           
trans.Rollback();
        }
    }
    public void sendMailNow(string username, string password, string email)
    {
       
            // Code to send mail

        }

Total Pageviews