How to find Object property and set it's value

by admin 16. July 2008 10:44

Sometimes you may want to find your object property and set it's value. To do this try something like this:

MyObject myObject = new MyObject(); string propertyName = "MyPropertyName"; bool myValue = true;
Type type = this.GetType();
System.Reflection.PropertyInfo property = type.GetProperty(propertyName);
if (property != null)
    System.ComponentModel.TypeDescriptor.GetProperties(typeof(MyObject))[propertyName].SetValue(myObject, myValue);

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

c#

How to get cell value from OpenXml document (Excel 2007)

by admin 17. June 2008 14:34

Below you'll find code snippet for reading cell value(s) from Office 2007 Excel document.

In order to get this working you'll need to add refference to WindowsBase.dll .

sheetName="Sheet1"; addressName="E9";

public static string GetCellValue(string filePath, string sheetName, string addressName)
        {
            //  Return the value of the specified cell.
            const string documentRelationshipType = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument";
            const string worksheetSchema = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";
            const string sharedStringsRelationshipType = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings";
            const string sharedStringSchema = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";

            string cellValue = null;

            //  Retrieve the stream containing the requested
            //  worksheet's info:
            using (System.IO.Packaging.Package xlPackage = System.IO.Packaging.Package.Open(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read))
            {
                System.IO.Packaging.PackagePart documentPart = null;
                Uri documentUri = null;

                //  Get the main document part (workbook.xml).
                foreach (System.IO.Packaging.PackageRelationship relationship in xlPackage.GetRelationshipsByType(documentRelationshipType))
                {
                    //  There should only be one document part in the package.
                    documentUri = System.IO.Packaging.PackUriHelper.ResolvePartUri(new Uri("/", UriKind.Relative), relationship.TargetUri);
                    documentPart = xlPackage.GetPart(documentUri);
                    //  There should only be one instance,
                    //  but get out no matter what.
                    break;
                }

                if (documentPart != null)
                {
                    // Load the contents of the workbook.
                    System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                    doc.Load(documentPart.GetStream());
                    //  Create a namespace manager, so you can search.
                    //  Add a prefix (d) for the default namespace.
                    System.Xml.NameTable nt = new System.Xml.NameTable();
                    System.Xml.XmlNamespaceManager nsManager = new System.Xml.XmlNamespaceManager(nt);
                    nsManager.AddNamespace("d", worksheetSchema);
                    nsManager.AddNamespace("s", sharedStringSchema);

                    string searchString = string.Format("//d:sheet[@name='{0}']", sheetName);
                    System.Xml.XmlNode sheetNode = doc.SelectSingleNode(searchString, nsManager);
                    if (sheetNode != null)
                    {
                        //  Get the relId attribute:
                        System.Xml.XmlAttribute relationAttribute = sheetNode.Attributes["r:id"];
                        if (relationAttribute != null)
                        {
                            string relId = relationAttribute.Value;

                            //  First, get the relation between the
                            // document and the sheet.
                            System.IO.Packaging.PackageRelationship sheetRelation = documentPart.GetRelationship(relId);
                            Uri sheetUri = System.IO.Packaging.PackUriHelper.ResolvePartUri(documentUri, sheetRelation.TargetUri);
                            System.IO.Packaging.PackagePart sheetPart = xlPackage.GetPart(sheetUri);

                            //  Load the contents of the workbook.
                            System.Xml.XmlDocument sheetDoc = new System.Xml.XmlDocument(nt);
                            sheetDoc.Load(sheetPart.GetStream());

                            System.Xml.XmlNode cellNode = sheetDoc.SelectSingleNode(string.Format("//d:sheetData/d:row/d:c[@r='{0}']", addressName), nsManager);
                            if (cellNode != null)
                            {
                                //  Retrieve the value. The value may be stored within
                                //  this element. If the "t" attribute contains "s", then
                                //  the cell contains a shared string, and you must look
                                //  up the value individually.
                                System.Xml.XmlAttribute typeAttr = cellNode.Attributes["t"];
                                string cellType = string.Empty;
                                if (typeAttr != null)
                                {
                                    cellType = typeAttr.Value;
                                }

                                System.Xml.XmlNode valueNode = cellNode.SelectSingleNode("d:v", nsManager);
                                if (valueNode != null)
                                {
                                    cellValue = valueNode.InnerText;
                                }

                                //  Check the cell type. At this point, this code only checks
                                //  for booleans and strings individually.
                                if (cellType == "b")
                                {
                                    if (cellValue == "1")
                                    {
                                        cellValue = "TRUE";
                                    }
                                    else
                                    {
                                        cellValue = "FALSE";
                                    }
                                }
                                else if (cellType == "s")
                                {
                                    //  Go retrieve the actual string from the associated string file.
                                    foreach (System.IO.Packaging.PackageRelationship stringRelationship in documentPart.GetRelationshipsByType(sharedStringsRelationshipType))
                                    {
                                        //  There should only be one shared string reference,
                                        // so you exit this loop immediately.
                                        Uri sharedStringsUri = System.IO.Packaging.PackUriHelper.ResolvePartUri(documentUri, stringRelationship.TargetUri);
                                        System.IO.Packaging.PackagePart stringPart = xlPackage.GetPart(sharedStringsUri);
                                        if (stringPart != null)
                                        {

                                            //  Load the contents of the shared strings.
                                            System.Xml.XmlDocument stringDoc = new System.Xml.XmlDocument(nt);
                                            stringDoc.Load(stringPart.GetStream());

                                            //  Add the string schema to the namespace manager:
                                            nsManager.AddNamespace("s", sharedStringSchema);

                                            int requestedString = Convert.ToInt32(cellValue);
                                            string strSearch = string.Format("//s:sst/s:si[{0}]", requestedString + 1);
                                            System.Xml.XmlNode stringNode = stringDoc.SelectSingleNode(strSearch, nsManager);
                                            if (stringNode != null)
                                            {
                                                cellValue = stringNode.InnerText;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                return cellValue;
            }

Currently rated 3.0 by 2 people

  • Currently 3/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

c# | OpenXml

How to get sheet name(s) from OpenXml document (Excel 2007)

by admin 17. June 2008 14:28

Below you'll find code snippet for reading Excel Sheet names from Office 2007 Excel document

public static List<string> GetSheetInfo(string fileName)
        {
            //  Fill this collection with a list of all the sheets.
            List<string> sheets = new List<string>();

            using (Microsoft.Office.DocumentFormat.OpenXml.Packaging.SpreadsheetDocument xlPackage = Microsoft.Office.DocumentFormat.OpenXml.Packaging.SpreadsheetDocument.Open(fileName, false))
            {
                Microsoft.Office.DocumentFormat.OpenXml.Packaging.WorkbookPart workbook = xlPackage.WorkbookPart;
                System.IO.Stream workbookstr = workbook.GetStream();
                System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                doc.Load(workbookstr);

                System.Xml.XmlNamespaceManager nsManager = new System.Xml.XmlNamespaceManager(doc.NameTable);
                nsManager.AddNamespace("default", doc.DocumentElement.NamespaceURI);
                System.Xml.XmlNodeList nodelist = doc.SelectNodes("//default:sheets/default:sheet", nsManager);

                foreach (System.Xml.XmlNode node in nodelist)
                {
                    string sheetName = string.Empty;
                    sheetName = node.Attributes["name"].Value;
                    sheets.Add(sheetName);
                }
            }
            return sheets;
        }

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

c# | OpenXml

An attempt was made to access a socket in a way forbidden by its access permissions

by admin 5. June 2008 14:25

When I'm trying to access network socket on Vista it's throwing this exception:

An attempt was made to access a socket in a way forbidden by its access permissions

The only workaround I found so far is to run application as Administrator. The code to reproduce it goes like this:

System.Net.Sockets.Socket socket = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Raw, System.Net.Sockets.ProtocolType.Icmp);

Anyone knows the answer for this problem?

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

c# | Vista

How to verify that string is in valid e-mail format

by admin 16. April 2008 22:35

The following code uses the static Regex.IsMatch method to verify that a string is in valid e-mail format.

The IsValidEmail method returns true if the string contains a valid e-mail address and false if it does not, but takes no other action.

You can use IsValidEmail to filter out e-mail addresses containing invalid characters before your application stores the addresses in a database or displays them in an ASP.NET page.

bool IsValidEmail(string email)
{

     return System.Text.RegularExpressions.Regex.IsMatch(email, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
}

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

asp.net | c# | Regex

Reading web.config configuration section

by admin 10. April 2008 08:27

Code below helped when I wanted to read customErrors configuration section from web.config.  

System.Configuration.Configuration configuration = System.Web.Configuration.WebConfigurationManager"~");
System.Web.Configuration.CustomErrorsSection section = (System.Web.Configuration.CustomErrorsSection)configuration.GetSection("system.web/customErrors");

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

asp.net | c#

Powered by BlogEngine.NET 1.4.5.0
Theme by Mads Kristensen

Calendar

<<  March 2010  >>
MoTuWeThFrSaSu
22232425262728
1234567
891011121314
15161718192021
22232425262728
2930311234

View posts in large calendar