Thursday 30 August 2012

Delete button in list view Webpart in sharepoint 2010



Delete button in list view Webpart in sharepoint 2010

Hi, we all know that list view is the best way to show the data to use without wasting of time.



Recently we got requirement that client needs delete button link in SharePoint list view
Now edit button is available but delete button is not available in default view.

So finally we are went the same way as we always used: change the Listview HTML in JavaScript




We created a text field “Delete” and put some below text inside that field
<div><a href='#' onclick='javascript:DeleteItem(2);'><img alt='delete' src='/_layouts/images/delitem.gif' style='border:0px;' /></a></div>
where 2 will be listitem ID
Note: calculated column is not supporting ID. So we can use event handler or SPDesigner workflow to fill this field.
//Or You can try this

Just Break the webpart in XSLT
ADD the ID field into the webpart,Select the ID(Heading like End time,Comment in my picture) Div and delete it then just select any id like 1 ,2  etc.
Example :













See the image and replace the selected text with this below text , then save.



<xsl:variable name="LstId" select="$thisNode/@*[name()=current()/@Name]"/>
    <a href="#" onclick="javascript:DeleteItem('{$LstId}');"><img alt='delete' src='/_layouts/images/delitem.gif' style='border:0px;' /></a>


after this check one thing the "ddwrt:ghost" property ( should be blank )  like  ddwrt:ghost="" otherwise it will not  be updated .


<xsl:template name="FieldRef_body.ID" ddwrt:dvt_mode="body" match="FieldRef[@Name='ID']" mode="body" ddwrt:ghost="">
    <xsl:param name="thisNode" select="."/>


<xsl:variable name="LstId" select="$thisNode/@*[name()=current()/@Name]"/>
     <a href="#" onclick="javascript:DeleteItem('{$LstId}');"><img alt='delete' src='/_layouts/images/delitem.gif' style='border:0px;' /></a>
</xsl:template>




Now what we had done is on DeleteItem function we called web service from JavaScript using SPServices jQuery and delete the item and then just reload the thepage.

That’s it
Here is the function which called on page load to change text field to div field.

we have to put this JavaScript on the same page of list view.


$(document).ready(function(){
$(".ms-vb2:contains('<div')").each(function(){
var tempDIV = document.createElement ("div");
tempDIV.style.cursor = "pointer";
tempDIV.innerHTML = $(this).text();
$(this).text("");
$(this).append(tempDIV);

});
});

function DeleteItem(cID)
{try{
var cnf = confirm("Are you sure you want to send the item(s) to the site Recycle Bin?");
//this is default message that sharepoint gives.
if(cnf)
{
$().SPServices({
operation: 'UpdateListItems',
listName: ‘your list name’,
batchCmd: 'Delete',
ID: cID,
completefunc: function (xData, Status) {
location.reload(true)
}
});
}


}catch(ex){alert(ex);} }</script>


Hope fully you will get the idea how its working.





Please follow the full  blog :Here

Inline Code in Sharepoint 2010

Change the web config accordingly :
find <PageParserPaths></PageParserPaths> block in web.config file and replace with


<PageParserPaths>
         <PageParserPath VirtualPath="/*" CompilationMode="Always" 
         AllowServerSideScript="true" IncludeSubFolders="true"/>
      </PageParserPaths>


Thursday 23 August 2012

How to get choice field data from sharepoint list and add it to dropdown list


Add SharePoint list choice field data to dropdown



SPSite oSite = new SPSite(url);
     SPWeb myWeb = oSite.OpenWeb();
    SPFieldChoice myField = (SPFieldChoice)myWeb.Lists["List Name"].Fields["Task"];
    DataTable dataTasks = new DataTable();
    DataColumn[] dtCols = new DataColumn[] { new DataColumn("Task", Type.GetType("System.String")) };
    dataTasks.Columns.AddRange(dtCols);
    for (int i = 0; i < myField.Choices.Count; i++)
     {
        DataRow dRow = dataTasks.NewRow();
        dataTasks.Rows.Add(Convert.ToString(myField.Choices[i]));
     }
    this.DrpTask.DataSource = dataTasks;
    this.DrpTask.DataValueField = Convert.ToString(dataTasks.Columns["Task"]);
     this.DrpTask.DataTextField = Convert.ToString(dataTasks.Columns["Task"]);
    this.DrpTask.DataBind();
     this.DrpTask.Items.Insert(0, "All");

Thursday 16 August 2012

Write exception to log file in C#

Add system.IO namespace
then write the following code
Create a text file named as "MyText.txt" in a location where the user having write access.( on which credential you are running the application.)

  FileStream fs = new FileStream("D:\\MyText.txt", FileMode.Append, FileAccess.Write);
                            StreamWriter sw = new StreamWriter(fs);
                            sw.WriteLine("Exception ="+"    "+ex.Message);
                            sw.Close();
                            fs.Close();

Thursday 9 August 2012

Add Scrollbars to Quick Launch


Add Scrollbars to Quick Launch


Note: If you just want to tighten up the Quick Launch area then see this article:http://techtrainingnotes.blogspot.com/2011/10/sharepoint-2010-365-tighten-up-quick.html
When you scroll down in a SharePoint page to find what's at the end of the Quick Launch area you also scroll the top navigation area out of site. This area has the site title, top link bar, search and the Tags and Notes buttons. To be able to browse the Quick Launch area without scrolling the entire page add this CSS to your master page:
.ms-quicklaunch-navmgr
{
    overflow-y:scroll;
    height:200px;
}
You will need to carefully select the height property and/or write some JavaScript to set the height based on the user's browser settings.
    image
If you want to scroll the entire left navigation area then use this CSS:
#s4-leftpanel-content
{
    overflow-y:scroll;
    height:300px;
}
    image
Setting the height of this area gives you a little bonus of adding text or links just below the navigation area. Search for "MSO_ContentTable" in your master page and place your content between the two "</div>" tags above this line. (This example is for the standard v4.master page. Yours may be different.)
    image




Reference:
http://techtrainingnotes.blogspot.in/2012/06/sharepoint-2010fun-with-scrollbars.html

Modal dialog in Sharepoint 2010

Modal dialog in SharePoint 2010


Open modal dialog in Sharepoint 2010
<script type="text/javascript">
 
    function DialogCallback(dialogResult, returnValue) {
        //SP.UI.ModalDialog.RefreshPage(SP.UI.DialogResult.OK);
        window.location.href = window.location.href;
    }  
    function OpenWebPage() {
        var options = {
            url: "/Lists/test/NewForm.aspx",
            height:600,
            width:400,         
            dialogReturnValueCallback: DialogCallback
        };
        SP.UI.ModalDialog.showModalDialog(options);
    }
    </script>
just add the function name to open the modal dialog like 
<a class="ms-addnew" onclick="javascript:OpenWebPage(); return false;" href="/Lists/test/NewForm.aspx">
Add new item</a>
if you want to refresh your page after the modal dialog ok button press the just on-comment the second line and comment the line next to it i'e  " window.location.href ....".



Following are the list of options you can put as dialog options.









































































Property

Data type

Default value

Description

allowMaximise

boolean

true

Determines whether the maximise button is present on the rendered dialog.

args

object

We’ll examine this property in more detail later. The args property allows us to pass arbitrary properties into our dialog.

autoSize

boolean (true/false)

true

Determines whether the dialog should be automatically sized to fit within the parent browser window. Where a value has been set for width or height, this value is deemed to be false regardless of the actual setting.

dialogReturnValueCallback

function

We’ll examine this property in more detail. By passing a function, we can specify a section of script to be executed when the dialog is closed.

height

numeric

The height of the dialog to be displayed. If this value is not set the dialog is automatically sized to fit the window.

html

string

Where a Url is passed, an IFRAME tag is rendered pointing to the appropriate Url. AS an alternative to this, it is possible to pass arbitrary HTML instead, in which case, rather than an IFRAME tag, the arbitrary HTML is rendered instead.

showClose

boolean (true/false)

true

Determines whether the close button is visible in the titlebar of the dialog.

showMaximized

boolean
(true/false)

false

Dictates whether the rendered dialog should fill the available space in the parent window.

title

string

Specifies the title of the dialog. Where no title is specified, the title of the document referred to by the Url property is used instead.

url

string

null

The url of the page to be shown in the dialog. Where a url is set and IFRAME tag will be rendered by the Dialog framework and the src of the IFRAME will be set to this url.

width

numeric

The width of the dialog to be displayed. If this value is not set the dialog is automatically sized to fit the window.

x

numeric

Specifies the starting position of the rendered dialog. If this value is not set the dialog is shown in the middle of the viewing area. This value represents the offset from the left edge of the parent browser window.

y

numeric

Specifies the starting position of the rendered dialog. If this value is not set the dialog is shown in the middle of the viewing area. This value represents the offset from the bottom of the parent browser window.

Wednesday 8 August 2012

Asp.net Chart using C#


How to Create Asp.net Chart using C# ?

Find below code for the chart



















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;
using System.Drawing;
using System.Drawing.Imaging;

public partial class Chart : System.Web.UI.Page
{
    public Bitmap myImage;
    public Graphics g;
    public double[] p;
    public string[] GLabel;
    public Brush[] myBrushes;
    public int Gwidth;
    protected void Page_Load(object sender, EventArgs e)
    {
        setvalues();//Set the default values for chart
        g.Clear(Color.WhiteSmoke);
        drawBarcharts(g);
        myImage.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
    }
    public void setvalues()
    {
        int size = 2;

        DefineArrays(size);

        p[0] = 100;
        p[1] = 200;
        //p[2] = 16.40;
        //p[3] = 15.29;
        //p[4] = 12.12;
        //p[5] = 17.21;

        GLabel[0] = "Estimate Hour";
        GLabel[1] = "Worked Hour";
        //GLabel[2] = "C";
        //GLabel[3] = "D";
        //GLabel[4] = "E";
        //GLabel[5] = "F";


        initialiseGraphics(size);

    }

    public void DefineArrays(int size)
    {
        p = new double[size];
        GLabel = new string[size];
        myBrushes = new Brush[20];

    }

    private void initialiseGraphics(int size)
    {
        try
        {
            // Create an in-memory bitmap where you will draw the image.
            // The Bitmap is 300 pixels wide and 200 pixels high.

            Gwidth = size * 155;
            myImage = new Bitmap(Gwidth, 300, PixelFormat.Format32bppRgb);
            //myImage=new Bitmap(


            // Get the graphics context for the bitmap.
            g = Graphics.FromImage(myImage);

            //   Create the brushes for drawing
            createBrushes();
        }
        catch (Exception ex)
        {
            throw ex;
        }

    }
    public void createBrushes()
    {
        try
        {
            //Method to create brushes of specific colours

            myBrushes[0] = new SolidBrush(Color.Red);
            myBrushes[1] = new SolidBrush(Color.Blue);
            myBrushes[2] = new SolidBrush(Color.Yellow);
            myBrushes[3] = new SolidBrush(Color.Green);
            myBrushes[4] = new SolidBrush(Color.Tan);
            myBrushes[5] = new SolidBrush(Color.SkyBlue);
            myBrushes[6] = new SolidBrush(Color.Orange);
            myBrushes[7] = new SolidBrush(Color.PaleGreen);
            myBrushes[8] = new SolidBrush(Color.Silver);
            myBrushes[9] = new SolidBrush(Color.SeaGreen);
            myBrushes[10] = new SolidBrush(Color.White);
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    public void drawBarcharts(Graphics g)
    {
        try
        {
            int i;
            int xInterval = 40;
            int width = 30;
            int height = 0;
            double total = 0.0;
            double percentage;
            SolidBrush blackBrush = new SolidBrush(Color.Black);



            //mine
            System.Drawing.Bitmap objBitMap = new System.Drawing.Bitmap(400, 250);
            System.Drawing.Graphics objGraphics;
            objGraphics = System.Drawing.Graphics.FromImage(objBitMap);
            objGraphics.Clear(System.Drawing.Color.Silver);
            System.Drawing.PointF symbolLeg = new System.Drawing.PointF(250, 25);
            //System.Drawing.PointF descLeg = new System.Drawing.PointF(310, 21);
            System.Drawing.PointF descLeg = new System.Drawing.PointF(130, 21);
         
            //
            for (i = 0; i < p.Length; i++)
            {
                total = total + p[i];
            }
            for (i = 0; i < p.Length; i++)
            {
               
                //mine

                //string color = myBrushes[i];
                //System.Drawing.ColorConverter colConvert = new System.Drawing.ColorConverter();
                //System.Drawing.Color objColor;
                //objColor = (System.Drawing.Color)colConvert.ConvertFromString(color);
                g.FillRectangle(myBrushes[i], symbolLeg.X, symbolLeg.Y, 20, 10);
                g.DrawRectangle(System.Drawing.Pens.Black, symbolLeg.X, symbolLeg.Y, 20, 10);
               // g.DrawString(GLabel[i], new System.Drawing.Font("Tahoma", 10), System.Drawing.Brushes.Black, descLeg);
                g.DrawString(GLabel[i], new Font("Verdana", 8, FontStyle.Bold), Brushes.Black, descLeg);
                //




                percentage = double.Parse(p[i].ToString()) / double.Parse(total.ToString()) * 100;
                height = Convert.ToInt32(percentage * 2);

                g.FillRectangle(myBrushes[i], xInterval * i + 50, 280 - height, width, height);

                //label the barcharts
             
                //g.DrawString(GLabel[i], new Font("Verdana", 8, FontStyle.Bold), Brushes.Black, xInterval * i + 50 + (width / 3), 280 - height - 25);
                // Draw the scale
                 g.DrawString(p[i].ToString(), new Font("Verdana", 5, FontStyle.Bold), Brushes.Black, 0, 280 - height);
               

                //Draw the axes
                g.DrawLine(Pens.Brown, 40, 10, 40, 290);        //y-axis
                g.DrawLine(Pens.Brown, 20, 280, Gwidth, 280);        //x-axis
                //mine
                symbolLeg.Y += 20;
                descLeg.Y += 20;
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

}