Tuesday, November 08, 2011

Installing and Running IIS and Apache Server Together

We working on project that include web application based on python and several application based on IIS (as WCF , Web application, web site ant etc'). "Python" application use port 80 therefore we cannot use same port in IIS application. HERE was explained solution that based on 2 IP addresses.

p.s. One more note: you must run command prompt as administrator.

Tuesday, September 06, 2011

"The specified metadata path is not valid." error in using Windows Service and Entity Framework

I have project (Windows Service) that use Entity Framework model as external DLL.
I cannot use a metadada as embedded resource and must define connection string in config file of Windows Service. In the Debug mode I got right result, I created setup project and installed service in directory but a immediately I saw the next error:

 The specified metadata path is not valid. A valid path must be either an existing directory, an existing file with extension '.csdl', '.ssdl', or '.msl', or a URI that identifies an embedded resource.
I'll not tell you what I not tried  and a solution was found after deep research in order to understand where is run Windows Service. Bad news! Windows Service not run in installed directory therefore all path's to files in config file must be define as physical path otherwise application cannot find it. Windows service use relative path different to installation directory.

Where you use Entity Framework you must to define row as this one:
In order to not change path to physical path just add next row in event OnStart in Windows Service:

This is a way to define relative path of Service as installed directory.


kick it on DotNetKicks.com

Tuesday, August 23, 2011

Friday, August 05, 2011

Paging in LINQ

Implementation of paging  with help from ROW_COUNT() of SQL in LINQ :


public static IEnumerable<T> Paging<T>(int rowCount, int pageId, IQueryable<T> query)


    return  query       

        .Skip((pageId - 1) * rowCount)




private void TestMethod()


    Random rnd = new Random();

    List<Foo> fooList = new List<Foo>();

    for (int i = 0; i < 20; i++)



                new Foo


                    ID = rnd.Next(100),

                    Name = Membership.GeneratePassword(5, 0)





    var query = fooList.OrderBy(item => item.ID).AsQueryable();


   Console.WriteLine("Attempt 1");

   Paging(10, 1,query )



        item => Console.WriteLine(item.ID + ": " + item.Name)


    Console.WriteLine("Attempt 2");

    Paging(5, 2, query)



        item => Console.WriteLine(item.ID + ": " + item.Name)




public class Foo


    public int ID { get; set; }

    public string Name { get; set; }



And now as extension!


kick it on DotNetKicks.com

Monday, August 01, 2011

Entity Framework and Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.

I had troubles with long list in "delete" action. After several unsuccessful attempts I found solution (maybe is not the best):

using (var ctx = new EntityContext())
  var tmpTimeout = ctx.CommandTimeout;
   ctx.CommandTimeout = int.MaxValue;
  catch (Exception ex)
   ctx.CommandTimeout = tmpTimeout;

Thursday, July 21, 2011

Reading XLSX format file from C#

The best guide for reading excel file without Excel instance exist here.

Pay attentions! In the final example in the loop ForEach missed validation of  not string values and NULL value cells, threfore change it to:

foreach (XElement cell in cells)
    if (cell.IsEmpty)
    string cellPosition = cell.Attribute("r").Value;
    int index = IndexOfNumber(cellPosition);
    string column = cellPosition.Substring(0, index);
    int row = Convert.ToInt32(cellPosition.Substring(index, cellPosition.Length - index));
    if (cell.HasElements)
        if (cell.Attribute("t") != null && cell.Attribute("t").Value == "s")
            // Shared value
            int valueIndex = Convert.ToInt32(cell.Descendants(ExcelNamespaces.excelNamespace + "v").Single().Value);
            parsedCells.Add(new Cell(column, row, sharedStrings[valueIndex]));
            string value = cell.Descendants(ExcelNamespaces.excelNamespace + "v").Single().Value;
            parsedCells.Add(new Cell(column, row, value));
        parsedCells.Add(new Cell(column, row, ""));

Wednesday, July 20, 2011

Error in SecurityMode = None in WsHttpBinding

Define next attributes in the binding:

        <binding name="wsHttpBindingConfig">
          <security mode ="None"/>
          <reliableSession enabled="true" />


Tuesday, July 19, 2011

WCF error messages - the guide.

Whenever web developers hear the term session, we think of Http Session which is used to store data between multiple HTTP requests....to full article click here!

Sunday, July 10, 2011

Could not load file or assembly 'ASSEMBLY_NAME' or one of its dependencies. An attempt was made to load a program with an incorrect format.

The error occurred as transfer from 32-bit to 64-bit platforms. A solution is very easy:

1. Go to "ASSEMBLY_NAME" project in solution
2. Open project properties
3. Open "Build" tab
4. Change "Platform target" to "Any CPU"
5. Compile solutions.


Thursday, June 30, 2011

How to prevent duplicates in 2 columns in one table

We know how to define column as unique, but what to do where you need to prevent duplicate in 2 columns?
This is a state:
Wine VARCHAR(50),
Country VARCHAR(50)



A result is:

Id |  Wine    |  Country
----------- ------------------
1 | Merlot | France
2 | Merlot | Argentina
3 | Malbec | Argentina

A target to prevent:

Id |  Wine    |  Country
----------- ------------------

1 | Merlot | France
2 | Merlot | Argentina
3 | Malbec | Argentina

4 | Merlot | France
5 | Caberne | France

That means table allow duplicate Wines and duplicate Countries, but must prevent double rows.
A solution is to add next row after table creation:
ALTER TABLE  #tmp      ADD UNIQUE(Wine, Country)


Monday, June 27, 2011

Generic Type Convert Function

It's simple method can be use as extension method for conversion types :
public static TK ConvertTo<TK>(this object value,bool isThrowException = false, 
TK defaultValue = default(TK))
return (TK)Convert.ChangeType(value, typeof(TK));
catch (InvalidCastException ex)
if (isThrowException)
throw ex;
return defaultValue;

Using example:

string value = "15";
//Method will convert string to int.
//In case val is not numeric will throw exception.
int result = value.ConvertTo();
//In case val is not numeric will return type default value.
int result1 = value.ConvertTo(false);
//In case val is not numeric will return your defined value (5).
int result2 = value.ConvertTo(false,5);


kick it on DotNetKicks.com

Wednesday, June 22, 2011

Entity Framework, web.config and error "The specified named connection is either not found in the configuration..."

Hi my friend,

If  you come to here from generic search, then you already know what is a real nightmare. Every new feature from Microsoft can include surprised items and will take hours (sometimes days) for understand how it work correct. Anyway...

For using Entity Framework as DLL class-library in win/console application you should work by next steps:

1. Create YOUR_NAME.edmx.
2. Open designer.
3. Click on background.
4. In property tab change property "Metadata artifact Processing" to "Copy to Output Directory".
5. Save project (Connection string will be changed from "res//*/" to ".\" ).
6. Copy connection string to main app.config as is.
7. Go to EF project properties. Choose "Build event" and in Post-Build event command line add next rows:

copy  YOUR_NAME.csdl $(SolutionDir)START_PROJECT\bin\Debug\
copy  YOUR_NAME.ssdl $(SolutionDir)START_PROJECT\bin\Debug\
copy  YOUR_NAME.msl $(SolutionDir)START_PROJECT\bin\Debug\

8. Remove app.config of EF project.

But the nightmare does not live in win application, because she's place in Web Application!

Next steps will help you to back out from hell:
Do it 1-6 steps as in win application case.
7. In web.config change  ".\" to "~\App_Data" in c/m/s files
8. Go to EF project properties. Choose "Build event" and in Post-Build event command line add next rows:

copy  YOUR_NAME.csdl $(SolutionDir)START_WEB_PROJECT\App_Data\
copy  YOUR_NAME.ssdl $(SolutionDir)START_WEB_PROJECT\App_Data\
copy  YOUR_NAME.msl $(SolutionDir)START_WEB_PROJECT\App_Data\

9. Remove app.config of EF project.
10. Cross fingers, run it and pray!


Sunday, June 05, 2011

Full solution to: The server committed a protocol violation. Section=ResponseStatusLine

In most answers to this error you will get same answer:
      <httpWebRequest useUnsafeHeaderParsing="true" />

But not always a problem will be resolved. A full solutions to error present here. Just add next row to request variable:

   request.KeepAlive = false;


   ((HttpWebRequest)request).KeepAlive = false; (Where request type is WebRequest)

LINQ2SQL Connection Strings with class library projects

1. Set connection string in Web/App.config in main external project.
2. Open up your DBML and click the designer service. Expand the Connection property, delete Connection String and set "Application Settings" to False.
3. Open designer file and add new construtor as:
  public DataClassesDataContext()
            : base(ConfigurationManager.ConnectionStrings["ConnectionStringName"].ConnectionString)



4. Enjoy!

Full article and inspiration exist here.

Sunday, April 03, 2011

Check is IP in range

You can find countless examples how to check is IP in range. I would like to offer my way for solution with LINQ:

using System.Collections.Generic;
using System.Net;
using System.Linq;

 public class IPRange
        public byte[] StartAddressBytes { get; private set; }
        public byte[] EndAddressBytes { get; private set; }

        public IPRange(IPAddress startAddress, IPAddress endAddress)
            StartAddressBytes = startAddress.GetAddressBytes();
            EndAddressBytes = endAddress.GetAddressBytes();
        public IPRange(string strartIp, string endIp)
            IPAddress startAddress, endAddress;
            if (IPAddress.TryParse(strartIp, out startAddress) 

                && IPAddress.TryParse(endIp, out endAddress))
                StartAddressBytes = startAddress.GetAddressBytes();
                EndAddressBytes = endAddress.GetAddressBytes();

public class IPRangeUtil
        public static bool IsInRange(List<
IPRange> ipRange , string clientIp)
            IPAddress clientAddress;
            if (!IPAddress.TryParse(clientIp, out clientAddress))
                return false;
            return IsInRange(ipRange, clientAddress);
        public static bool IsInRange(
List<IPRange> ipRange, IPAddress clientAddress)
            int clientIpSum = clientAddress.GetAddressBytes().Sum(item => item);
            return ipRange.Where(range =>
                clientIpSum >= range.StartAddressBytes.Sum(item => item)
                && clientIpSum <= range.EndAddressBytes.Sum(item => item)).Any() ;

A using is very easy:
 List ranges = new List
                        //You can replace "xxx.xxx.xxx.xxx" to IPAddress typed variable 
                          new IPRange("", ""),
                          new IPRange("", "")

bool isInRange = IPRangeUtil.IsInRange(ranges, "");


kick it on DotNetKicks.com

Thursday, January 20, 2011

LINQ and #Temporary tables in Stored Procedure do not have return values

I have Stored Procedure which include #tmp table. I tried to drag it to DBML but every time i got message "bla-bla-bla ... do not have return values...".After countless attempts was found solution! (Thanks to Marc Gravell )
Replace the #tmp in variable, a meaning:

CREATE TABLE #tmp (Item in)
Replace it to:
DECLARE @tmp TABLE (Item int)

A using in query is:
SELECT yt.*, t.Item
FROM YUOR_TABLE yt, @tmp t