Thursday, May 3, 2012

Exporting a GridView To Excel is simple
Well... but it soms come with some complications
If the gridview has TextBoxes or Checkboxes, you would have to take only the value and put it to a literal control, then export.
And while exporting; If you are using the UpdatePanel, it means you cannot have the export button within the panel,
as this works against the response object to create the excel file, you would have to add a postback trigger to the button.


the .aspx
<asp:UpdatePanel runat=server ID=updPnl>
<ContentTemplate>
<table>
<tr><td><asp:ImageButton ID="LinkButtonExcel"  runat="server" ImageUrl="~images/ex.jpg"
        ToolTip="Click to export contents of grid to Excel."
        onclick="LinkButtonExcel_Click" CausesValidation="false"></asp:ImageButton>
</td></tr>
<tr><td>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="True" ></asp:GridView>
<td><tr>

</table>
 </ContentTemplate></UpdatePanel>

the codebehind

.cs
protected void LinkButtonExcel_Click(object sender, ImageClickEventArgs e)
        {
            try
            {
               
GridView1.AllowPaging = false;
                bindRpt(); // this method binds the gridview
                GenerateExcel(
GridView1);
            }
            catch
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "", "alert('Could not Export to excel, please try again later );", true);
            }
        }


public void GenerateExcel(GridView grdSource)
        {

            StringBuilder sbDocBody = new StringBuilder();
            try
            {
                // Declare Styles
                sbDocBody.Append("<style>");
                sbDocBody.Append(".Header {  background-color:Navy; color:#ffffff; font-weight:bold;font-family:Verdana; font-size:12px;}");
                sbDocBody.Append("</style>");
                //
                StringBuilder sbContent = new StringBuilder();

                sbDocBody.Append("<br><table align=\"center\" cellpadding=0 cellspacing=0 border=1>");

                if (grdSource.Rows.Count > 0)
                {
                    for (int i = 0; i < grdSource.Columns.Count - 1; i++)
                    {
                        sbDocBody.Append("<td class=\"Header\" width=\"120\">" + grdSource.Columns[i].HeaderText + "</td>");
                    }
                    sbDocBody.Append("</tr>");
                    // Add Data Rows
                    for (int i = 0; i < grdSource.Rows.Count; i++)
                    {
                        sbDocBody.Append("<tr>");
                        for (int j = 0; j < grdSource.Columns.Count - 1; j++)
                        {
                            if (grdSource.Rows[i].Cells[j].Controls.Count == 0)
                            {
                                sbDocBody.Append("<td class=\"Content\">" + grdSource.Rows[i].Cells[j].Text + "</td>");
                            }
                            else
                            {
                                if (grdSource.Rows[i].Cells[j].Controls[1].ToString() == "System.Web.UI.WebControls.LinkButton")
                                {
                                    LinkButton lnkBtn = (LinkButton)grdSource.Rows[i].Cells[j].Controls[1];
                                    sbDocBody.Append("<td class=\"Content\">" + lnkBtn.Text + "</td>");
                                }
                                else if (grdSource.Rows[i].Cells[j].Controls[1].ToString() == "System.Web.UI.WebControls.Label")
                                {
                                    Label lblData = (Label)grdSource.Rows[i].Cells[j].Controls[1];
                                    sbDocBody.Append("<td class=\"Content\">" + lblData.Text + "</td>");
                                }
                                else
                                if (grdSource.Rows[i].Cells[j].Controls[1].ToString() == "System.Web.UI.WebControls.TextBox")
                                {
                                    TextBox tb = (TextBox)grdSource.Rows[i].Cells[j].Controls[1];
                                    sbDocBody.Append("<td class=\"Content\">" + tb.Text + "</td>");
                                }
                            }
                        }
                        sbDocBody.Append("</tr>");
                    }
                    sbDocBody.Append("</table>");
                 }
                //
                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.Buffer = true;
                //
                HttpContext.Current.Response.AppendHeader("Content-Type", "application/ms-excel");
                HttpContext.Current.Response.AppendHeader("Content-disposition", "attachment; filename=BiasReport-" + DateTime.Now.ToLongDateString() + ".xls");
                HttpContext.Current.Response.Write(sbDocBody.ToString());
                HttpContext.Current.Response.End();
            }
            catch (Exception ex)
            {
                // Ignore
            }
        }

 

Friday, February 17, 2012

Size of a DataTable in a Session

Storing an object in the session for easy access by other pages is the easiest way to move around objects in a web application but
What’s the size of a DataTable stored in a session
I used serialization as shown here http://stackoverflow.com/questions/1689045/can-i-get-the-size-of-a-session-object-in-bytes-in-c
After creating a DataTable with a few columns and 100 rows,
like...
        private DataTable getTable()
        {
            #region make tables         
            //        Add around 10 columns to the table
            #endregion
            for (int i = 0; i < 100; i++)
            {
                dt.Rows.Add(...//add 10 rows
                dt.AcceptChanges();
            }
            return dt;
        }
After putting it to a session I tried calculating the memory using...

protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                long totalSessionBytes;
                BinaryFormatter b = new BinaryFormatter();
                MemoryStream m = new MemoryStream();
                DataTable dt = getTable();
                Session.Add("tab", dt);
                b.Serialize(m, Session["tab"]);
                totalSessionBytes = m.Length;
                Response.Write("Total MB = " + (totalSessionBytes/1000).ToString());

            }
        }


Then It showed 137 MB! And even when Session is replaced with ViewState, it gave the same result. 137! Well… So I saved the binary object to a file Making the DataTable in a constructor of a class, and serializing it...

    [Serializable]
    public class serialtest
    {

        private DataTable dt = new DataTable();


        public serialtest()
        {
            dt = getTable();
        }
     
        private DataTable getTable()
        {
              //the method above
        }
    }


Then making the object and serializing it to a file
private void makefile(serialtest s)
        {
            Stream str = File.OpenWrite("C:\\ serial.txt");
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(str, s);
            str.Close();

        }


The size of the file, it said 240KB I did the same thing with a ViewState and the result was exactly the same So, there is no conclusion as to how you will be able to get the size of the object in a viewstate or a session

Friday, February 10, 2012

RENDER FAILED

This problem usually shows up when the view goes wrong in SharePoint 2007, this problem had shown itself on a list and when the view was modified, it worked
If you google <!-- #RENDER FAILED --> , it gives you a number of solutions but all of them describe the problem for a list in which the view needs to be changes and/or modified
I had this problem in every list and library on every site, and SharePoint was not allowing me to create anything.
Then After checking the content database, I found it had been made read-only , therefore, SharePoint cannot work without write permissions one the content DB (obviously)
after changing this everything was back to normal again.
There were no errors in any of the lists/libraries/workflows

Thursday, October 27, 2011

Xoom apps


I just got the Motorola Xoom and its the coolest piece of technology Ivé held ... until now.
The Xoom runs Android HoneyComb 3.1, and you can watch enormous amount of videos on youtube
Its powered by Nvidia terga2 1Ghz processor, 32 GB space with a resolution of 1280 x 800 pixels.
See the complete specs here

Ivé downloaded some apps, and here goes

Adobe reader ... all the pdfs that I need to read, essential app

Nook for android book reader

Google books is a cool app, but it did not install the free books and when I when to shop for books, (by clicking the link on the top right corner) it said its not there in your area... man! like i'm not in Antarctica!

Wyse PocketCloud RDP This is one useful app, it helps me control my PC, of course youu need the client installed on your PC.

WiFi Finder This simply finds WiFi networks near you. Really cool app

Google Sky Map is another nice app... (if you're wannabe astronomer)

Google earth is there alright, but this hangs on Xoom, so I recommend dont install this yet, I hope there will be an update coming soon.

Google maps .. I had the pre-installed.. and so was Street view

Press Reader Gets what you want .. I mean all the news papers around, it downloads them on demand, and of course, most of the news papers and magazines are paid for log term usage.

Draw Free Is nice bit does not have many brushes or marker options, you can change colors ... thats it.. not much of a freehand draw tool.

Shazam 'Which song is that'. This app is innovative and cool. One downside though... this app is not optimized for the tablet. Yet.

Quick Office Pro For your office apps

NDTV is a news app for India and it comes with a cool widget, too bad it works only vertical.

CNN for android tabletsThis is a really well built app

IMDB Essential for tablets For movie buffs

FlickFolio This is a paid app for flickr fans.

File Manager HD This is a really useful app for those of us used to seeing the windows explorer. And is optimized for HoneyComb.

And note: I recommend not using App Killers (for those of us used to taskmanage) coz' HonayComb is designed for multitasking.

Tablet Keyboard is very useful, it does need a bit of practice to type with you thumbs. There are paid keyboard out there, but this works like a charm.

And here are the games!
Gaming is just awesome on the Xoom
See this youtube video http://www.youtube.com/watch?v=zi7kcknBAf8


Lets start Angry
Angry birds is the most popular and fun game around, anyone who owns (or doesn't own) an Android phone will know. On the Xoom, you can see the whole perspective , angling the shots is easier. There are many many versions of the game available.

Shortyz Crosswords This is for crossword people, it downloads new games from various sources.

Gun Bros If you wanna' see the Terga2 in action this is the game.

Deer Hunter is good looking as well, its paid though.

Fruit Ninja THD This is real fun on the Xoom

Rocket Bunnies This is the most addictive and fun game.

Tic Tac Toe Traditional....I wish there was a multiplayer option.

I bought my Xoom on FlipKart (India) it came in 3 days and they sent a Motorola case with it.
And the Box was way different and better here (in india) that in other places.
I mean
This is what I thought i'd get
this is what I got


I'll have to update the games soon,

Keep Xoomin

Sunday, October 16, 2011

Add tooltip to each item of a DropDown list

You can do a simple DataBind() to bind the DataValue and the DataText fields To populate data into a dropdown list, I thought that binding it with the DropDown1.ToolTip = would do it, yes it does add ToolTip to each item but does not bind a different values.
like I tried to do this on a databind


    private DataTable makeTable()
    {
        DataTable t = new DataTable();
        t.Columns.Add("id");
        t.Columns.Add("display");
        t.Columns.Add("description"); // I thought this would add a tooltip to each item
        t.Rows.Add("1","item1","item1 desc");
        t.Rows.Add("2","item2","item2 desc");
        return t;
    }
    private void bingdd()
    { 
        DataTable t = makeTable();
        DropDownList1.DataValueField = "id";
        DropDownList1.DataTextField = "display";
        DropDownList1.ToolTip = "description";
        DropDownList1.DataSource = t;
        DropDownList1.DataBind();
    }

If you have table where the value, text and description are placed (I just made a datatable), and you want to display the description on mouseover of each item, then use the databound even to add attibutes each item.
The comes in the databound event that will be used to add a 'title' to each item


    private string[] descArray = new string[8];//array to store descriptions

    private void bingdd() //modified bind method
    { 
        DataTable t = makeTable();
        DropDownList1.DataValueField = "id";
        DropDownList1.DataTextField = "display";
       // DropDownList1.ToolTip = "description";
        for (int i = 0; i < t.Rows.Count; i++)
        {
            descArray[i] = t.Rows[i][2].ToString();
        }
        DropDownList1.DataSource = t;
        DropDownList1.DataBind();
    }
    protected void DropDownList1_DataBound(object sender, EventArgs e)
    {
        int i = 0;
        foreach (ListItem l in DropDownList1.Items)
        {
            l.Attributes.Add("title", descArray[i]);
            i++;
        }
    }

Then you get something like

If there is a faster or better way, tell me please

Hope this helps

Sunday, June 5, 2011

InfoPath for the web

There are some constraints while designing InfoPath forms for the web.
First thing is that it does not support views!
If you wanna make a readonly view, then .... not possible ...
But, you can write a rule for every element by sing the username() function to see who has logged in
like
I wanted to disable a textbox when someone login, other than the administrator (the system account)
so, put a textbox on a form , in its properties window click on the fx button

Select username function as shown above and click ok for every window.
Once you have this text box, it can be used to validate every other control on the form
Suppose I have another txtbox called field2, and I need to enable it only if system logs in then,
Double click the textbox to see its properties (for IP 2010, add a new formatting rule)
then ....


In the display tab click conditional formatting to get the window shown above
Then select field1 (or whatever you called the username textbox) then select no equal to in the second and type system in the third, then check read-only.
Click ok for every window.

After publishing this form, you can only find field2 enabled when you login with the system account.

Another thing in web enabled forms is that they don’t allow a section within a section!
That’s one great feature in InfoPath, maybe you won't require it, but what if you want to hide a datepicker that is in a repeating table?
You need to use a section and put the formatting rules in there.
Like: http://www.infopathdev.com/blogs/shiraz/archive/2006/09/08/Hide-a-Date-Picker-Control.aspx
How can you show this web?
please, tell me if you know....

Friday, May 20, 2011

Create an approval workflow In SharePoint designer

 To create a Workflow in SPD 2010 see this video http://office.microsoft.com/en-us/sharepoint-designer-help/video-create-an-approval-workflow-in-sharepoint-designer-2010-VA101897477.aspx

I used the SPD 2007 to create an approval workflow for an InfoPath form library.
It had to work by sending an email and getting the approve or reject status to a form an approver, then send emails to users, notifying them of their status
The only thing was, that the approvers had to be a list of users who would be selected from the InfoPath form .
I started off from here http://www.u2u.info/Blogs/Kevin/Lists/Posts/Post.aspx?ID=39
Thats a cool post that help to start off (and end ) . Thanks Kevin.
here's a nice post too http://cycogeek.fiesta25.com/blogs/cycogeek/page/Create-Custom-Approval-Workflow-with-SharePoint-Designer.aspx
In the step called 'user' (in the above link) I had to choose a variable from the InfoPath form. please refer to my earlier posthttp://saudkhansblog.blogspot.com/2011/05/send-mail-from-infopath.html form sending mail from InfoPath.
After gathering the approver process and other variables, namely- comments and approve
I had to send two mails at once, ie. one to the creator and a cc to the person holiday is requested for.
If it were the same person, then it should send just one email, else should send two mails .
This can be done by adding 3 else if conditions, (and the first if , so totally 4)

like :
if Holiday Approve equals Approve
and if created by equals accountID
then send one mail to created by(approved mail)
else iff Holiday Approve equals Reject
and if created by equals accountID
then send one mail to created by(reject mail)
else if Holiday Approve equals Approve
and if created by not equals accountID
then send mail to created by with cc to accountID (approve mail)
else if Holiday Approve equals Reject
and if created by not equals accountID
then send mail to created by with cc to accountID (reject mail)

not another thing when you send the mail, you send the URL form current items, dont do that
coz if the url has spaces it won't work
Use EncodedUrl instead, this will have the whole correct path to the document.
If you need any help just ask
Thanks