Solving: A generic error occurred in GDI+. in C#

I was creating an image in C# by using code similar to:

public void SaveImage()
{
byte[] byteArray = null; // Put the bytes of the image here....
Image result = null;
ImageFormat format = ImageFormat.Png;
using (MemoryStream ms = new MemoryStream(byteArray))
{
result = Image.FromStream(ms);
}
using (Image imageToExport = result)
{
string filePath = string.Format(@"C:\Temp\Myfile.{0}", format.ToString());
imageToExport.Save(filePath, format);
}
}

This resulted in the error: "A generic error occurred in GDI+."

 

The error was resolved, after changing the code to:

public void SaveImage()
{
byte[] byteArray = null; // Put the bytes of the image here....
Image result = null;
ImageFormat format = ImageFormat.Png;
  result = new Bitmap(new MemoryStream(byteArray));


using (Image imageToExport = result)
{
string filePath = string.Format(@"C:\Temp\Myfile.{0}", format.ToString());
imageToExport.Save(filePath, format);
}
}

 

I found the solution at: http://stackoverflow.com/questions/1053052/a-generic-error-occurred-in-gdi-jpeg-image-to-memorystream

Solving: Windows Authentication fails, when using a host header and accessing IIS on the local box.

If you are developing an ASP .NET website that uses Windows Authentication and add a host header in IIS to the ASP .NET web application, accessing the site on the local box, might not work. Windows Authentication will fail if the loopback check is not disabled. By default, loopback check functionality is turned on in Windows Server 2003 SP1 and later. So if you add an entry to the Windows hosts file, found in [C:\Windows\System32\drivers\etc], like:

127.0.0.1     dev.com

And access the ASP .NET web application on the local box, by using the hostheader: http://dev.com/MyWebApplicaiton/Default.aspx make sure the loopback check is disabled:

 

  1. Click Start, click Run, type regedit, and then click OK.
  2. Locate and then click the following registry subkey: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa
  3. Right-click Lsa, point to New, and then click DWORD Value.
  4. Type DisableLoopbackCheck, and then press ENTER.
  5. Right-click DisableLoopbackCheck, and then click Modify.
  6. In the Value data box, type 1, and then click OK.
  7. Exit Registry Editor.
  8. Restart the computer. Note You must restart the server for this change to take effect

 

image

Solving: HttpContext.Current.User.Identity.Name is empty, when using Windows Authentication.

If you want to use Windows Authentication in your ASP .NET website, you need to add the <authentication mode="Windows"/> tag in the Web.config.

<system.web>
<authentication mode="Windows"/>

If the HttpContext.Current.user.Identity.Name is still empty. Check the authentication feature of the web application in IIS, make sure all authentication mechanisms are Disabled, except for the Windows Authentication, this should be set to Enabled.

 

image

 

image

Transforming an input file to an output file in C#, by using XSLT.

Just a code snippet for transforming an input file to an output file in C# by using XSLT:

/// <summary>
/// Transform an input file to an output file, by using XSLT.
/// </summary>
public void ExecuteTransform()
{
string xsltFilePath = @"C:\BDATA\Transform.xsl";
string sourceFilePath = @"C:\BDATA\input.xml";
string destinationFilePath = @"C:\BDATA\output.xml";
var transform = new XslCompiledTransform();
transform.Load(xsltFilePath);
transform.Transform(sourceFilePath, destinationFilePath);
}

How to convert a byte[] to an image in C# by using an extension method.

To convert a byte array to an image in C#, you can use the following code:

[TestMethod]
public void Test()
{
byte[] bytes = new byte[100]; // Supply your bytes here. 
Image image = bytes.ToImage();
}
using System.Drawing;
using System.IO;
namespace Services.Extensions
{
/// <summary>
/// Contains extensions methods to the byte[] type.
/// </summary>
public static class ByteArrayExtensions
{
/// <summary>
/// Creates an images, based on the given bytes.
/// </summary>
/// <param name="image">The image.</param>
/// <param name="byteArray">The byte array.</param>
/// <returns></returns>
public static Image ToImage(this byte[] byteArray)
{
return new Bitmap(new MemoryStream(byteArray));
}
}
}

How to: Convert an Image to a byte array in C#, by using a extension method.

If you want to convert an Image to a byte array in C#, you can use the following extension method:

 

[TestMethod]
public void Test()
{
Image image = null; // Supply your image here.
byte[] bytes = image.ToBytes();
}
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
namespace Services.Extensions
{
/// <summary>
/// Extensions to the [System.Drawing.Image] class
/// </summary>
public static class ImageExtensions
{
/// <summary>
/// Converts an image to an array of bytes.
/// </summary>
/// <param name="image">The image.</param>
/// <returns></returns>
public static byte[] ToBytes(this Image image)
{
byte[] result = null;
using (var stream = new MemoryStream())
{
image.Save(stream, image.RawFormat as ImageFormat);
result = stream.ToArray();
}
return result;
}
}
}

How to serialize an object to string and deserialize a string back to an object in C# 4.0

If you want to serialize an object to a string or want to deserialize a string back to an object, you can use the following class:

 

The XmlSerializationTask class

using System;
using System.IO;
using System.Text;
using System.Xml.Serialization;
namespace Rvl.NewCode.Test.Task
{
/// <summary>
/// This class is used for serializing a object to string and back.
/// </summary>
/// <typeparam name="T"></typeparam>
public class XmlSerializationTask<T> where T : class, new()
{
/// <summary>
/// Use this property for types that are unkown at compiletime.
/// </summary>
public Type[] ExtraTypes { get; set; }
/// <summary>
/// Serializes the object to string.
/// </summary>
/// <param name="source">The source.</param>
/// <returns></returns>
public string SerializeObjectToString(T source)
{
StringBuilder result = new StringBuilder(string.Empty);
using (StringWriter writer = new StringWriter(result))
{
XmlSerializer xs = new XmlSerializer(typeof(T), ExtraTypes);
xs.Serialize(writer, source);
}
return result.ToString();
}
/// <summary>
/// Deserializes from string.
/// </summary>
/// <param name="source">The source.</param>
/// <returns></returns>
public T DeserializeFromString(string source)
{
T result;
using (StringReader reader = new StringReader(source))
{
XmlSerializer xs = new XmlSerializer(typeof(T), ExtraTypes);
result = xs.Deserialize(reader) as T;
}
return result;
}
}
}

 

Using the XmlSerializationTask class

public void TestXmlSerializationTask()
{
// DynamicTask, is just a class I created with 3 properties:
var dynamicTask = new DynamicTask 
{ 
Id = Guid.NewGuid(), 
AssemlbyPath= Environment.NewLine, 
TypeDescription="Test" 
};
var serializeTask = new XmlSerializationTask<DynamicTask>();
string serializedObject = serializeTask.SerializeObjectToString(dynamicTask);
DynamicTask newDynamicTask = serializeTask.DeserializeFromString(serializedObject);
}

Produced XML

<?xml version="1.0" encoding="utf-16"?>

<DynamicTask xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">

  <Id>5b1c6ca4-a8a3-46fc-8496-8caa8c37a47f</Id>

  <AssemlbyPath>C:\Temp\Test.dll</AssemlbyPath>

  <TypeDescription>Test</TypeDescription>

</DynamicTask>

How to: Adjust C# assembly probing path at runtime.

When a assembly is not found, when using the standard probing method, an assembly resolve event is fired, allowing to load the assembly from a different file system path:

 

public void Test()
{
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.AssemblyResolve += new ResolveEventHandler(LoadFromSameFolder);
}
public static Assembly LoadFromSameFolder(object sender, ResolveEventArgs args)
{
string folderPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string assemblyPath = Path.Combine(folderPath, string.Format("{0}.dll", new AssemblyName(args.Name).Name));
if (!File.Exists(assemblyPath))
{
assemblyPath = Path.Combine(folderPath, string.Format("{0}.exe", new AssemblyName(args.Name).Name));
if (!File.Exists(assemblyPath))
{
return null;
}
}
Assembly assembly = Assembly.LoadFrom(assemblyPath);
return assembly;
}

How to deserialize an object containing collections from an App.config or Web.config in .NET 4.0 and C#

Let says you want to store your application settings in an App.config or Web.config file and these settings should contain collections of settings, then use can use the following code to deserialize an object containing these settings from an App.config or Web.config. By using deserialization the object can contain any type that’s serializable.

 

The App.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="ApplicationSettings" type="Rvl.NewCode.Test.BC.ApplicationSettings, Rvl.NewCode.Test" />
</configSections>
<ApplicationSettings>
<Id>12</Id>
<CarTypes>
<string>Audi</string>
<string>BMW</string>
<string>Mercedes</string>
</CarTypes>
</ApplicationSettings>
</configuration>

 

The code to deserialize the object from the App.config file

ApplicationSettings settings = new ApplicationSettings();
settings.InitializeFromAppConfig();

After running this code the settings object, contains the data:

image

 

The ApplicationSettings class

using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace Rvl.NewCode.Test.BC
{
public class ApplicationSettings : IConfigurationSectionHandler
{
public int Id { get; set; }
public List<string> CarTypes { get; set; }
/// <summary>
/// Creates a configuration section handler.
/// </summary>
/// <param name="parent">Parent object.</param>
/// <param name="configContext">Configuration context object.</param>
/// <param name="section">Section XML node.</param>
/// <returns>
/// The created section handler object.
/// </returns>
public object Create(object parent, object configContext, System.Xml.XmlNode section)
{
return section;
}
/// <summary>
/// Initialize this object from app config.
/// </summary>
public void InitializeFromAppConfig()
{
XmlElement settingsXmlElement       = GetXmlElementFromAppConfig();
ApplicationSettings settings    = DeserializeFromXmlElement(settingsXmlElement);
CopyDataToCurrentObject(settings);
}
/// <summary>
/// Gets the XML element from app config.
/// </summary>
/// <returns>
/// The found xml element.
/// </returns>
private XmlElement GetXmlElementFromAppConfig()
{
string tagName = this.GetType().Name;
XmlElement sectionElement = ConfigurationManager.GetSection(tagName) as XmlElement;
if (sectionElement == null)
{
throw new ApplicationException(string.Format("Could not find section [{0}] in the App.config file.", tagName));
}
return sectionElement;
}
/// <summary>
/// Convert the given XML element to a ScheduleServiceSettings object.
/// </summary>
/// <param name="sectionElement">The XML element containing the information to create a ScheduleServiceSettings object.</param>
/// <returns>A ScheduleServiceSettings object</returns>
private ApplicationSettings DeserializeFromXmlElement(XmlElement sectionElement)
{
ApplicationSettings settings = null;
using (StringReader reader = new StringReader(sectionElement.OuterXml))
{
XmlSerializer xs    = new XmlSerializer(typeof(ApplicationSettings));
settings            = xs.Deserialize(reader) as ApplicationSettings;
}
return settings;
}
/// <summary>
/// Copy the data found in the ScheduleServiceSettings object to the current object
/// </summary>
/// <param name="settings"></param>
private void CopyDataToCurrentObject(ApplicationSettings settings)
{
Id = settings.Id;
CarTypes = settings.CarTypes;
}
}
}

How to solve: The type or namespace name ‘log4net’ could not be found in .NET 4.0?

 

If you create a new .NET 4.0 console application in Microsoft Visual Studio .NET 2010 and add a reference to the Log4Net v1.2.10 dll, you can add the using statement [using log4net;], but after a rebuild, Microsoft Visual Studio still reports the error:

Error    29    The type or namespace name ‘log4net’ could not be found (are you missing a using directive or an assembly reference?)

This is caused by the [Target framework] is set to the [.NET Framework 4 Client Profile]. This profile does not include some .NET assemblies found in the Full .NET Framework, that are used by log4net.

image

 

As can be seen with RegGate Reflactor, log4net uses Full .NET Framework assemblies:

image

 

Solution

Set the [Target framework] of your application to [.NET Framework 4].

image