'System.InvalidCastException' error when exporting sharepoint

System.InvalidCastException: Unable to cast object of type...

Page 1 of 1

4 Replies - 2310 Views - Last Post: 18 August 2010 - 07:42 AM Rate Topic: -----

#1 swferrier  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 17-August 10

'System.InvalidCastException' error when exporting sharepoint

Posted 18 August 2010 - 06:34 AM

I am using a tool to export user profile data from SharePoint 2007 SSP database. When I click multiple fields for export within the tool and try to run, I get the following error:

---------------------------
ERROR
---------------------------
System.InvalidCastException: Unable to cast object of type 'System.String' to type 'System.Collections.ArrayList'.

at SharePointProfileExporter.frmMain.BuildHeader(ArrayList PropertyNames)

at SharePointProfileExporter.frmMain.cmdBeginExport_Click(Object sender, EventArgs e)
---------------------------
OK
---------------------------

Here is the code:

private void cmdBeginExport_Click(object sender, System.EventArgs e)
		{
			try 
			{
				//TODO: Check to make sure at least 1 column is checked...

				start = DateTime.Now.Ticks; 

				this.pbProgress.Value = 0;
				this.pbProgress.Visible = true;
				this.pbProgress.Enabled = true;
				this.pbProgress.Minimum = 0;
				this.pbProgress.Maximum = Convert.ToInt32(iRows);
				this.pbProgress.Step = 1;

				//Get Portal Context from the drop down list
				//TopologyManager topologyManager = new TopologyManager();
				//Uri uri = new Uri(cbPortals.SelectedValue.ToString());
				//PortalSiteCollection sites = topologyManager.PortalSites;
				//PortalContext pc = PortalApplication.GetContext(sites[uri]); //SPS2003 API
				//UserProfileManager upm = new UserProfileManager(pc);  //SPS203 API
                
                using (SPSite ssp = new SPSite(cbPortals.SelectedValue.ToString()))
                {
                    //Microsoft.Office.Server.ServerContext sc = Microsoft.Office.Server.ServerContext.GetContext("SharedServices1"); //TODO: use webapp instead of hardcoded ssp name.
                    Microsoft.Office.Server.ServerContext sc = Microsoft.Office.Server.ServerContext.GetContext(ssp);
                    UserProfileManager upm = new UserProfileManager(sc,true); //ignore user privacy = true

				    string sTotal = iRows.ToString() + ")";
				    int iLoop = 0;

				    //create temp txt file in application directory
				    string fileName = System.DateTime.Now.Month.ToString() + "-" +
					    System.DateTime.Now.Day.ToString() + "-" +
					    System.DateTime.Now.Year.ToString() + " " +
					    System.DateTime.Now.Hour.ToString() +
					    System.DateTime.Now.Minute.ToString() +
					    System.DateTime.Now.Second.ToString() +
					    ".csv";
				    StreamWriter sw = File.CreateText(Application.StartupPath + "\\" + fileName);


				    //Create list of properties to export
				    ArrayList _aCkd = new ArrayList();
				    ListView.CheckedListViewItemCollection checkedItems = lvProfiles.CheckedItems;
				    foreach (ListViewItem item in checkedItems)
				    {
					    _aCkd.Add(item.SubItems[1].Text);
					    //_header.Append("," + item.SubItems[1].Text);
				    }
                    
                    //Header
                    string _header=BuildHeader(_aCkd);
                    sw.WriteLine(_header);

				    //foreach(Microsoft.SharePoint.Portal.UserProfiles.UserProfile _up in upm) // SPS2003 API
                    foreach(UserProfile _up in upm)
				    {
					    sbpText.Text = "Exporting profile " + _up["AccountName"].ToString() + " (" + iLoop.ToString() + " of " + sTotal.ToString();
    					
					    StringBuilder _out = new StringBuilder();
					    _out.Append("\"" + _up["AccountName"].ToString() + "\"");

					    //for each property in the property collection
					    foreach(string _i in _aCkd)
					    {
                            Debug.WriteLine(_i.ToString());
						    //if the prop is within the _aCkd, then we can add it to the output string
                            //We already added the AccountName.  Don't add it again.
                            if ((null != _up[_i.ToString()]) && ("AccountName" != _i.ToString()))
                            {
                                UserProfileValueCollection upvCollection = _up[_i.ToString()];

                                if (null != upvCollection.Value)
                                {
                                    //TODO: Make the field separator configurable.
                                    _out.Append(",\"" + _up[_i.ToString()] + "\""); //TODO:  need to handle multi-value props.
                                }
                                else
                                {
                                    _out.Append(",\"" + "" + "\"");
                                }
                            }
                            else 
                            {
                                Debug.WriteLine("null encountered");
                            }
					    }
    					
					    sw.WriteLine(_out);
					    this.pbProgress.PerformStep();
					    iLoop++;
				    }
				    pbProgress.Value = 0;
				    end = DateTime.Now.Ticks; 
				    TimeSpan tsExec = new TimeSpan(end-start);
				    sbpText.Text = "Idle (" + iLoop.ToString() + " profiles exported in " 
					    + tsExec.Hours.ToString() + "h "
					    + tsExec.Minutes.ToString() + "m "
					    + tsExec.Seconds.ToString() + "s "
					    + tsExec.Milliseconds.ToString() + "ms "
					    + ")";

				    sw.Close();
				    System.Diagnostics.Process.Start("Explorer.exe", Application.StartupPath.ToString());
                } //using
			}
			catch (Exception ex)
			{
				MessageBox.Show(null,ex.ToString(),"ERROR");
			}
		}




&


        private string BuildHeader(string PropertyNames)
        {
           
            //Create HeaderRow
            StringBuilder _header = new StringBuilder();
            _header.Append("AccountName");
            foreach (ArrayList item in PropertyNames)
            {
                _header.Append("," + item);
            }
            return _header.ToString();
        }
        #endregion Helper Methods



Any help will be most appreciated. I have no coding experience, but access to VS2010.

Is This A Good Question/Topic? 0
  • +

Replies To: 'System.InvalidCastException' error when exporting sharepoint

#2 Somyagupta  Icon User is offline

  • D.I.C Head

Reputation: 6
  • View blog
  • Posts: 85
  • Joined: 05-August 10

Re: 'System.InvalidCastException' error when exporting sharepoint

Posted 18 August 2010 - 06:52 AM

Try replacing the code

 string _header=BuildHeader(_aCkd);  


with

 string _header=Convert.ToString(BuildHeader(_aCkd));



Basically its asking you to convert the arraylist to string before assigning it to another string.

Hope this is helpfull
Was This Post Helpful? 0
  • +
  • -

#3 swferrier  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 17-August 10

Re: 'System.InvalidCastException' error when exporting sharepoint

Posted 18 August 2010 - 07:09 AM

View PostSomyagupta, on 18 August 2010 - 05:52 AM, said:

Try replacing the code

 string _header=BuildHeader(_aCkd);  


with

 string _header=Convert.ToString(BuildHeader(_aCkd));



Basically its asking you to convert the arraylist to string before assigning it to another string.

Hope this is helpfull


Thanks for your reply. Unfortunately I just tried it and it threw the same error (below)
---------------------------
ERROR
---------------------------
System.InvalidCastException: Unable to cast object of type 'System.String' to type 'System.Collections.ArrayList'.

at SharePointProfileExporter.frmMain.BuildHeader(ArrayList PropertyNames)

at SharePointProfileExporter.frmMain.cmdBeginExport_Click(Object sender, EventArgs e)
---------------------------
OK
---------------------------

Here is the updated code

private void cmdBeginExport_Click(object sender, System.EventArgs e)
		{
			try 
			{
				//TODO: Check to make sure at least 1 column is checked...

				start = DateTime.Now.Ticks; 

				this.pbProgress.Value = 0;
				this.pbProgress.Visible = true;
				this.pbProgress.Enabled = true;
				this.pbProgress.Minimum = 0;
				this.pbProgress.Maximum = Convert.ToInt32(iRows);
				this.pbProgress.Step = 1;

				//Get Portal Context from the drop down list
				//TopologyManager topologyManager = new TopologyManager();
				//Uri uri = new Uri(cbPortals.SelectedValue.ToString());
				//PortalSiteCollection sites = topologyManager.PortalSites;
				//PortalContext pc = PortalApplication.GetContext(sites[uri]); //SPS2003 API
				//UserProfileManager upm = new UserProfileManager(pc);  //SPS203 API
                
                using (SPSite ssp = new SPSite(cbPortals.SelectedValue.ToString()))
                {
                    //Microsoft.Office.Server.ServerContext sc = Microsoft.Office.Server.ServerContext.GetContext("SharedServices1"); //TODO: use webapp instead of hardcoded ssp name.
                    Microsoft.Office.Server.ServerContext sc = Microsoft.Office.Server.ServerContext.GetContext(ssp);
                    UserProfileManager upm = new UserProfileManager(sc,true); //ignore user privacy = true

				    string sTotal = iRows.ToString() + ")";
				    int iLoop = 0;

				    //create temp txt file in application directory
				    string fileName = System.DateTime.Now.Month.ToString() + "-" +
					    System.DateTime.Now.Day.ToString() + "-" +
					    System.DateTime.Now.Year.ToString() + " " +
					    System.DateTime.Now.Hour.ToString() +
					    System.DateTime.Now.Minute.ToString() +
					    System.DateTime.Now.Second.ToString() +
					    ".csv";
				    StreamWriter sw = File.CreateText(Application.StartupPath + "\\" + fileName);


				    //Create list of properties to export
				    ArrayList _aCkd = new ArrayList();
				    ListView.CheckedListViewItemCollection checkedItems = lvProfiles.CheckedItems;
				    foreach (ListViewItem item in checkedItems)
				    {
					    _aCkd.Add(item.SubItems[1].Text);
					    //_header.Append("," + item.SubItems[1].Text);
				    }
                    
                    //Header
                    string _header = Convert.ToString(BuildHeader(_aCkd));
                    sw.WriteLine(_header);

				    //foreach(Microsoft.SharePoint.Portal.UserProfiles.UserProfile _up in upm) // SPS2003 API
                    foreach(UserProfile _up in upm)
				    {
					    sbpText.Text = "Exporting profile " + _up["AccountName"].ToString() + " (" + iLoop.ToString() + " of " + sTotal.ToString();
    					
					    StringBuilder _out = new StringBuilder();
					    _out.Append("\"" + _up["AccountName"].ToString() + "\"");

					    //for each property in the property collection
					    foreach(string _i in _aCkd)
					    {
                            Debug.WriteLine(_i.ToString());
						    //if the prop is within the _aCkd, then we can add it to the output string
                            //We already added the AccountName.  Don't add it again.
                            if ((null != _up[_i.ToString()]) && ("AccountName" != _i.ToString()))
                            {
                                UserProfileValueCollection upvCollection = _up[_i.ToString()];

                                if (null != upvCollection.Value)
                                {
                                    //TODO: Make the field separator configurable.
                                    _out.Append(",\"" + _up[_i.ToString()] + "\""); //TODO:  need to handle multi-value props.
                                }
                                else
                                {
                                    _out.Append(",\"" + "" + "\"");
                                }
                            }
                            else 
                            {
                                Debug.WriteLine("null encountered");
                            }
					    }
    					
					    sw.WriteLine(_out);
					    this.pbProgress.PerformStep();
					    iLoop++;
				    }
				    pbProgress.Value = 0;
				    end = DateTime.Now.Ticks; 
				    TimeSpan tsExec = new TimeSpan(end-start);
				    sbpText.Text = "Idle (" + iLoop.ToString() + " profiles exported in " 
					    + tsExec.Hours.ToString() + "h "
					    + tsExec.Minutes.ToString() + "m "
					    + tsExec.Seconds.ToString() + "s "
					    + tsExec.Milliseconds.ToString() + "ms "
					    + ")";

				    sw.Close();
				    System.Diagnostics.Process.Start("Explorer.exe", Application.StartupPath.ToString());
                } //using
			}
			catch (Exception ex)
			{
				MessageBox.Show(null,ex.ToString(),"ERROR");
			}
		}



any other ideas?

This post has been edited by swferrier: 18 August 2010 - 07:21 AM

Was This Post Helpful? 0
  • +
  • -

#4 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6078
  • View blog
  • Posts: 23,549
  • Joined: 23-August 08

Re: 'System.InvalidCastException' error when exporting sharepoint

Posted 18 August 2010 - 07:17 AM

Your BuildHeader method is just wrong. I think it should be taking an ArrayList as an argument and should look like this:
private string BuildHeader(ArrayList PropertyNames)
{
   
    //Create HeaderRow
    StringBuilder _header = new StringBuilder();
    _header.Append("AccountName");
    foreach (string item in PropertyNames)
    {
        _header.Append("," + item);
    }
    return _header.ToString();
}


Was This Post Helpful? 0
  • +
  • -

#5 swferrier  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 17-August 10

Re: 'System.InvalidCastException' error when exporting sharepoint

Posted 18 August 2010 - 07:42 AM

View PostJackOfAllTrades, on 18 August 2010 - 06:17 AM, said:

Your BuildHeader method is just wrong. I think it should be taking an ArrayList as an argument and should look like this:
private string BuildHeader(ArrayList PropertyNames)
{
   
    //Create HeaderRow
    StringBuilder _header = new StringBuilder();
    _header.Append("AccountName");
    foreach (string item in PropertyNames)
    {
        _header.Append("," + item);
    }
    return _header.ToString();
}



Thanks, but the same error exists. here is the updated BuildHeader code

private string BuildHeader(ArrayList PropertyNames)
{
   
    //Create HeaderRow
    StringBuilder _header = new StringBuilder();
    _header.Append("AccountName");
    foreach (string item in PropertyNames)
    {
        _header.Append("," + item);
    }
    return _header.ToString();
}


        }
        #endregion Helper Methods
    }
}


Was This Post Helpful? 0
  • +
  • -

Page 1 of 1