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.
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.
То есть требуется написать полноценные парсер и семантический анализатор. То есть по сути небольшой компилятор. Пришлось написать. :)
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, блин. Я бы тех людей, которые возвращают такие ошибки, приговаривал бы к десяти годам насильственного исправления ошибок типа "В программе ошибка!". Млин, уже полвека программирование существует, и так и не научилось человечество диагностику ошибок нормальную возвращать. Дурдом какой-то.
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.
Converting IEnumerable to EntitySet
03.09.2008 Среда 18:59
Software: .Net 3.5 or later
To convert IEnumerable
to EntitySet
use the following extension method:
private static EntitySet<T> ToEntitySet<T>(this IEnumerable<T> source) where T : class
{
var es = new EntitySet<T>();
es.AddRange(source);
return es;
}
Reading connection string from app.config
03.09.2008 Среда 14:40
Software: .Net, C#
This is how to read connection string from a configuration file (web.config, app.config). Assume you have the following in your configuration file:
<configuration>
<connectionStrings>
<add name="MyConnectionString"
connectionString="Data Source=localhost;Initial Catalog=master;Persist Security Info=True" />
</connectionStrings>
<configuration>
In order to read this string within C# code do this:
1. Add reference to System.Configuration.dll
2.Use this code:
string connString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;