Archive for the ‘.NET’ Category

h1

Loading image for Full PostBack

April 7, 2009

Loading image should be use, when user is waiting to performing “long time” server action.

When you will look to the internet, than you will probably find a lot of Ajax which will not work for full postback correctly (it is correctly working for update panels but not for whole page).

Solution

  • Use javascript, and set visibility style of animated gif to hidden
  • However you’ll press control which executes “long running” action, set visibility and timeout of animated gif
  • When processing finish, animated gif will be disabled again.

Links

h1

Default values for FormView control in Insert mode

November 19, 2008

In many times we must assign default values to FormView in the insert mode. Problem is, that FW creates empty entity and this means empty FW.

Here is very short and powerful solution ;)

  • Add binding source to control which we want to set

    <asp:TextBox ID=”RateTextBox” runat=”server” Text=’<%# Bind(“Rate”) %> TabIndex=”24″ MaxLength=”5″ OnDataBinding=”InsertRateOnDataBinding />

  • Setting value to this control

    protected void InsertRateOnDataBinding(object sender, EventArgs e)
    {
      ((TextBox) sender).Text = RevertedOccupiedPercentage.ToString();
    }

h1

Global resources for validations (ASP .NET)

October 31, 2008

If you want to reuse expressions, error messages etc. for validators, you should use app.config storage or resources.

I will show you how to use resources for storing adjustments of ExpressionValidator .

  • Create Global resource directory

    1

  • Create GlobalResources – Call them ValidationResources.resx
    2 
  • Fill resources by expression and error message

    3

  • Add meta attribute  with resource resource name into your @Page directive on the page where you want to use resource.

    4

  • Add RegularExpressionValidator from toolbox and set it to resource values.

    5

  • If you want you can skip last step and you can set it in the designer

    6

  • Now run the application and look whats happening ;)

     7

h1

e.Cancel and update page

October 30, 2008

First at all I solved this f***ng problem than I found this forum.  My problem was, that I used FomView default setted to FormViewMode.Edit.  If I changed mode to Insert mode ,calling FomView.CahngeMode(FormViewMode.Insert), than  it worked fine. However I made mistake in FormView (bad typed price etc…) I validated data on server . After bad validation which I made in Inserting handled method of Object DataSource I called called e.Cancel.

It’s good idea but  result is, that updating of page is stopped => FormView will be setted to Edit mode, not to in insert Mode (prepared to pass data about new customer again). My solution of this is to set flag and set values of components in overrided prerender method.

 

//method blocks processing of updating page
private
void BlockCommandProcessing(ObjectDataSourceMethodEventArgs e, string message)
{
 
OnError(message);
 
e.Cancel = true;
 
_formviewWillBeVisibleAndInInsertMode = true;
}

//is setted when e.Cancel is called => we lost settings of page
//I will set it again in prerender phase
private bool _formviewWillBeVisibleAndInInsertMode;

protected
override void OnPreRender(EventArgs e)
{
if (_formviewWillBeVisibleAndInInsertMode)
    SetVisibilityOfItems(ControlStates.InsertClicked);
base.OnPreRender(e);
}

SetVisibility method sets FormView mode and visibilities of controls in depends of ControlState.

 

Links

 

 

h1

"Automatic sorting is only supported with DataView, DataTable, and DataSet" or else How to sort list in ObjectDataSource

October 7, 2008

 

When I wanted to sort GridView which used ObectDataSource I obtained exception Automatic sorting is only supported with DataView.  (WTF!! why?!)

 

So, becouse I changed my job I wanted to solve this problem ASAP.

First at all you should do is

  • make your universal Comparer.
  • Update data object for ObjectDataSource
  • Update code behind for your page
  • Update ASPX file – sortable columns + add ObjectDatasource parameters

UniversalComparer

 

/// <summary>
///
Provides universal comparing for particular UDT’s.
///
</summary>
///
<typeparam name=”T”></typeparam>
/// <example>listBO.Sort(new UniversalComparer<BO>(sortExpression, SortDirection.Ascending));
</example>
public class UniversalComparer<T> : IComparer<T>
{
private readonly string _sortExpression;
private readonly short _sortDirection;
public UniversalComparer(string expression, SortDirection sortDirection)
{
_sortExpression = expression;
_sortDirection = (short)sortDirection;
}

/// <summary>
///
Compares two objects and returns a value indicating whether one is less than, equal to, or greater than the other.
///
</summary>
/// <param name=”x”>The first object to compare.
</param>
/// <param name=”y”>The second object to compare.
</param>
///
<returns>
/// Value Condition Less than zero<paramref name=”x”/> is less than <paramref name=”y”/>.Zero<paramref name=”x”/> equals <paramref name=”y”/>.Greater than zero<paramref name=”x”/> is greater than <paramref name=”y”/>
.
///
</returns>
public int Compare(T x, T y)
{
if (string.IsNullOrEmpty(_sortExpression)) return 0;
Type t = x.GetType();
PropertyInfo pInfo = t.GetProperty(_sortExpression);
if (pInfo != null)
  return (_sortDirection) * Comparer.DefaultInvariant.Compare(pInfo.GetValue(x, null), pInfo.GetValue(y, null));
throw new NullReferenceException(string.Format(“Property doesn’t exists in the instance”));
}

 /// <summary>
///
Determinates direction of sorting.
///
</summary>
public enum
SortDirection
{
Ascending = 1,
Descending = -1
}
}

 

Update code behind for your page

Add delegated method which is calling when Sorting event is fired.

protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
ObjectDataSource1.SelectParameters["sortExpression"].DefaultValue = e.SortExpression;
ObjectDataSource1.SelectParameters["sortDirection"].DefaultValue = RevertSortDirection(ObjectDataSource1.SelectParameters["sortDirection"].DefaultValue);
e.Cancel = true;
}

/// <summary>
/// Reverts the sort direction, which is parsed from string. Return value and input parameters are in string format.
/// Values must be equal to Values of SortDirection enum.
/// </summary>
/// <param name=”sortDirectionString”>The sort direction string.</param>
/// <returns></returns>
private string RevertSortDirection(string sortDirectionString)
{
SortDirection sortDirection ;
if (string.IsNullOrEmpty(sortDirectionString))
sortDirection = SortDirection.Descending;
else
sortDirection = (SortDirection) Enum.Parse(typeof(SortDirection), sortDirectionString, false);
SortDirection direction = sortDirection == SortDirection.Ascending ? SortDirection.Descending : SortDirection.Ascending;
return Enum.GetName(typeof(SortDirection), direction);
}

 

e.Cancel = true – this is very important line which tell us, that firing event must be cancelled in this moment. In other words: It block  Automatic sorting is only supported with DataView error

 

Update DataSource of ObjectDataSource

In this part I will update SELECT for ObjectDataSource

public List<BO> GetBOs(string sortExpression, string sortDirection)
{
listBO.Add(new BO(10, “Kolar”));
listBO.Add(new BO(11, “Kopecky”));
listBO.Add(new BO(10, “Pavel”));
listBO.Add(new BO(12, “Banan”));
listBO.Add(new BO(14, “Opice”));

 if (!string.IsNullOrEmpty(sortExpression))
{
if (string.IsNullOrEmpty(sortDirection) || sortDirection.ToUpper() == “DESCENDING”)
listBO.Sort(new UniversalComparer<BO>(sortExpression, UniversalComparer<BO>.SortDirection.Ascending));
else
listBO.Sort(new UniversalComparer<BO>(sortExpression, UniversalComparer<BO>.SortDirection.Descending));
}
return listBO;
}

 

For Select method I am telling which column and how to sort.

 

Update ASPX ObjectdataSource + Grid

<form id=”form1″ runat=”server”>
<div
>
<asp:GridView ID=”GridView1″ runat=”server” AllowSorting=”True”
AutoGenerateColumns=”False” DataSourceID=”ObjectDataSource1″ Height=”241px” onsorting=”GridView1_Sorting” Width
=”396px”>
<Columns
>
<asp:BoundField DataField=”Name” HeaderText=”Name” SortExpression=”Name”
/>
<asp:BoundField DataField=”Id” HeaderText=”Id” SortExpression=”Id”
/>
</Columns
>
</asp:GridView
>
</div>

<asp:ObjectDataSource ID=”ObjectDataSource1″ runat=”server” SelectMethod=”GetBOs” TypeName=”BOListDataSource”>
<SelectParameters
>
<asp:Parameter Name=”sortExpression” Type=”string” Direction=”input”
/>
<asp:Parameter Name=”sortDirection” Type=”string” Direction=”input”
/>
</SelectParameters
>
</asp:ObjectDataSource
>
</form>

 

Links

h1

Timeout SQL problem when calling procedure

September 17, 2008

What happens  if you make some difficult stored procedure (SP) and call it by ADO for example in connected mode?? All code is just pseudo….

  • We have this code: 

    Command cmd = new  SqlCommand(“LongCall”,con)    ;
    cmd.CommandType = CmdType.StroredProcedure;
    cmd.ExecuteNonQuery();

 

  • We have this procedure
    CREATE  PROCEDURE  LongCall AS
      …….Inside of LongCall SP can be cascade calling of selects    
          SELECT * FROM ( SELECT * ……( SELECT *)  ) basically  something with huge complexity

What happened??  ExecuteNonQuery closes connection. Implicitly after 30 seconds.  So what you have to do?  
 

  • You can set TimeOut
    cmd.TimeOut = 100; //sets timeout to 100 seconds
     
  • You can disable Timeout
    cmd.Timeout = 0;  //calling of cmd.ExecuteNonQuery finish however LongCall ends.
     
  • You should call asynchronous ExecuteNonQuery
    IAsyncResult result = cmd.BeginExecuteReader(CommandBehavior.CloseConnection)
    while(!result.IsCompleted)
    {
      ….
    }
    cmd.EndExecuteReader();

     

  • Take a thing on your Stored Procedure LongCall. Can you degrease complexity??
    What about make a cache!! Use temporary  tables as much as you can.  Replace Views by selects etc…

http://www.csharphelp.com/archives4/archive640.html

h1

Gacutil

September 16, 2008

In this Article I want to just describe, where you can find your gacutil and how to write out your asseblies into the file.

I don’t know why, buut there are two gacutils:

  • C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\gacutil.exe
  • C:\WINDOWS\system32\dllcache\gacutil.exe

You can write out your GAC by gacutil.exe /L >> aaa.txt

Assemblies in the GAC you can find in hidden folder

  • C:\WINDOWS\assembly
h1

How to play sound in .NET

September 8, 2008

using System.Runtime.InteropServices;

namespace NotterdamDLX.DLX

{

/// <summary>
/// Summary description for Sound.
/// </summary>

   public class Sound

   {

[DllImport("winmm.dll")]

// play asynchronously

       public static extern long PlaySound(String lpszName, long hModule, long dwFlags);

// use file name

public static int SND_ASYNC    = 0×0001;   
       // purge non-static events

       public static int SND_FILENAME = 0×00020000;  

       public static int SND_PURGE    = 0×0040;    

 
       public Sound()      {}

      
      
public static void PlaySound(string fName)

       {

          PlaySound(fName, 0,SND_ASYNC |  SND_FILENAME );

       }

  }

}

h1

Easy serialization in c#

September 3, 2008

 

Following code works for general types without types which implememnts IDictionary. I’am serializing List<T> in my examples, but you can serialize all  types which contains [Serializable] attribute + implicit public constructor + public class of type.

 


Serialization

public static void Serialize<T>(T entity)
{
  
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
  
using (FileStream fstream = new FileStream(@”blabla.xml”, FileMode.Create, FileAccess.Write, FileShare.None))
  
{
        
xmlSerializer.Serialize(fstream, entity);
  
}
}

 

 

Deserialization

public static T Deserialize<T>()
{
  
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
  
T result;
  
using (FileStream fstream = new FileStream(@”blabla.xml”, FileMode.Open, FileAccess.Read, FileShare.None))
  
{
      
result = (T)xmlSerializer.Deserialize(fstream);
  
}
  
return result;
}

 

Calling code

Serialize<List<Aaa>>(list);

List<Aaa> list2 = Deserialize<List<Aaa>>();

 

h1

Security settings for this service require Windows Authentication but it is not enabled for the IIS application that hosts this service.

September 1, 2008

I obtained this error when i tested my WCF Service.

Security settings for this service require Windows Authentication but it is not enabled for the IIS application that hosts this service.

Solution

IIS->select virtual directory with services -> Properties -> Directory Security tab-> Edit… -> Check Integrated windows authentication. Uncheck Anonymous access.

Then open command line and execute iisreset