Cannot modify members of ‘item’ because it is a ‘foreach iteration variable’

 I had a compile time issue with using my custom list. The code simply looks like the following:

 

foreach (ItemType item in listOfItems)

    item.CustomAccessor = "value";

 

And compiler complains with error:

            Cannot modify members of ‘item’ because it is a ‘foreach iteration variable’

 

This is because the ItemType is defined as a  struct and not as a class. Doing so the iteration of foreach will result to some copies of the heap that are not reflecting the real objects. The question that has often been asked is why did you define your ItemType as struct and not as a class…. which I will answer it in other discussion.

  

Attributes to consider applying when writing a custom control

The original author published this : Eilon Lipton’s Blog

 

Almost every custom control has at least one additional public property, and that public property as well as the control itself should probably have at least a few attributes applied to them. Attributes tell the designer host (Visual Studio) or the parser (ASP.NET) interesting things about your control that might not be evident from just its name and its type. Launch any decent class browser tool and you’ll see that every control that shipped in ASP.NET and ASP.NET AJAX has several attributes on it as well as their properties and events.

By applying the proper set of attributes you can significantly increase the usefulness of your control in several ways. For example, the DescriptionAttribute provides helpful text to the person designing the page. The ValidationPropertyAttribute is required when the person designing the page wants to validate the value of your control. Following is a list of the most useful and important attributes you can apply to your control and its properties and events.

Control attributes:

  • ControlValueProperty
     – Used by data source parameters to get the "intrinsic" value of the control. For example, DropDownList’s "intrinsic" value is its SelectedValue property.
  • DefaultEvent
     – Set the event for which to create an event handler when double clicking the control in the designer.
  • DefaultProperty
     – Set the default selected property in the designer’s property grid.
  • NonVisualControl
     – Hide the control at design time when "Non Visual Controls" is unchecked from the View menu.
  • ParseChildren
     – The full name is really "parse children as properties".
     – Set to true if the inner contents of the control represent properties as opposed to child controls.
     – True by default on controls deriving from WebControl; false by default otherwise.
  • PersistChildren
     – The full name is really "persist child controls".
     – Set to true if the designer should persist child controls as the inner contents.
     – False by default on controls deriving from WebControl; true by default otherwise.
     – 99.9% of the time PersistChildren has the opposite value of ParseChildren.
  • SupportsEventValidation
     – Indicates that the control’s client-side calls to __doPostBack() should be validated on the server for security purposes.
  • Themable
     – Indicates that by default all the control’s properties can be customized via themes. Individual properties can also be marked with this attribute to override the behavior.
     – True by default for controls that derive from WebControl.
  • ValidationProperty
     – Required when a control can be validated.
     – Somewhat similar to the ControlValueProperty in that they often point at the same property.
  • ViewStateModeById
     – Indicates that viewstate should be loaded based on control IDs as opposed to being loaded based on the index of the control in the child controls collection.

Property attributes:

  • Bindable
     – Indicates at design time only whether the property should appear by default in the Edit Databindings dialog.
  • Browsable
     – Indicates whether the property is visible in the property grid at design time.
  • Category
     – Determines in which category the property will appear when the property grid is in category mode.
  • DefaultValue
     – Get-only property: Since get-only properties are never persisted anyway, no default value is needed.
     – Get/Set value type property: Must be set.
     – Get/Set reference type property: Must be null so that it shows up as non-bold in the property grid.
  • Description
     – Determines the help text that will show in the property grid’s lower help panel.
  • DesignerSerializationVisibility
     – Controls whether the property is persisted in the markup (see also PersistenceMode).
     – Use this to prevent get/set properties from being persisted at all.
  • EditorBrowsable
     – Affects whether the property appears in Intellisense.
  • IDReferenceProperty
     – Specifies that the property represents a control ID, and optionally the type of the target control. Not used by Visual Studio 2005.
  • MergableProperty
     – Affects whether the property shows up in the property grid when multiple controls are selected.
     – If the property is Browsable and is a reference type then set Mergable=false (except immutable reference types, such as string).
  • PersistenceMode
     – Controls how the property is persisted in the markup.
     – Simple-valued properties should use the default, which is Attribute.
     – Collection, template, and complex (e.g. styles) should use InnerProperty.
     – InnerDefaultProperty should never be used since it causes compatibility problems. For example, if in the next version of your control you want another inner property, it won’t work properly.
     – EncodedInnerDefaultProperty should also rarely be used for similar reasons as InnerDefaultProperty.
     – In ASP.NET 2.0 support was added for strings to be InnerProperties, which is good for large multi-line string values, such as XmlDataSource’s Data property.
  • Themable
     – Overrides the value of the attribute on the control to determine whether the property can be customized via themes.

Event attributes:

  • Browsable
     – Same as properties.
  • Category
     – Same as properties.
  • Description
     – Same as properties.
  • EditorBrowsable
     – Same as properties.

 

Customize attachment settings in outlook

I got a mail in my outlook and the application didn't let me open the attachment because it might be unsecure. The mail was from a know person and I want to access the attachment file. It appears that you can override the security level as described by Microsoft ( Customize attachment settings in Outlook 2007) and let some file types allowed to be opened.
 
To do this you have to tell the outlook which types of files are allowed. You do it in the registry:
HKCUSoftwareMicrosoftOffice12.0OutlookSecurityLevel1Remove
 
You simply mention the extentions seporated by a semicolon like this one :
pts;bat;reg;vbs
 
 

Read/Write files from/to an Image field in SQL-Server

In this example I have a table called Attachment having a field of time Image which holds binary value. In this field I am going to put any type of file in a byte array and read it back. I have defined a class called Attachment to read and write the records. This class has a variable called Data which is defined as byte[]

Read Image Field

This example passes a reference to an object called record of type Attachment. The record object has an attribute called Data where the attachment file will be streamed into it.

/// <summary>
/// Read a TestLog record identified by the given parameter
/// </summary>
/// <param name="id">the record key</param>
/// <returns>a Attachment object that maps to the record</returns>
public static void Read(Attachment record)
{


if (record.Id < 1)
throw new ApplicationException("Invalid Record ID");

using (SqlConnection sqlConnection1 = Connection)
{
SqlCommand cmd
= sqlConnection1.CreateCommand();
cmd.CommandType
= CommandType.Text;
cmd.CommandText
= "SELECT TestLogId, Name, Description, CreatedBy, CreateDate, Data FROM Attachment WHERE ID=@Id";

SqlParameter par
= new SqlParameter("@Id", SqlDbType.Int);
par.Value
= record.Id;
cmd.Parameters.Add(par);


sqlConnection1.Open();
SqlDataReader dr
= cmd.ExecuteReader();
if (!dr.HasRows)
throw new ApplicationException(String.Format("Could not find TestLog '{0}'.", record.Id));

dr.Read();

if (!dr.IsDBNull(0))
record.TestLogID
= dr.GetInt32(0);
if (!dr.IsDBNull(1))
record.Name
= dr.GetString(1).TrimEnd();
if (!dr.IsDBNull(2))
record.Description
= dr.GetString(2).TrimEnd();
if (!dr.IsDBNull(3))
record.CreatedBy
= dr.GetString(3).TrimEnd();
if (!dr.IsDBNull(4))
record.CreateDate
= dr.GetDateTime(4);

// Read the bytes into the Data attribute of the record
int PictureCol = 5; // the column # of the BLOB field
record.Data = new Byte[(dr.GetBytes(PictureCol, 0, null, 0, int.MaxValue))];
dr.GetBytes(PictureCol,
0, record.Data, 0, record.Data.Length);

dr.Close();
sqlConnection1.Close();
}
}

Write File into the record

/// <summary>
/// Save the Attachment record. If Id doesn't exist, it will create a new one, otherwise it will update.
/// </summary>
/// <param name="record">the attachment record to save</param>
public static void Save(Attachment record)
{

using (SqlConnection sqlConnection1 = Connection)
{
SqlCommand cmd
= sqlConnection1.CreateCommand();
cmd.CommandType
= CommandType.StoredProcedure;
cmd.CommandText
= "SaveAttachment";

#region Add the input parameter and set its value

SqlParameter par
= new SqlParameter("@TestLogId", SqlDbType.Int);
par.Value
= record.TestLogID;
cmd.Parameters.Add(par);

par
= new SqlParameter("@Name", SqlDbType.NVarChar, 128);
par.Value
= record.Name;
cmd.Parameters.Add(par);

par
= new SqlParameter("@Description", SqlDbType.NVarChar, 320);
par.Value
= record.Description;
cmd.Parameters.Add(par);

par
= new SqlParameter("@Data", SqlDbType.VarBinary, record.Data.Length);
par.Value
= record.Data;
cmd.Parameters.Add(par);

#endregion

// Add the output parameter
par = new SqlParameter("@Id", SqlDbType.Int, 4);
par.Direction
= ParameterDirection.InputOutput;
par.Value
= record.Id;
cmd.Parameters.Add(par);

sqlConnection1.Open();
cmd.ExecuteNonQuery();
int id = Int32.Parse(cmd.Parameters["@ID"].Value.ToString());
record.Id
= id;
sqlConnection1.Close();
}
}

Read the file into the variable

/// <summary>
/// Read the file into the Data field
/// </summary>
/// <param name="path">A valid path to the file</param>
public void ReadFromFile(string path)
{
System.IO.FileStream fs
=
new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read);

this.data = new Byte[fs.Length];
fs.Read(
this.data, 0, this.data.Length);
fs.Close();
}

Write the byte array to a File

This simple method is using the name of the file as is stored in the attachment record to save in the location specified by parameter.

/// <summary>
/// Save the content into a file
/// </summary>
/// <param name="path">the full path to write to</param>
public void SaveToFile(string path)
{
if (path.EndsWith("\"))
path
+= "\";

string DestFilePath = path + this.name;
System.IO.FileStream fs
=
new System.IO.FileStream(DestFilePath, System.IO.FileMode.Create, System.IO.FileAccess.Write);

fs.Write(
this.data, 0, this.data.Length);
fs.Close();

}

Welcome

I have lost my blogs that I used to store on http://blogs.wdevs.com/a.Panahy/ The site is just gone down and made me desporate. I decided to start my own. Thanks to NiMS I got this subdomain up and running in short time and the idea is to build up my personal blogs in this blog site.
The site will start with my technical blogs to support my (leaking) memory. I might have a copy of them on other online site (maybe on codeproject.com or msn.Live) and later on probably some private blogs.
for now all I want to say is yoopy