Search This Blog

Friday, July 30, 2010

Standard out-of-the-box workflows in WSS 3.0 and Office SharePoint Server 2007

Workflows in Windows SharePoint Services (WSS) 3.0

Windows SharePoint Services (WSS) 3.0 comes with only one workflow template out-of-the-box (OOTB):
  • Three-state workflow

Three-state workflow

The Three-state workflow is a simple issue tracking workflow that shows the status of active and resolved issues. You can use this workflow to move a document along one or 3 states, for example a Pending, Approved, and Rejected state.
The Three-state workflow works with an Issue Tracking list or any other list that has a Choice column with 3 values.

Workflows in Microsoft Office SharePoint Server 2007

Microsoft Office SharePoint Server 2007 comes with the following workflow templates out-of-the-box (OOTB):
  • Approval workflow
  • Collect Feedback workflow
  • Collect Signatures workflow
  • Disposition Approval workflow
  • Group Approval workflow (available only in some languages)
  • Translation Management workflow

Approval workflow

The Approval workflow routes a document for approval. You can set up this workflow to be serial or parallel, and preset the approvers.
The Approval workflow is typically used to send out a document to people who need to approve the document, often as a prerequisites to publishing the document.
The document can be sent to:
  1. People one by one after each other ( = serial), or 
  2. Everyone at the same time ( = parallel)

Collect Feedback workflow

The Collect Feedback workflow routes a document for feedback. When the workflow completes all the feedback is aggregated and sent to the originator of the workflow.

Collect Signatures workflow

Rather than just sending a document for approval, the Collect Signatures workflow requires digital signatures on the document. This workflow requires Office 2007 and can only be initiated from an Office 2007 client application.

Disposition Approval workflow

The Disposition Approval workflow works with the records management capabilities and Records Center in SharePoint. It allows you to manage document expiration and retention.
You can use the Disposition Approval workflow to make decisions as to what you want to do with documents after they expire; not just delete the documents, but for example, archive documents, send out notifications, etc.

Group Approval workflow (East Asian Document Approval)

The Group Approval workflow routes a document for approval using stamp signatures and a group-oriented consensus process. It is only available for East Asian cultures.
To support hierarchical approvals, this workflow uses a hierarchical control to select the approvers and stamping rather than signatures for approval.

Translation Management workflow

The Translation Management workflow is used with the Web content management features of SharePoint to support a translation workflow for content to multiple languages.

Monday, July 19, 2010

Get Distinct values from a Columns in Datatable

DataTable dtcols = ds.Tables[0].DefaultView.ToTable(true, "Type");

Using above statemnt you will distinct types from the datatable ..here type is one of the column in datatable

Convert Data table columns to Arrary

DataSet ds = objSummary.BindDataSet("xxxxxxxxxxxxxxxxxx", dts, strUserid);

        DataTable dt = ds.Tables[0];
        string strTitle = ds.Tables[1].Rows[0]["ABBR"].ToString().Trim();
        //dt.DefaultView.Sort = "PLAN  DESC";
        // DataView dv = dt.DefaultView;
        // dv.Sort = "PLAN  DESC";


        string[] legends = Array.ConvertAll(dt.Select(), delegate(DataRow row) { return (String)row["LOSSREASON"].ToString().Trim(); });

        string[] xValues = Array.ConvertAll(dt.Select(), delegate(DataRow row) { return (String)row["REVENUE"].ToString().Trim(); });

Friday, July 16, 2010

Create a custom site theme and make it available to others

1 - Identify a theme that closely resembles the theme you want to create

The first step is to first take a look at the existing themes available in SharePoint and determine if one of those themes closely resembles the theme that you want to create.
  1. Go to the SharePoint site where you want to create the theme (log on, if necessary).
  2. Click the Site Actions menu and choose Site Settings.
  3. Under Look and Feel, click Site theme.
  4. Look through the themes until you find one that closely resembles the theme you want to create. Note the name of the theme so you can find the files you need for later steps.
  5. For this example, I know that I want to use the Classic theme.
  6. Cancel out of the Site Theme page.
2- Create your custom theme folder
  1. Log onto the server that hosts your SharePoint site and browse to the following folder:
    C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\THEMES
  2. Copy the folder that corresponds with our theme. In my case, I copied the Classic folder.
  3. Paste this into this same THEMES folder, so that you end up with a Copy of THEMENAME folder. In my case, I ended up with a Copy of CLASSIC folder.
  4. Rename this folder to MyCustomTheme.
3 - Modify the theme setup information file (INF)
  1. Open the MyCustomTheme folder and locate the name of the theme you chose as a starting point for your new theme. For example, CLASSIC.INF.
  2. Rename CLASSIC.INF (or the INF file for the theme you chose) to MYCUSTOMTHEME.INF (yes, please use upper case).
  3. Edit MYCUSTOMTHEME.INF in Notepad (or your preferred text editor).
  4. Perform a search and replace in this file, replacing every instance of Classic (or the theme you chose) with MyCustomTheme.
  5. Save and close MYCUSTOMTHEME.INF.
4 - Modify the SPTHEMES.XML file
  1. Browse to the following folder:
    C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS\1033
  2. Locate SPTHEMES.XML.
  3. Edit SPTHEMES.XML in Notepad (or your preferred text editor).
  4. Add the following text after the tag so that it matches the other templates in this file:

     MyCustomTheme
     My Custom Theme
     My Custom Theme.
     images/mycustomtheme.gif
     images/mycustomtheme.gif
  5. Save and close SPTHEMES.XML.
  6. Reset the server so that your theme shows up on the Site Theme page in SharePoint. You can reset the server by entering the following text in the Start > RUN line:
    iisreset computer name
    (where computer name is the name of the server)
5 - Apply your custom theme to your site
  1. Return to your SharePoint site.
  2. Click the Site Actions menu and choose Site Settings.
  3. Under Look and Feel, click Site theme.
  4. In the list of themes, select My Custom Theme.
  5. Click Apply.
    Your site will look no different from the Classic theme since we based your custom theme on it. The next step is to customize this theme.
6 - Customize your theme in SharePoint Designer
  1. Launch SharePoint Designer 2007.
  2. Click File > Open Site.
  3. Specify the site in the Site name field, for example http: //sitename/TeamSite, and click Open.
  4. In the Folder List pane, open the _themes folder and then our custom theme folder, MyCustomTheme.
  5. To customize the look and feel, the colors, and the layout of elements, open the cascading style sheet associated with this theme, MyCu1011-65001.css. (This file was created when you applied your custom theme to your site. It overwrites the site collection’s core.css by loading after that file when the page is viewed. The name of this file is always the first four characters of your custom theme name followed by 1011-65001.css.)
    Tip: Working with style sheets on a SharePoint site can be tricky because there are so many elements to work with. I recommend taking a look at the article Cascading Style Sheets Class Definitions on MSDN and definitely Heather Solomon's CSS Reference Chart for SharePoint for a description of these. Then take a look at the article Modify a style on Office Online.
  6. When finished, save the MyCu1011-65001.css file.
  7. To change the images associated with the theme, open the desired .jpg or.gif files in this same folder. For this example, I modified the siteTitleBKGD_classic.jpg image. This image displays in the upper right corner of the page. I changed it from a yellow gradient to a gray gradient.
  8. To see the changes, you can preview your site in SharePoint Designer or log onto your site directly and take a look.
  9. If you’re finished making changes, this is probably a good time to take a screen capture of your web site and save the image with the filename mycustomtheme.gif to your desktop, for example. We’ll use this image later on to serve as the preview and thumbnail of the custom theme.
    Tip: For best results, save this image with the dimensions 375 x 231 as this is what it will preview as on the Site Theme page in SharePoint.
7 - Apply your changes to the custom theme on the server
You might be wondering why these final steps are necessary since you already customized and saved your theme. Well, actually the theme folder in SharePoint Designer is a copy of the original theme on the server (C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\THEMES\MYCUSTOMTHEME).
So, if you or someone else in your organization applies this theme to your site or to another site, it will read from the original theme on the server and not the copy you’re working with. Your changes will appear to have been lost!
For this reason, the last step is to copy your customized theme files to the theme folder on the server.
  1. In SharePoint Designer 2007, copy the contents of the MyCu1011-65001.css file, if you made changes to it.
  2. Log on to the server and browse to the following folder:
    C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\THEMES\MYTHEME
  3. Open the theme.css file in a text editor, like Notepad.
  4. Paste the contents copied from MyCu1011-65001.css into this file, overwriting all of its contents.
  5. Since in my example, I also updated an image in this theme, I copied the file siteTitleBKGD_classic.jpg to this folder as well, overwriting the original.
  6. One last file! Remember the mycustomtheme.gif image we created, the screenshot of our theme? This needs to be copied to the following folder so that it appears as a preview and thumbnail for the theme:
    C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\IMAGES
  7. Reset the server so that the theme becomes permanently available on the Site Theme page. Again, you can reset the server by entering the following text in the Start > RUN line:
    iisreset computer name
    (where computer name is the name of the server)
  8. Return to your site and test your new theme by reapplying it or by applying it to another site!
As a result of these steps, you and others in your organization can now choose the My Custom Theme on the Site Theme page in SharePoint.

Reading .Evt Files in c#

using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.IO;
using System.Runtime;
using System.Runtime.InteropServices;
using System.Collections;
using System.Diagnostics;

namespace EventLogParser
{
    // Show the progress
    public delegate void ProgressHandler(int val, int max);
    // Send any message to UI
    public delegate void MessageHandler(string msg);
    // Parsed a new event.
    public delegate void NewEventFoundHandler(object[] items);

  public  class EventLogParser
    {
        //Constants for api call
        const int NO_ERROR = 0;
        const int ERROR_INSUFFICIENT_BUFFER = 122;

        public event ProgressHandler OnProgress;
        public event MessageHandler OnAction;
        public event NewEventFoundHandler OnFoundRecord;

        uint offset;

        enum SID_NAME_USE
        {
            SidTypeUser = 1,
            SidTypeGroup,
            SidTypeDomain,
            SidTypeAlias,
            SidTypeWellKnownGroup,
            SidTypeDeletedAccount,
            SidTypeInvalid,
            SidTypeUnknown,
            SidTypeComputer
        }

        [StructLayout(LayoutKind.Sequential, Pack = 1)]
        public unsafe struct EventLogHeader
        {
            public uint HeaderLength; // length
            public uint Signature; // signature
            public uint Unknown1;
            public uint Unknown2;
            public uint Unknown3;
            public uint FooterOffset;
            public uint NextIndex;
            public uint FileLength; // always wont give correct value
            public uint Unknown6;
            public uint Unknown7;
            public uint Unknown8;
            public uint EndHeaderLength;

            public EventLogHeader(byte[] data)
            {
                fixed (byte* pData = data)
                {
                    this = *(EventLogHeader*)pData;
                }
            }
        }

        [StructLayout(LayoutKind.Sequential, Pack = 1)]
        public unsafe struct EventLogFooter
        {
            public uint FooterLength; // length
            public uint Unknown0; // 0x11111111
            public uint Unknown1; // 0x22222222
            public uint Unknown2; // 0x33333333
            public uint Unknown3; // 0x44444444
            public uint Unknown4;
            public uint FooterOffset;
            public uint NextIndex;
            public uint Unknown7;
            public uint EndFooterLength;

            public EventLogFooter(byte[] data)
            {
                fixed (byte* pData = data)
                {
                    this = *(EventLogFooter*)pData;
                }
            }
        }

        [StructLayout(LayoutKind.Sequential, Pack = 1)]
        public unsafe struct EventLogRecord
        {
            public uint Length;
            public uint Reserved;
            public uint RecordNumber;
            public uint TimeGenerated;
            public uint TimeWritten;
            public uint EventID;

            public ushort EventType;
            public ushort NumStrings;
            public ushort EventCategory;
            public ushort ReservedFlags;
            public uint ClosingRecordNumber;
            public uint StringOffset;
            public uint UserSidLength;
            public uint UserSidOffset;
            public uint DataLength;
            public uint DataOffset;

            public EventLogRecord(byte[] data)
            {
                fixed (byte* pData = data)
                {
                    this = *(EventLogRecord*)pData;
                }
            }

        }

        [StructLayout(LayoutKind.Sequential)]
        private struct SystemTime
        {
            public short year;
            public short month;
            public short dayOfWeek;
            public short day;
            public short hour;
            public short minute;
            public short second;
            public short milliseconds;
        }

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
        private struct TimeZoneInformation
        {
            public int bias;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
            public string standardName;
            public SystemTime standardDate;
            public int standardBias;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
            public string daylightName;
            public SystemTime daylightDate;
            public int daylightBias;
        }

        // Class for holding an event log entry
        public class EventLogEntry
        {
            public EventLogRecord rec;
            public string SourceName;
            public string Computername;
            public string UserSid;
            public string Strings;
            public byte[] Data;
        }

        [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        static extern bool LookupAccountSid(
            string lpSystemName,
            [MarshalAs(UnmanagedType.LPArray)] byte[] Sid,
            System.Text.StringBuilder lpName,
            ref uint cchName,
            System.Text.StringBuilder ReferencedDomainName,
            ref uint cchReferencedDomainName,
            out SID_NAME_USE peUse);

        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        private static extern int GetTimeZoneInformation(out TimeZoneInformation lpTimeZoneInformation);

        // Ctor
        public EventLogParser()
        {
            TimeZoneInformation tzi;
            GetTimeZoneInformation(out tzi);
            offset = (uint)(tzi.bias * 60) - (uint)(tzi.daylightBias * 60);
        }

        // Parse the file
        public unsafe void Parse(string filename)
        {
            try
            {
                // Open the file
                using (FileStream fs = new FileStream(filename, FileMode.Open))
                {
                    // Use BinaryReader to read the file
                    using (BinaryReader br = new BinaryReader(fs))
                    {
                        //Read the header of the file
                        byte[] header = new byte[sizeof(EventLogHeader)];
                        br.Read(header, 0, header.Length);
                        EventLogHeader _h = new EventLogHeader(header);
                        // Validate the file
                        if (!Validate(_h))
                        {
                            this.OnAction("Invalid file format.");
                            return;
                        }
                        //
                        int totalEvents = (int)(_h.NextIndex - 1);
                        this.OnAction(String.Format("Found {0} events", totalEvents));
                        // Read the items
                        EventLogEntry e;
                        int cnt = 0;
                        uint offset = _h.FooterOffset;
                        while (true)
                        {
                            byte[] buff = ReadEntry(br, ref offset);
                            e = ReadEntry(buff);
                            cnt++;
                            DateTime dt = GetTime(e.rec.TimeGenerated);
                            this.OnFoundRecord(
                                new object[] {
                                    Enum.GetName(typeof(EventLogEntryType),e.rec.EventType),
                                    dt.ToShortDateString(),
                                    dt.ToShortTimeString(),
                                    e.SourceName,
                                    e.Strings,
                                    e.rec.EventCategory,
                                    e.rec.EventID,
                                    e.UserSid,
                                    e.Computername});
                            if (cnt % 200 == 0) this.OnProgress(cnt, totalEvents);
                            if (offset == 48)
                                break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                this.OnAction(String.Format("Error Occured! {0}", ex.Message));
            }
            return;
        }

        // Read an event log record as byte[] from the file.
        private byte[] ReadEntry(BinaryReader br, ref uint endPoint)
        {
            br.BaseStream.Seek(endPoint - 4, SeekOrigin.Begin);
            uint length = br.ReadUInt32();
            endPoint -= length;
            br.BaseStream.Seek(endPoint, SeekOrigin.Begin);
            byte[] buff = new byte[length];
            br.Read(buff, 0, buff.Length);
            return buff;
        }

        // Parse the byte[] as an event log record
        private unsafe EventLogEntry ReadEntry(byte[] buff)
        {
            EventLogEntry entry;
            try
            {
                fixed (byte* ptr = buff)
                {
                    entry = new EventLogEntry();
                    entry.rec = new EventLogRecord(buff);
                    // Read SourceName
                    uint start = (uint)sizeof(EventLogRecord);
                    // Get the Source Name
                    entry.SourceName = ReadString(ptr, ref start);
                    // Get the Computer Name
                    entry.Computername = ReadString(ptr, ref start);
                    // Get the User Name
                    byte[] uname = new byte[entry.rec.UserSidLength];
                    Copy(ptr, ref start, uname, uname.Length);
                    entry.UserSid = GetUserInfo(uname);
                    // read the strings
                    entry.Strings = ReadString(ptr, ref start, (int)(entry.rec.DataOffset - entry.rec.StringOffset) / 2);
                    // read the data
                    entry.Data = new byte[(int)entry.rec.DataLength];
                    Copy(ptr, ref start, entry.Data, entry.Data.Length);
                    //
                }
            }
            catch (Exception)
            {
                entry = null;
            }
            return entry;
        }

        // Check whether the evt file is a valid one.
        private bool Validate(EventLogHeader header)
        {
            if (!(header.HeaderLength == 0x00000030 &&
                    header.Signature == 0x654C664c &&
                    header.Unknown1 == 0x00000001 &&
                    header.Unknown2 == 0x00000001))
                return false;
            return true;
        }

        // Read string from the byte[]
        private unsafe string ReadString(byte* ptr, ref uint start)
        {
            StringBuilder result = new StringBuilder();
            char temp;
            ptr += start;
            while (true)
            {
                temp = (char)*((ushort*)ptr);
                ptr += 2;
                start += 2;
                if (temp == '\0')
                    break;
                result.Append(temp);
            }
            return result.ToString();
        }

        // Read the Description according to the length specified.
        private unsafe string ReadString(byte* ptr, ref uint start, int count)
        {
            StringBuilder result = new StringBuilder(count);
            char temp;
            ptr += start;
            for (; count > 0; count--)
            {
                temp = (char)*((ushort*)ptr);
                ptr += 2;
                start += 2;
                result.Append(temp);
            }
            return result.ToString();
        }

        // Get the user name from SID
        private string GetUserInfo(byte[] buff)
        {
            StringBuilder name = new StringBuilder();
            uint cchName = (uint)name.Capacity;
            StringBuilder referencedDomainName = new StringBuilder();
            uint cchReferencedDomainName = (uint)referencedDomainName.Capacity;
            SID_NAME_USE sidUse;

            int err = NO_ERROR;
            if (!LookupAccountSid(null, buff, name, ref cchName, referencedDomainName, ref cchReferencedDomainName, out sidUse))
            {
                err = System.Runtime.InteropServices.Marshal.GetLastWin32Error();
                if (err == ERROR_INSUFFICIENT_BUFFER)
                {
                    name.EnsureCapacity((int)cchName);
                    referencedDomainName.EnsureCapacity((int)cchReferencedDomainName);
                    err = NO_ERROR;
                    if (!LookupAccountSid(null, buff, name, ref cchName, referencedDomainName, ref cchReferencedDomainName, out sidUse))
                        err = System.Runtime.InteropServices.Marshal.GetLastWin32Error();
                }
            }
            if (err == 0)
                return String.Format(@"{0}\{1}", referencedDomainName.ToString(), name.ToString());
            else
                return @"N\A";
        }

        // copy the byte[]
        private unsafe void Copy(byte* pSrc, ref uint srcIndex, byte[] dst, int count)
        {
            if (count == 0)
                return;
            fixed (byte* pDst = dst)
            {
                byte* ps = pSrc;
                ps += srcIndex;
                byte* pd = pDst;

                // Loop over the count in blocks of 4 bytes, copying an
                // integer (4 bytes) at a time:
                for (int n = 0; n < count / 4; n++)
                {
                    *((int*)pd) = *((int*)ps);
                    pd += 4;
                    ps += 4;
                }

                // Complete the copy by moving any bytes that weren't
                // moved in blocks of 4:
                for (int n = 0; n < count % 4; n++)
                {
                    *pd = *ps;
                    pd++;
                    ps++;
                }

                srcIndex += (uint)count;
            }
        }

        // Convert to seconds to date time format
        private DateTime GetTime(uint time)
        {
            DateTime output = new DateTime(1970, 1, 1, 0, 0, 0);
            time = time - offset;
            output = output.AddSeconds(time);
            return output;
        }
    }
}

Reading Folder structures and display in drop down

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            GetFolderList();

    }

    void GetFolderList()
    {
        string searchPattern = "*.evt";
        string InitDirectory = ConfigurationManager.AppSettings["EventPath"].ToString();
        ArrayList MyFiles = new ArrayList();
        DirectoryInfo di = new DirectoryInfo(InitDirectory);
        // Get Files
        GetFiles(di, searchPattern, ref MyFiles);
        //Print it
      //  foreach (string s in MyFiles)
       // {
          //  System.Diagnostics.Debug.Write(s);
        //}
    }



    private void GetFiles(DirectoryInfo di, string searchPattern, ref ArrayList MyFiles)
    {

        foreach (DirectoryInfo d in di.GetDirectories())
        {
            string FolderName = d.Name.ToString();
            ListItem item = new ListItem(FolderName, d.FullName);
            drpServers.Items.Add(item);
          
            //GetFiles(d, searchPattern, ref MyFiles);
        }
     
        // Search in subdirctories
      
    }

    void GetFolders()
    {
        DataTable dt = new DataTable();
        DataRow dr;
        //string upFolder = MapPath(".");
        string upFolder = ConfigurationManager.AppSettings["EventPath"].ToString();
        DirectoryInfo dir = new DirectoryInfo(upFolder);
        if (dir.Exists)
        {
            if (dir.GetDirectories().Length > 0)
            {
                FileInfo[] fi_array = dir.GetFiles();
                foreach (FileInfo fi in fi_array)
                {
                    string s = fi.Name;
                    dr = dt.NewRow();
                    dr["file_id"] = s;
                    dr["file_name"] = s;
                    dt.Rows.InsertAt(dr, 0);
                }
            }
        }

        Response.Write(dt.Rows.Count.ToString());
    }

    protected void drpDates_SelectedIndexChanged(object sender, EventArgs e)
    {
        string strValue = drpDates.SelectedValue.Trim();
        ArrayList MyFiles = new ArrayList();
        DirectoryInfo di = new DirectoryInfo(strValue);
        string searchPattern = "*.evt";
        drpfiles.Items.Clear();
        foreach (FileInfo fi in di.GetFiles(searchPattern))
        {
            ListItem item = new ListItem(fi.Name, fi.FullName);
            drpfiles.Items.Add(item);
            MyFiles.Add(fi.FullName);
        }
      

    }
    DataSet ds = null;
    void parser_OnAction(string msg)
    {
       // this.Invoke(msgHandler, new object[] { msg });
    }
    protected void drpfiles_SelectedIndexChanged(object sender, EventArgs e)
    {
       
        string strValue = drpfiles.SelectedValue.Trim();
     
        EventLogParser.EventLogParser obj = new EventLogParser.EventLogParser();

        ds = new DataSet("EventLog Entries");
        ds.Tables.Add("Events");
        ds.Tables["Events"].Columns.Add("Type");
        ds.Tables["Events"].Columns.Add("Date");
        ds.Tables["Events"].Columns.Add("Time");
        ds.Tables["Events"].Columns.Add("Source");
        ds.Tables["Events"].Columns.Add("Description");
        ds.Tables["Events"].Columns.Add("Category");
        ds.Tables["Events"].Columns.Add("EventID");
        ds.Tables["Events"].Columns.Add("User");
        ds.Tables["Events"].Columns.Add("System");

        obj.OnAction += new MessageHandler(parser_OnAction);
        obj.OnFoundRecord += new NewEventFoundHandler(obj_OnFoundRecord);
        obj.Parse(strValue);
        GridView1.DataSource = ds.Tables[0];
        GridView1.DataBind();

        //SqlConnection con = new SqlConnection("Server=172.20.11.100;User ID=Synprod;password=globe431;database=syntranet_sqlsrv;Trusted_Connection=False");

        //con.Open();
        //string strQry = "select *from System.evt";
        //SqlCommand cmd = new SqlCommand(strQry, con);
        //SqlDataAdapter ad = new SqlDataAdapter(strQry, con);
        //DataSet ds = new DataSet();
        //ad.Fill(ds);

    
       // StreamReader fp;
        //fp=File.OpenText(Server.MapPath(strValue));
        //fp = File.OpenText(strValue);
       
        ////fp.Close();
      //  string output=System.Diagnostics.EventLog.CreateEventSource(.LogNameFromSourceName(strValue, "SYNSPZ3266");
        //System.Text.StringBuilder sb = new System.Text.StringBuilder();

        //foreach (System.Diagnostics.EventLogEntry entry in log.Entries)
        //{
        //    sb.AppendLine(entry.Message);
        //}
        //Response.Write(ds.Tables[0].Rows.Count.ToString());
        // Dim fp As strea
        //fp = File.OpenText(Server.MapPath(".\Upload\") & "test.txt")
        //    txtMyFile.Text = fp.ReadToEnd()
        //    lblStatus.Text = "File Succesfully Read!"
        //    fp.Close()
        //Catch err As Exception
        //    lblStatus.Text = "File Read Failed. Reason is as follows

    }

    void obj_OnFoundRecord(object[] items)
    {
        ds.Tables[0].Rows.Add(items);
    }
    protected void drpServers_SelectedIndexChanged(object sender, EventArgs e)
    {
        string strValue = drpServers.SelectedValue.Trim();
        ArrayList MyFiles = new ArrayList();
        DirectoryInfo di = new DirectoryInfo(strValue);
        string searchPattern = "*.evt";
        drpDates.Items.Clear();

        foreach (DirectoryInfo d in di.GetDirectories())
        {
            string FolderName = d.Name.ToString();
            ListItem item = new ListItem(FolderName, d.FullName);
            drpDates.Items.Add(item);

            //GetFiles(d, searchPattern, ref MyFiles);
        }

     
    }

Wednesday, July 7, 2010

Return all tables and columns where a particular value is present -SQL SERVER

DECLARE @value VARCHAR(64)
DECLARE @sql VARCHAR(1024)
DECLARE @table VARCHAR(64)
DECLARE @column VARCHAR(64)
SET @value = 'valuehere'
CREATE TABLE #t (
    tablename VARCHAR(64),
    columnname VARCHAR(64)
)
DECLARE TABLES CURSOR
FOR
    SELECT o.name, c.name
    FROM syscolumns c
    INNER JOIN sysobjects o ON c.id = o.id
    WHERE o.type = 'U' AND c.xtype IN (167, 175, 231, 239)
    ORDER BY o.name, c.name
OPEN TABLES
FETCH NEXT FROM TABLES
INTO @table, @column
WHILE @@FETCH_STATUS = 0
BEGIN
    SET @sql = 'IF EXISTS(SELECT NULL FROM [' + @table + '] '
    --SET @sql = @sql + 'WHERE RTRIM(LTRIM([' + @column + '])) = ''' + @value + ''') '
    SET @sql = @sql + 'WHERE RTRIM(LTRIM([' + @column + '])) LIKE ''%' + @value + '%'') '
    SET @sql = @sql + 'INSERT INTO #t VALUES (''' + @table + ''', '''
    SET @sql = @sql + @column + ''')'
    EXEC(@sql)
    FETCH NEXT FROM TABLES
    INTO @table, @column
END
CLOSE TABLES
DEALLOCATE TABLES
SELECT *
FROM #t
DROP TABLE #t

Tuesday, July 6, 2010

Moving Lists from One sharepoint site to another sharpeoint site

       static void Main(string[] args)
        {
            MoveLibraries();
        }

        static void MoveAccoucements(SPWeb sourceweb, SPWeb destWeb, SPList sourceList, SPList destList, string strListName)
        {



            // copy items
            foreach (SPListItem item in sourceList.Items)
            {
                SPListItem newDestItem = destList.Items.Add();
                foreach (SPField field in sourceList.Fields)
                {
                    if (!field.ReadOnlyField && item[field.Title] != null && field.Title != "Attachments")
                        newDestItem[field.Title] = item[field.Title];
                    destWeb.AllowUnsafeUpdates = true;
                    newDestItem.Update();
                }
            }

            // set quicklaunch settings
            destList.OnQuickLaunch = sourceList.OnQuickLaunch;
            destList.Update();

        }


        static void TraverseList(SPList srclist, SPWeb srcweb, SPList trglist, SPWeb trgweb)
        {

            Console.WriteLine("Traversing list: " + srclist.Title  );
            LogMessageToFile("Traversing list: " + srclist.Title  );

            Console.WriteLine("Base Type: " + srclist.BaseType.ToString()  );
            LogMessageToFile("Base Type: " + srclist.BaseType.ToString());

            TraverseListFolder(srclist.RootFolder, trglist.RootFolder, trglist, trgweb);

        }

        static void CreateImpFields(SPListItem subitem, SPWeb trgweb, SPListItem item,string strFldName)
        {
            try
            {

                if (subitem.Fields[strFldName].ReadOnlyField && subitem[strFldName] != null)
                {
                    item.Fields[strFldName].ReadOnlyField = false;
                    item[strFldName] = subitem[strFldName].ToString();
                    trgweb.AllowUnsafeUpdates = true;
                    item.Update();
                    item.Fields[strFldName].ReadOnlyField = true;
                }
                else if (subitem[strFldName] != null)
                {
                    item[strFldName] = subitem[strFldName].ToString();
                    trgweb.AllowUnsafeUpdates = true;
                    item.Update();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + "while creating field :" + strFldName); ;
            }
        }

        static void CreateFiled(SPListItem subitem, SPWeb trgweb, SPListItem item)
        {
            try
            {
                CreateImpFields(subitem, trgweb, item, "Title");
                CreateImpFields(subitem, trgweb, item, "Created");
                CreateImpFields(subitem, trgweb, item, "Created By");
                CreateImpFields(subitem, trgweb, item, "Name");
                CreateImpFields(subitem, trgweb, item, "Modified");
                CreateImpFields(subitem, trgweb, item, "Modified By");
                Console.WriteLine("Fields are sucessfully created");


            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + "while field creation"); ;
            }
          
         
          
        

        }


        static void CreateFileds(SPListItem subitem, SPWeb trgweb, SPListItem item)
        {
            foreach (SPField field in subitem.Fields)
            {
                // if (!field.ReadOnlyField && item[field.Title] != null && field.Title != "Attachments")
                try
                {

                    if (field.ReadOnlyField)
                    {
                        item.Fields[field.Title].ReadOnlyField = false;

                        item[field.Title] = subitem[field.Title].ToString();
                        trgweb.AllowUnsafeUpdates = true;
                        item.Update();
                        item.Fields[field.Title].ReadOnlyField = true;
                    }
                    else
                    {
                        item[field.Title] = subitem[field.Title].ToString();
                        trgweb.AllowUnsafeUpdates = true;
                        item.Update();

                    }

                }
                catch (Exception ex)
                {
                    continue;
                }

            }

        }

        static void TraverseListFolder(SPFolder folder, SPFolder trgRootFolder, SPList trglist, SPWeb trgweb)
        {

            // Get the collection of items from this folder

            SPQuery qry = new SPQuery();

            qry.Folder = folder;

            SPWeb web = null;

            try
            {

                web = folder.ParentWeb;

                SPListItemCollection ic = web.Lists[folder.ParentListId].GetItems(qry);

                foreach (SPListItem subitem in ic)
                {

                    try
                    {

                        Console.WriteLine("List item: " + subitem.Name);

                        Console.WriteLine("List item type: " + subitem.ContentType.Name);
                        LogMessageToFile("List item: " + subitem.Name);
                        LogMessageToFile("List item type: " + subitem.ContentType.Name);

                        if (subitem.Folder != null)
                        {

                            trgweb.AllowUnsafeUpdates = true;
                            web.AllowUnsafeUpdates = true;

                            /* create a folder under the path specified */
                            SPFolder spfolder = trgRootFolder.SubFolders.Add(subitem.Name);
                            /* set the folder name and update */
                            SPListItem item = spfolder.Item;
                            //  item["Title"] = "Name";
                            //item["Title"]

                            CreateFiled(subitem, trgweb, item);

                            // item.Update();
                            // trgweb.AllowUnsafeUpdates = true;
                            //  web.AllowUnsafeUpdates = true;
                            TraverseListFolder(subitem.Folder, spfolder, trglist, trgweb);
                        }
                        else
                        {
                          

                            string strFileURL = subitem.File.Url.Trim();

                            //  Upload the file

                            string RegExpUrl = "{0}/{1}";
                            RegExpUrl = string.Format(RegExpUrl, trgRootFolder.Url, subitem.File.Name);

                            trgweb.AllowUnsafeUpdates = true;
                            web.AllowUnsafeUpdates = true;
                            byte[] fileBytes = subitem.File.OpenBinary();

                            const bool OverwriteDestinationFile = true;
                            SPFile destinationFile =
                          ((SPDocumentLibrary)trglist).RootFolder.Files.Add(
                           
                         RegExpUrl,
                           fileBytes,
                          OverwriteDestinationFile);
                            SPListItem item = destinationFile.Item;
                            CreateFiled(subitem, trgweb, item);


                            // item["Title"] = subitem.Name.Trim();
                            // item.Update();
                            //   trgweb.AllowUnsafeUpdates = true;
                            web.AllowUnsafeUpdates = true;

                        }

                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                        LogMessageToFile(ex.Message);
                        continue;
                    }
                 

                }

            }

            catch (Exception e)
            {

                Console.WriteLine(e.Message);
                LogMessageToFile(e.Message);


            }

            finally
            {

                // Cleanup that nasty web reference.
                if (web != null)
                    web.Dispose();

            }

        }
        static System.IO.StreamWriter sw;
        static void CreatLogFile()
        {
            try
            {
                string strPath = GetTempPath();
                if (!File.Exists(strPath))
                    sw = System.IO.File.CreateText(strPath);
                else
                    sw = System.IO.File.AppendText(strPath);


            }
            finally
            {
                sw.Close();
            }
        }
        static string GetTempPath()
        {
            string path = ConfigurationSettings.AppSettings["LogPath"];
            path = path + DateTime.Now.ToString("dd-MM-yyyy" )+".txt";

            return path;
        }

        static void LogMessageToFile(string msg)
        {

            try
            {
                sw = System.IO.File.AppendText(GetTempPath());
                string logLine = System.String.Format(
                    "{0:G}: {1}.", System.DateTime.Now, msg);
                sw.WriteLine(logLine);
            }
            finally
            {
                sw.Close();
            }
        }

        static void MoveLibraries()
        {
            CreatLogFile();
            LogMessageToFile("***************************Service Start***************************************");
            string strSrcURL = "", strTrgURL = "", strSrcSite = "", strTrgSite = "";
            //Console.Write("Please Enter Source Site URL:");
            strSrcURL = ConfigurationSettings.AppSettings["SourceURL"].ToString();
            strTrgURL = ConfigurationSettings.AppSettings["TargetURL"].ToString();


             Console.Write("Please Enter Source Site Name:");
            strSrcSite = Console.ReadLine();

            Console.Write("Please Enter Trarget Site Name:");
            strTrgSite = Console.ReadLine();



            SPSite srcSite = new SPSite(strSrcURL);

            SPWeb srcWebs = srcSite.AllWebs[strSrcSite];

            SPSite trgSite = new SPSite(strTrgURL);

            SPWeb trgWebs = trgSite.AllWebs[strTrgSite];


            SPListCollection srcLists = srcWebs.Lists;
            SPListCollection trgLists = trgWebs.Lists;

            for (int i = 0; i < srcLists.Count; i++)
            {
                Console.WriteLine("ListName: " + srcLists[i].Title);
                LogMessageToFile("ListName: " + srcLists[i].Title);

                try
                {
                    SPList temp = trgWebs.Lists[srcLists[i].Title];
                    trgWebs.Lists.Delete(temp.ID);
                }
                catch { }


                if (srcLists[i].BaseTemplate.ToString() == "DocumentLibrary" || srcLists[i].BaseTemplate.ToString() == "PictureLibrary" || srcLists[i].BaseTemplate.ToString() == "Announcements")
              
                {

                    try
                    {

                        // create new list on the destination web with same properties
                        //  SPList sourcelist=srcWebs[si].Lists[""]
                        trgWebs.AllowUnsafeUpdates = true;

                        Guid newListID = trgWebs.Lists.Add(srcLists[i].Title, srcLists[i].Description,
                                                           srcLists[i].BaseTemplate);
                        trgWebs.AllowUnsafeUpdates = true;
                        SPList destList = trgWebs.Lists[newListID];

                        Console.WriteLine(srcLists[i].Title + " :List Created SucessFully");
                         LogMessageToFile(srcLists[i].Title + " :List Created SucessFully");

                        if (srcLists[i].BaseTemplate.ToString() == "DiscussionBoard" || srcLists[i].BaseTemplate.ToString() == "Announcements")
                        {

                            MoveAccoucements(srcWebs, trgWebs, srcLists[i], destList, srcLists[i].Title.ToString());
                        }
                        else if (srcLists[i].BaseTemplate.ToString() == "DocumentLibrary" || srcLists[i].BaseTemplate.ToString() == "PictureLibrary")
                        {

                            TraverseList(srcLists[i], srcWebs, destList, trgWebs);
                          
                        }
                      //  Console.ReadLine("*********************************End Of Serive*********************************");
                        LogMessageToFile("***************************Service Start***************************************");
                    }
                    catch (Exception ex)
                    {
                         Console.WriteLine("Error :" + ex.Message);

                    }
                }
            }
        }