Навигация

Итоги года

Другие ссылки


Реклама

Счётчики


<- Предыдущие записи Следующие записи ->

FtpWebRequest: The remote server returned an error: (500) Syntax error, command unrecognized

12.08.2009 Среда 19:34

I am wokring on a project now that involves transfering data by FTP. I use standard .Net functionality to do FTP'ing — System.Net.FtpWebRequest class. Everything works fine while I am running single isolated requests to the FTP server. But when I start a batch processing that quickly sends massive requests to the server (like "list files in a FTP directory", "upload a file", "download a file", "delete a file") I start seeing the following error, which occurs sporadically:

The remote server returned an error: (500) Syntax error, command unrecognized.
at System.Net.FtpWebRequest.SyncRequestCallback(Object obj)
at System.Net.FtpWebRequest.RequestCallback(Object obj)
at System.Net.CommandStream.InvokeRequestCallback(Object obj)
at System.Net.CommandStream.Abort(Exception e)
at System.Net.FtpWebRequest.FinishRequestStage(RequestStage stage)
at System.Net.FtpWebRequest.GetResponse()
at MyCoolProgram.DownloadFileFromFtp(String fileName) in C:\MyCoolProgram\FtpHelper.cs:line 97

The exception is happening in this code:

FtpWebRequest uploadRequest = (FtpWebRequest)WebRequest.Create(uri);
uploadRequest.ReadWriteTimeout = 30000;
uploadRequest.Method = WebRequestMethods.Ftp.UploadFile;
uploadRequest.Credentials = new NetworkCredential(myLogin, myPassword);
requestStream = uploadRequest.GetRequestStream();
requestStream.Write(data, 0, data.Length);
requestStream.Close();
response = (FtpWebResponse)uploadRequest.GetResponse(); // <— here occurs the exception

The reason is somewhat strange inner workings of the .Net FTP library. For some reason it sometimes decides to send USER command to the server between downloads. If it did it always, I'd see this error on each request. But it doesn't do it always, it does it SOMETIMES. Weird enough. But, anyway. The solution is to re-use the NetworkCredential instance between the calls. That is, create an instance of the NetworkCredential class once, and re-use it for each FtpWebRequest created.

I found this solution here. There's more elaborated info on the topic.

Доктор, меня все игнорируют (нет комментариев)

Isolation levels in SQL Server 2005

28.07.2009 Вторник 13:29


Courtesy Dinesh Priyankara

Доктор, меня все игнорируют (нет комментариев)

SQL Server Management Studio: "Incorrect syntax near ':'" on :setvar

22.07.2009 Среда 12:51

I had a database project generated in Visual Studio 2008. When built, this project generates a script file whose purpose is to re-create the database. When I was trying to run this script file in SQL Server Management Studio 2005, I received the following error:

Incorrect syntax near ':'.
... which ocurred on this line in the script:

:setvar DatabaseName "MyDB"
The solution was to turn on the so called "SQLCMD Mode" in the Management Studio. When this mode is on, the Management Studio does understand the ":setvar" syntax. To turn SQLCMD mode on go to menu Query, then check SQLCMD Mode item.

Доктор, меня все игнорируют (нет комментариев)

Visualize project dependencies in Visual Studio

23.03.2009 Понедельник 16:30

Sometimes it is nice to see project dependencies in Visual Studio in a visual form, so as to assess complexity of a new project you get involved with. Here's a way to do it:

  • Start Visual Studio

  • Open your solution

  • Start the data collecting macro (its code is at the bottom of the post)

  • The macro will generate a text file with name [your solution name].dot

  • Download and install open source program called Graphviz. It is a graph vizualization software. It takes a text file of a simple format as input.

  • Start Graphviz and open the .dot file in it. Graphviz will create an image visualizing dependencies of your application for you. You will get something like this:




Now for the macro.

Imports System

Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports System.Diagnostics
Imports VSLangProj
Imports System.IO

Public Module Diagram

Sub ProjectDependency()
Dim writer As New StreamWriter(DTE.Solution.FileName & ".dot")
writer.WriteLine("digraph """ & DTE.Solution.FullName & """ {")
writer.WriteLine(" rankdir=LR")
writer.WriteLine(" size=""10,10""")
writer.WriteLine(" node [color=lightblue2, style=filled]")

For Each project As Project In DTE.Solution.Projects
NavProj(project, writer)
Next

writer.WriteLine("}")
writer.Dispose()
End Sub

Sub NavProj(ByVal proj As Project, ByRef writer As StreamWriter)
For Each projectItem As ProjectItem In proj.ProjectItems
If Not projectItem Is Nothing Then
If Not projectItem.SubProject Is Nothing Then
writer.WriteLine(" """ & proj.Name & """->""" & projectItem.Name & """")
NavProj(projectItem.SubProject, writer)
End If
End If
Next
End Sub

End Module

This macro works in Visual Studio 2008.

Комментариев: 2

How to combine (AND) two LINQ expressions in one

02.03.2009 Понедельник 12:17


private static Expression<Func<object, bool>> AndExpressions(
Expression<Func<object, bool>> expression1,
Expression<Func<object, bool>> expression2)
{
if (expression1 == null)
{
return expression2;
}
else if (expression2 == null)
{
return expression1;
}
else
{
var invokedExpr = Expression.Invoke(expression2, expression1.Parameters.Cast<Expression>());
return Expression.Lambda<Func<object, bool>>(Expression.AndAlso(expression1.Body, invokedExpr), expression1.Parameters);
}
}

Доктор, меня все игнорируют (нет комментариев)

Тестовое задание

11.02.2009 Среда 15:28

Во какие теперь тестовые задания дают:

Тестовое задание к тренингу «Разработка программного обеспечения для Microsoft .NET Framework»

Калькулятор. Написать консольное приложение, выполняющее простые арифметические действия и функции. Приложение читает выражения со стандартного входного потока и выводит значение выражения в стандартный выходной поток. Выражения могут содержать целые и дробные числа, скобки, унарные (‘+’, ‘-‘) и бинарные (‘+’, ‘-‘, ‘*’, ‘/’) операторы и функции (напр. abs(), pow() – степень). Функции могут принимать определенное число аргументов: 1 (например sin(x)), 2 (например pow(x, y) и т.д. Некоторые функции допускают любое число аргументов (напр. max(1, 2), max(1, 2, 3, 4, 5)).

Функции, которые должны быть реализованы:

abs(x) – абсолютная величина
sqrt(x) – квадратный корень
min(x,y,…), max(x,y,…) – минимум и максимум из двух или более аргументов
round(x) – округление
pow(x,y) – x в степени y

Приложение должно уметь работать с любыми функциями из списка, корректно обрабатывая неправильное использование.

Примеры:

abs(-10) * (12 + max(1,4,0))
160

12 + abs(-10, 3)
Error: incorrect number of parameters for function “abs”

12 * a(-10)
Error: unknown function “a”

12 + (max(1,4)
Error: “)” expected

12 + PI2
Error: cannot resolve symbol “PI2”

abs(-min(200, 220 - sqrt(100)))
200

Общие требования для задания:

– Классы, методы и поля должны иметь XML-комментарии (см. http://msdn.microsoft.com/library/default.asp?url=/library/en-us/csref/html/vcwlkxmldocumentationtutorial.asp). Ключевые моменты в реализации методов должны сопровождаться комментариями.
– Приложения должны быть ”устойчивы” к ошибкам пользователя, выдавая информативные сообщения.
– Важно: задания оцениваются не только по правильности работы приложений, но и по качеству кода, эффективности реализации, пониманию и использованию OOP.

То есть требуется написать полноценные парсер и семантический анализатор. То есть по сути небольшой компилятор. Пришлось написать. :)

Комментариев: 15

JavaScript: Correct way to check for existance of a variable

08.12.2008 Понедельник 07:52

Not like this:

if (!my_var) return;

but like this:

if (!window.my_var) return;

Доктор, меня все игнорируют (нет комментариев)

RAD Grid: OnRowSelected doesn't fire up

30.09.2008 Вторник 18:29

Context: .Net, Telerik RADControls (RAD, R.A.D.) for ASP.Net AJAX, RAD Grid Control

The following didn't work for my RAD grid control:

<ClientSettings>

<ClientEvents OnRowSelected="grid_onRowSelected" />
</ClientSettings>
Javascript function grid_onRowSelected was never being called. The reason was very simple: in the grid definition in the .aspx page, the OnRowSelected event was assigned twice, with different target functions. Despite obvious stupidity of this error this may happen because sometimes definitions of complex RAD grid controls may become very long and cumbersome. Something important may get lost if you are not meticulous enough. Which is exactly what happened to me.

Доктор, меня все игнорируют (нет комментариев)

Catastrophic failure

25.09.2008 Четверг 19:09

Работаю с объектой моделью Exchange Server 2003 Management Tools. Пытаюсь при помощи создать COM-интерфейса CDOEXM.IMailboxStore создать mailbox для пользователя. Получаю ошибку:

System.Runtime.InteropServices.COMException: Catastrophic failure (Exception from HRESULT: 0x8000FFFF (E_UNEXPECTED))

at CDOEXM.IMailboxStore.CreateMailbox(String HomeMDBURL)
...
В итоге выяснилось, что такая ошибка возникала при попытке создания mailbox'а для пользователя, у которого в ActiveDirectory не установлен атрибут "displayName".

Catastrophic failure, блин. Я бы тех людей, которые возвращают такие ошибки, приговаривал бы к десяти годам насильственного исправления ошибок типа "В программе ошибка!". Млин, уже полвека программирование существует, и так и не научилось человечество диагностику ошибок нормальную возвращать. Дурдом какой-то.

Комментариев: 2

Error calling WCF service

23.09.2008 Вторник 16:51

Context: .Net 3.5, C#, WCF

Was getting this error message when trying to call a WCF service's method:

The message with Action 'blah' cannot be processed at the receiver, due to a ContractFilter mismatch at the EndpointDispatcher. This may be because of either a contract mismatch (mismatched Actions between sender and receiver) or a binding/security mismatch between the sender and the receiver. Check that sender and receiver have the same contract and the same binding (including security requirements, e.g. Message, Transport, None).

In my case it was caused by the old version of the service deployed on the server. I was calling a function which was in the service's contract on the client side, but was not there on on the server side. To solve the problem deploy the latest version of the service.

Доктор, меня все игнорируют (нет комментариев)

Cannot add an entity with a key that is already in use

04.09.2008 Четверг 13:14

Related to: .Net 3.5, C#, LINQ, LINQ-to-SQL

Got the following error:

Cannot add an entity with a key that is already in use.

at the following line:

Context.SubmitChanges();

This error usually happens when the database and the Context object are out-of-sync. This may happen when:

a. You change database outside of the Context object. For example by directly executing command using SqlCommand class.

b. When you use more than one Context object to update database.

To solve this issue, either always use the same Context object to update database, or refresh all Context objects you use after a change in database made through one of them or oustide any Context object. To achieve this just re-create the object:

MyContext context;
...
context.Dispose();
context = new MyContext();


However, this will most likely discard all unsubmitted changes made through the Context object updated in such a manner. So you have to accomodate for the changes before refreshing your context objects.

Доктор, меня все игнорируют (нет комментариев)
<- Предыдущие записи Следующие записи ->