Archive for the 'Simple Things' Category

08
Sep
10

Changing log4net log file path via code

Sometimes we might have to place the log files away from the location where the application is installed. And lo there is an option to do that! In the config file create a variable like below

<file type="log4net.Util.PatternString" value="%property{SomeVariable}log.txt" />

And in the code, before calling log4net configure, set the new path to the Variable

log4net.GlobalContext.Properties["SomeVariable"] = YourNewPath;
log4net.Config.XmlConfigurator.Configure();

Simple isn’t it Smile

20
Apr
10

Team foundation server 2010 RTM installation steps, errors and workarounds

If you are planning to install Team Foundation Server on fresh Windows Server 2008 machine follow these steps which I was able to achieve after good number of trail and errors

Hope it saves somebody few frustrating hours :)

24
Mar
10

remove objects from an Enumerable collection in a loop

If you are trying to remove an object from a list that you are currently iterating through like below,

foreach (MyObject myObject in MyListOfMyObjects)
{
     if (condition) MyListOfMyObjects.Remove(myObject);
}

you will get an error message that you cannot do it.

Best alternative is to create a copy of the object and loop through it and remove from main object

foreach (MyObject myObject in new List<MyObject>(MyListOfMyObjects))
{
     if (condition) MyListOfMyObjects.Remove(myObject);
}

Simple isn’t it :)

Source : StackOverflow

12
Mar
10

xml schema generation, serialization & deserialization explained

Lets consider a simple xml named as sample.xml. This can be an xml that you are getting as a output of webservice, a function or just a plain file that you might read in your application.

<users>
    <user>
        <id>1</id>
        <name>asdf</name>
        <fullname>asdf,asdf</fullname>
    </user>
    <user>
        <id>2</id>
        <name>qwer</name>
        <fullname>qwer,qwer</fullname>
    </user>
</users>

Lets create a XML Schema aka XSD file

Open ‘Visual Studio 2008 Command Prompt’ and type in

xsd sample.xml

This will generate sample.xsd file in the folder where you are currently running this command from. Below is how it looks.

<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="users" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
  <xs:element name="users" msdata:IsDataSet="true" msdata:UseCurrentLocale="true">
    <xs:complexType>
      <xs:choice minOccurs="0" maxOccurs="unbounded">
        <xs:element name="user">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="id" type="xs:string" minOccurs="0" />
              <xs:element name="name" type="xs:string" minOccurs="0" />
              <xs:element name="fullname" type="xs:string" minOccurs="0" />
            </xs:sequence>
          </xs:complexType>
        </xs:element>
      </xs:choice>
    </xs:complexType>
  </xs:element>
</xs:schema>

Lets create a class for serialization of xml file

xsd sample.xsd /classes /language:cs

This will generate sample.cs file. By default in the generated file, the collection used is Array.

private usersUser[] itemsField;

Lets use ObservableCollection as it is a generic dynamic data collection that provides notifications (using an interface "INotifyCollectionChanged") when items get added, removed, or when the whole collection is refreshed.

Below is how the modified class file looks like.

//——————————————————————————
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:2.0.50727.3607
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//——————————————————————————

using System.Xml.Serialization;
using System.Collections.ObjectModel;

//
// This source code was auto-generated by xsd, Version=2.0.50727.1432.
//

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.1432")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
public partial class users {

    private ObservableCollection<usersUser> itemsField;
    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("user", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public ObservableCollection<usersUser> Items
    {
        get {
            return this.itemsField;
        }
        set {
            this.itemsField = value;
        }
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.1432")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class usersUser {
    private string idField;
    private string nameField;
    private string fullnameField;
    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string id {
        get {
            return this.idField;
        }
        set {
            this.idField = value;
        }
    }
    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string name {
        get {
            return this.nameField;
        }
        set {
            this.nameField = value;
        }
    }
    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string fullname {
        get {
            return this.fullnameField;
        }
        set {
            this.fullnameField = value;
        }
    }
}

Lets read a file from file system [ Serialization ]. Below is the sample code for doing so

System.Windows.Forms.OpenFileDialog ofd = new System.Windows.Forms.OpenFileDialog();
ofd.Multiselect = false;
ofd.Filter = "XML File|*.xml";
if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
    try
    {
        if (File.Exists(ofd.FileName))
        {
        XmlSerializer deserializer = new XmlSerializer(typeof(users));
        TextReader textReader = new StreamReader(ofd.FileName);
        objUsers = new users();
        objUsers = (users)deserializer.Deserialize(textReader);
        textReader.Close();  
        }
    }
    catch
    {
        MessageBox.Show("Not a valid file");
    }
}

To add a new user, below is the sample code

usersUser newuser = new usersUser();
newuser.id = "3";
newuser.name = "zxcv";
newuser.fullname = "zxcv,zxcv";
if (objUsers == null)
    objUsers= new users();
objUsers.Items.Add(newuser);

Lets write a xml file from the objects that we have created [ Deserialization ]. Below is the sample code for doing so

if (objUsers == null)
    objUsers = new users();
SaveFileDialog dlg = new SaveFileDialog();
dlg.FileName = "New";
dlg.DefaultExt = ".xml";
dlg.Filter = "XML file|*.xml";
Nullable<bool> result = dlg.ShowDialog();
if (result == true)
{
    string filepath = dlg.FileName;
    XmlSerializer serializer = new XmlSerializer(typeof(users));
    TextWriter textWriter = new StreamWriter(filepath);
    serializer.Serialize(textWriter, objUsers);
    textWriter.Close();
}          

Simple isn’t it :)

Sample code explained in this post is available here

14
Jan
10

VS 2010 beta 2 opening applications with error : MSB3134

When you open an already existing full trust application in Visual Studio 2010 beta 2, you might encounter this error after the first build.

MSB3134: The permission set requested by the application exceeded the permissions allowed by the Internet or Intranet zones. Select Full Trust or to continue using partial trust, define your custom permission set in the Security Page of the Project Designer.

This error and the rationale behind it is explained by Kristopher Makey here.

Unfortunately, fix is not clear. Solution is as below.

  • Open <Application>/Properties/app.manifest
  • Remove everything between <security> tag
  • Go to Application Properties > Security tab. Select the permission as ‘Full trust’ and save and compile.

Simple Isn’t it :)

02
Dec
09

URL encode decode reference

I was looking for url encoding and decoding reference and found this cool resource.. http://www.w3schools.com/TAGS/ref_urlencode.asp

In C# to encode or decode string Uri.EscapeDataString and Uri.UnescapeDataString :)

26
Nov
09

enabling Async methods for wcf in wpf

By default when you add a WCF Service reference in WPF, it does not give async functions. If your application needs async features, while adding a reference to the service, lookout for a ‘Advanced’ button on Add service reference window at bottom right corner. On clicking on that button, a new window appears. There is a checkbox called ‘Generate Asynchronous Operations’. Hit Ok and you are done!

Simple isn’t it :)

25
Nov
09

custom setting tab order in wpf application

For the framework element set KeyboardNavigation.TabIndex="<number goes here>"

Simple isn’t it?

24
Nov
09

if you need to send more data to wcf service

For example, you need to upload log file in case of error from desktop application to remote site using WCF service and if the log file is too big, you might have to tweak your WCF service’s Web.config.

By default the configuration for the service will be

      <services>
            <service behaviorConfiguration="ServiceBehavior" name="Service">
                <endpoint address="" binding="basicHttpBinding" contract="IService">
                </endpoint>
                <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
            </service>
        </services>

You need to specify the binding manually and add binding reference as highlighted below.   

 

    <services>
            <service behaviorConfiguration="ServiceBehavior" name="Service">
                <endpoint address="" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IService" contract="IService">
                </endpoint>
                <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
            </service>
        </services>
        <bindings>
                <basicHttpBinding>
                    <binding name="BasicHttpBinding_IService" closeTimeout="00:01:00"
                        openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
                        allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
                        maxBufferSize="2147483647" maxBufferPoolSize="2147483647"
                        maxReceivedMessageSize="2147483647" messageEncoding="Text"
                        textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true">
                        <readerQuotas maxDepth="32" maxStringContentLength="2147483647"
                            maxArrayLength="2147483647" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
                        <security mode="None">
                            <transport clientCredentialType="None" proxyCredentialType="None"
                                realm="" />
                            <message clientCredentialType="UserName" algorithmSuite="Default" />
                        </security>
                    </binding>
                </basicHttpBinding>
            </bindings>

That’s it :) Simple isn’t it?

16
Nov
09

multiline textbox in wpf

As a windows forms application/web application developer you might be looking for MultiLine property while developing in WPF. You will be surprised to see that there is no property like that.

Trick is you have to set AcceptsReturn="True" TextWrapping="Wrap" and VerticalScrollBarVisibility="Auto" to get yourself a multiline textbox




@pooran

 

May 2012
M T W T F S S
« Nov    
 123456
78910111213
14151617181920
21222324252627
28293031  

Visits so far..

  • 10,471

Follow

Get every new post delivered to your Inbox.