I would like to read selected value from dropdownlist and accordingly, set the maxlength of a textbox through javascript.

To use javascript inside a user control, one should remember, while it is rendered in the page, a control called txtComany will be having a name like ctl03$txtComany when it is rendered on the page.

Hence it is important to call the clientId of the textbox like :

document.getElementById(“<%=txtComany.ClientID%>”).value;

 

function SetTextBoxMaxLength() {
var e = document.getElementById(“<%=DropDownlist1.ClientID%>);
var strUser = e.options[e.selectedIndex].text;
if (strUser == “Cargo ” || strUser == “Agent”) {
//Set maxlength of textbox to 11 through Javascript
document.getElementById(“<%=TextBox1.ClientID%>).maxLength = 11
}
else {
//Set maxlength of textbox to 8 through Javascript
document.getElementById(“<%=TextBox1.ClientID%>).maxLength = 8
}
}

The HTML of the page is like

<asp:TextBox CssClass=”contact” ID=”CUECode” onKeyDown=”SetCUECodeMaxLength();” runat=”server”/> 

To get selected value from dropdownlist using javascript:

var e = document.getElementById(“<%=Dropdown1.ClientID%>”);

var strUser = e.options[e.selectedIndex].text;

 To use onchange event of dropdownlist instead of using the selectedindexchange event through code behind to prevent postback, suppose the HTML is as shown below:

<asp:DropDownList ID=”DropDown1″ runat=”server” onchange=”ClearTextBox();” class=”type”/>

function ClearTextBox() {

  

 if (document.getElementById(“<%=TextBox1.ClientID%>”).value.length > 0) {

 

document.getElementById(“<%=TextBox1.ClientID%>”).value = “”;

}

}

 

 

 

The export to spreadsheet link was not visible in a particular list and we had an urgent request to export data from list to an excel.

So we created a windows application to take care of it.

Added web reference http://extranet/sites/sis-forum/_vti_bin/lists.asmx to the project and named it Sisforum.

Added a textbox txtSiteUrl  in the Windows form…and added the url of the site from where we wanted to export a list to excel e.g https://test-web.domain.org/sites/isago/_vti_bin/lists.asmx , in another textbox txtListName ,gave the name of the list we wanted to export,say “UserManagement Task” and a textbox txtFilepath  for putting the filepath like “c:\test.xls”.

 

            StringBuilder strExcel = new StringBuilder();
            StringBuilder strHtml = new StringBuilder();
            System.Net.NetworkCredential credential = new System.Net.NetworkCredential(“username”, “password”);
            XmlDocument xdoc = new XmlDocument();
            XmlNode allFields = xdoc.CreateElement(“ViewFields”);
            XmlNode QueryOpt = xdoc.CreateElement(“QueryOptions”);
            XmlNode Query = xdoc.CreateElement(“Query”);
            XmlNode xmlResults;
            try
            {
               SisForum.Lists lsts = new ExporttoExcelFile.SisForum.Lists();
                lsts.Credentials = credential;
                lsts.Url = txtSiteUrl.Text+”/_vti_bin/lists.asmx”;
                xmlResults = lsts.GetListItems(txtListName.Text, null, null, null, “1000000”, null, null);
                //Get Header Row
                foreach (XmlNode node in xmlResults)
                {
                    if (node.Name == “rs:data”)
                    {
                        for (int i = 0; i < 2; i++)
                        {
                            strExcel.Append(“\n”);
                           strHtml.Append(“”);
                           if (node.ChildNodes[i].Name == “z:row”)
                            {
              for (int j = 0; j < node.ChildNodes[i].Attributes.Count; j++)
                                {
                                    if (node.ChildNodes[i].Attributes[j] != null)
                                    {
                     string name = node.ChildNodes[i].Attributes[j].Name;
                                        name = StripHTML(name);
                   strExcel.Append(name.Substring(name.IndexOf(‘#’) + 1));
                                        strExcel.Append(“\t”);
                                    }
                                }
                            }
                        }
                    }
                }

                //Get List Items
                foreach (XmlNode node in xmlResults)
                {
                    if (node.Name == “rs:data”)
                    {
                        for (int i = 0; i < node.ChildNodes.Count; i++)
                        {
                            strExcel.Append(“\n”);
                            strHtml.Append(“”);
                            if (node.ChildNodes[i].Name == “z:row”)
                            {  
                                //get list items
          for (int j = 0; j < node.ChildNodes[i].Attributes.Count; j++)
                                {
                                    if (node.ChildNodes[i].Attributes[j] != null)
                                    {
        string name = node.ChildNodes[i].Attributes[j].Value;
                                        name = StripHTML(name);
                   strExcel.Append(name.Substring(name.IndexOf(‘#’) + 1));
                                        strExcel.Append(“\t”);
                                    }
                                }
                            }
                        }
                    }
                }
               WritetoFile(strExcel,”xls”);
               MessageBox.Show(“Completted”);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

public void WritetoFile(StringBuilder str,string Format)

        {

            string filename = txtFilepath.Text;

            TextWriter tw = new StreamWriter(filename);

            tw.Write(str);

            tw.Close();

        }

Now the string that we get from the xml by calling GetListItems needs to be formatted.We need to remove HTML development formatting, replace line breaks with space because browsers insert spaces,remove all scripts etc. The below functio takes care of that:

public string StripHTML(string source)

        {

            try

            {

                string result;

                // Remove HTML Development formatting

                // Replace line breaks with space

                // because browsers inserts space

                result = source.Replace(“\r”, ” “);

                // Replace line breaks with space

                // because browsers inserts space

                result = result.Replace(“\n”, ” “);

                // Remove step-formatting

                result = result.Replace(“\t”, string.Empty);

                // Remove repeating spaces because browsers ignore them

result = System.Text.RegularExpressions.Regex.Replace(result,  @”( )+”, ” “);

// Remove the header (prepare first by clearing attributes)

result = System.Text.RegularExpressions.Regex.Replace(result, @”<( )*head([^>])*>”, “<head>”,                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                result = System.Text.RegularExpressions.Regex.Replace(result,  @”(<( )*(/)( )*head( )*>)”, “</head>”,                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                result = System.Text.RegularExpressions.Regex.Replace(result,  “(<head>).*(</head>)”, string.Empty,                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);

// remove all scripts (prepare first by clearing attributes)

result = System.Text.RegularExpressions.Regex.Replace(result,    @”<( )*script([^>])*>”, “<script>”,                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                result = System.Text.RegularExpressions.Regex.Replace(result,  @”(<( )*(/)( )*script( )*>)”, “</script>”,                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);         

result = System.Text.RegularExpressions.Regex.Replace(result,   @”(<script>).*(</script>)”, string.Empty,                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);

// remove all styles (prepare first by clearing attributes)

result = System.Text.RegularExpressions.Regex.Replace(result,   @”<( )*style([^>])*>”, “<style>”,                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);

result = System.Text.RegularExpressions.Regex.Replace(result,    @”(<( )*(/)( )*style( )*>)”, “</style>”,                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);

result = System.Text.RegularExpressions.Regex.Replace(result, “(<style>).*(</style>)”, string.Empty,                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                // insert tabs in spaces of <td> tags

result = System.Text.RegularExpressions.Regex.Replace(result,  @”<( )*td([^>])*>”, “\t”,                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                // insert line breaks in places of <BR> and <LI> tags

result = System.Text.RegularExpressions.Regex.Replace(result,    @”<( )*br( )*>”, “\r”,                          System.Text.RegularExpressions.RegexOptions.IgnoreCase);

result = System.Text.RegularExpressions.Regex.Replace(result,   @”<( )*li( )*>”, “\r”,  System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                // insert line paragraphs (double line breaks) in place

                // if <P>, <DIV> and <TR> tags

result = System.Text.RegularExpressions.Regex.Replace(result,  @”<( )*div([^>])*>”, string.Empty,                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);

result = System.Text.RegularExpressions.Regex.Replace(result,  @”<( )*tr([^>])*>”, string.Empty,                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);

result = System.Text.RegularExpressions.Regex.Replace(result,   @”<( )*p([^>])*>”, string.Empty,                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                // Remove remaining tags like <a>, links, images,

                // comments etc – anything that’s enclosed inside < >

result = System.Text.RegularExpressions.Regex.Replace(result, @”<[^>]*>”, string.Empty,                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                // replace special characters:

result = System.Text.RegularExpressions.Regex.Replace(result,   @” “, ” “,   System.Text.RegularExpressions.RegexOptions.IgnoreCase);

result = System.Text.RegularExpressions.Regex.Replace(result, @”&bull;”, ” * “,   System.Text.RegularExpressions.RegexOptions.IgnoreCase);

result = System.Text.RegularExpressions.Regex.Replace(result,   @”&lsaquo;”, “<“,  System.Text.RegularExpressions.RegexOptions.IgnoreCase);

result = System.Text.RegularExpressions.Regex.Replace(result,  @”&rsaquo;”, “>”,     System.Text.RegularExpressions.RegexOptions.IgnoreCase);

result = System.Text.RegularExpressions.Regex.Replace(result,  @”&trade;”, “(tm)”,   System.Text.RegularExpressions.RegexOptions.IgnoreCase);

result = System.Text.RegularExpressions.Regex.Replace(result, @”&frasl;”, “/”,   System.Text.RegularExpressions.RegexOptions.IgnoreCase);

result = System.Text.RegularExpressions.Regex.Replace(result, @”&lt;”, “<“,    System.Text.RegularExpressions.RegexOptions.IgnoreCase);

result = System.Text.RegularExpressions.Regex.Replace(result, @”&gt;”, “>”,  System.Text.RegularExpressions.RegexOptions.IgnoreCase);

result = System.Text.RegularExpressions.Regex.Replace(result,   @”&copy;”, “(c)”,    System.Text.RegularExpressions.RegexOptions.IgnoreCase);

result = System.Text.RegularExpressions.Regex.Replace(result,  @”&reg;”, “(r)”,   System.Text.RegularExpressions.RegexOptions.IgnoreCase);

result = System.Text.RegularExpressions.Regex.Replace(result,  @”&(.{2,6});”, string.Empty,                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                return result;

            }

            catch

            {

                return source;

            }

        }

 I had to convert an excel file with different languages into a xml/dataset.

Below is the sample excel sheet I had

English French Spanish Portugese
Guinea Guinéee Guinea Guiné
Côte d’Ívoire Côte d’Ívoire Costa de Marfil Costa do Marfim
South Africa Afrique du Sud Sudáfrica África do Sul

For Excel 97-2003 format Microsoft Jet OLEDB Driver 4.0 is used. A sample connection string as follows.For Excel 2007 format the new Microsoft Ace OLEDB Driver 4.0 is used.

Code to convert is shown below:

//Connection String for Excel 97-2003 Format (.XLS)

String strExcelConn = “Provider=Microsoft.Jet.OLEDB.4.0;”

+ “Data Source=C:\\Gitolekha\\test.xls;

+ “Extended Properties=’Excel 8.0;HDR=Yes’“;

//Connect to excel sheet

OleDbConnection connExcel = new OleDbConnection(strExcelConn);

OleDbDataAdapter da = new OleDbDataAdapter();

OleDbCommand cmdExcel = new OleDbCommand();

cmdExcel.Connection = connExcel;

//Access the sheet

connExcel.Open();

DataTable dtExcelSchema;

dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

DataSet ds = new DataSet();

string SheetName = dtExcelSchema.Rows[0][“TABLE_NAME“].ToString();//It fetches the first sheet Sheet1$

cmdExcel.CommandText = “SELECT * From [” + SheetName + “]”;

da.SelectCommand = cmdExcel;

da.Fill(ds);

connExcel.Close();

 StringWriter sw = new StringWriter();

ds.WriteXml(sw, XmlWriteMode.IgnoreSchema);

 string textToConvert = sw.ToString();

//Encoding xml as it contains non ASCII characters of different languages 

Encoding latin = Encoding.GetEncoding(28591);

Encoding iso8= Encoding.GetEncoding(“iso-8859-8“);

Byte[] latinBytes= latin.GetBytes(textToConvert);

Byte[] iso8bytes = Encoding.Convert(latin, iso8, latinBytes);

string str = Encoding.UTF8.GetString(iso8bytes);

return str;

There is one point to remember if you are running this on a 64-bit platform:

I kept on getting eror “‘Microsoft.Jet.OLEDB.4.0′ provider is not registered on the local machine“, after much searching on the net, I dicovered :

  • there is no Jet OLEDB provider to use on a 64bit platform

However, we can configure the IIS to run 32-bit application on 64-bit Windows(IIS 6.0), for details, one can reffer the below url’s

http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/405f5bb5-87a3-43d2-8138-54b75db73aa1.mspx?mfr=true

http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/13f991a5-45eb-496c-8618-2179c3753bb0.mspx?mfr=true

This example shows how to add custom links under site administrator from site settings page. Below is Elements.xml modification

  <CustomActionGroup Id=”DF784448-CD3F-4221-9B8A-69769FA961EE” Title=”Cargolink Adminsitration” Location=”Microsoft.SharePoint.SiteSettings” Sequence=”110” />
<CustomAction Id=”EDBEB420-A817-4896-BE42-F5B9048C0CF5” Title=”Manage Company Profile” Location=”Microsoft.SharePoint.SiteSettings” GroupId=”DF784448-CD3F-4221-9B8A-69769FA961EE” Sequence=”120” RequireSiteAdministrator=”True“>
  <UrlAction Url=”_layouts/CargoLink/CompanyProfile.aspx” />
  </CustomAction>
<CustomAction Id=”29020219-0C09-4ef0-BF0A-8921F99AD1B0” Title=”Import from CSV” Location=”Microsoft.SharePoint.SiteSettings” GroupId=”DF784448-CD3F-4221-9B8A-69769FA961EE” Sequence=”130” RequireSiteAdministrator=”True“>
  <UrlAction Url=”_layouts/CargoLink/CompanyImport.aspx” />
  </CustomAction>

   </Elements>

This will create a new custom group called “Cargolink Administration” under the site settings page and have the 2 links placed under it.

There is a property which says RequireSiteAdminsitrator and its made as true. So in that case if non-adminsitrators will not be able to load the page. You can test the permissions too.

If you want to place the links under Site Administration group in Site settings page,this is what you write.

<CustomAction Id=”EDBEB420-A817-4896-BE42-F5B9048C0CF5” Title=”Manage Company Profile” Location=”Microsoft.SharePoint.SiteSettings” GroupId=”SiteAdministration” Sequence=”120” RequireSiteAdministrator=”True“>
  <UrlAction Url=”_layouts/CargoLink/CompanyProfile.aspx” />
  </CustomAction>
<CustomAction Id=”29020219-0C09-4ef0-BF0A-8921F99AD1B0” Title=”Import from CSV” Location=”Microsoft.SharePoint.SiteSettings” GroupId=”SiteAdministration” Sequence=”130” RequireSiteAdministrator=”True“>
  <UrlAction Url=”_layouts/CargoLink/CompanyImport.aspx” />
  </CustomAction>
  </Elements>
 
From feature.xml in call this element.xml as
<?xml version=”1.0″ encoding=”utf-8″ ?>
<Feature Id=”8f20690b-efb1-46bf-99dd-688aab89ac2e” Title=”Cargolink Administration” Description=”Cargolink Administration Pages” Version=”12.0.0.0” Hidden=”FALSE” Scope=”Web” DefaultResourceFile=”core” xmlns=”http://schemas.microsoft.com/sharepoint/“>
<ElementManifests>
  <ElementManifest Location=”elements.xml” />
  </ElementManifests>
  </Feature>
 
Run the stsadm to install the feature.

Stsadm to install feature

 C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\BIN>stsadm -o installfeature -name “CargolinkAdministration”  -force

The go to site site actions -> site settings Site Features and Activate the Feature “Cargolink Adminisrtation” .

It is a known issue that on exporting list items,look up column values are lost.

If the list is very big,it might not be possible to fix that manually.This problem occues since list template does look up on a table using GUID,on creating a list template and exporting to a different site,this GUID changes,hence it is no longer able to retain the values.

Suppose I have a list “Category” which has a look up column “sub category” which refers to list “Sub Categories“. I assume you have already created a look up list “Sub Categories” in the destination web.

  1. Browse to the source Web’s lookup list “Sub Category” and choose Modify settings and columns.
  2. Copy the source lookup list GUID from the URL.It should be a sequence of numbers and letters similar to:  %7BFFA47BF8%2D849C%2D4F20%2D9C50%2D173D2F5B6725%7D
  3. Browse to the destination Web’s lookup list and choose Modify settings and columns.
  4. Copy the destination lookup list GUID from the URL.Similar as point 2.
  5. Delete %2D from the string and replace with a dash sign (-). There should be no dash sign (-) at the start and the end. GUID should be in the following format: FA47BF8-849C-4F20-9C50-173D2F5B6725
  6. Save the source Web’s list that contains a lookup column “Category” to the lookup list as a list template called category.stp.
  7. Export the list template STP from the source list template gallery to the file system.
  8. Rename the category.stp file to category.cab so Windows can open it.
  9. Open the file, right click on the manifest.xml file and export it to the file system.
  10. Edit the manifest.xml file; find the source Web’s lookup list GUID and replace it with the destination Web’s lookup list GUID.
  11. Save the manifest.xml file.
  12. Open a VS.NET command prompt.
  13. Run the makecab command as: makecab manifest.xml category.stp
  14. Import the new STP into the destination Web’s list template gallery. You will need to delete it if it has previously been imported.
  15. Create a new list “Category” based upon the new STP file.

I was writing code using SPWeb under the impression that “using” statement takes care of disposing objects.
My Function was something like the one shown below:

public void LoadFunction()
{
using (SPWeb ospWeb = SPContext.Current.Web)
{
….Logic
}
}

However,I kept getting the error “Trying to use an SPWeb object that has been closed or disposed and is no longer valid.”
I realized, we should dispose off the SPSite object and not the SPWeb object directly.

So,I modified the code as shown below:

public void LoadFunction()
{
using(SPSite spSite=new SPSite(SPContext.Current.Web.Url))
{
using (SPWeb spWeb = spSite.OpenWeb())
{
….Logic
}
}
}

This solved the problem of “Trying to use an SPWeb object that has been closed or disposed and is no longer valid.”

We sometimes need to add lists,document/image libraries to a site automatically, or in other words when a feature is activated.To do that,we need a Feature Receiver class and on Feature Activated,we need to write the code for asdding list/doc library/picture library

using (SPSite siteCollection = new SPSite(“Absolute_url”))
{
using (SPWeb mySite = siteCollection.OpenWeb())
{
SPListCollection _Lists = mySite.Lists;
try
{
if (_Lists[strListName] != null)
Message += ” List Already Exists”;

}
catch(Exception ex)
{
Guid listGuid = _Lists.Add(“MapPicLibrary”, “Map Picture Library”, SPListTemplateType.PictureLibrary);
}
}
}