суббота, 6 февраля 2016 г.

Что делают SPWeb.Dispose() и Close()?


Вскрытый код метода Microsoft.SharePoint.SPWeb.Dispose();
// Microsoft.SharePoint.SPWeb
public void Close()
{
 if (this.m_closed)
 {
  return;
 }
 if (this.m_bFirstUniqueAncestorWebInited && this.m_FirstUniqueAncestorWeb != null && !object.ReferenceEquals(this.m_FirstUniqueAncestorWeb, this))
 {
  this.m_FirstUniqueAncestorWeb.Dispose();
  this.m_bFirstUniqueAncestorWebInited = false;
  this.m_FirstUniqueAncestorWeb = null;
 }
 if (this.m_Site != null)
 {
  if (this == this.m_Site.m_rootWeb)
  {
   this.m_Site.m_rootWeb = null;
  }
  this.m_Site.InvalidateWeb(this);
 }
 if (this.m_ctsAll != null)
 {
  foreach (SPContentType sPContentType in this.m_ctsAll)
  {
   sPContentType.CloseWebAsNecessary();
  }
 }
 this.Invalidate(SPContentTypeClass.Field);
 this.Invalidate(SPContentTypeClass.Type);
 if (this.m_Site != null)
 {
  this.m_Site.RemoveFromOpenedWebs(this);
 }
 this.Invalidate();
 this.m_closed = true;
}

[SharePointPermission(SecurityAction.Demand, ObjectModel=true)]
public void Dispose()
{
  this.Close();
}

До кучи System.IO.StreamWriter.Dispose():

// System.IO.TextWriter
/// Освобождает все ресурсы, используемые объектом .
public void Dispose()
{
 this.Dispose(true);
 GC.SuppressFinalize(this);
}
// System.IO.StreamWriter
/// Закрывает текущий объект StreamWriter и базовый поток.
/// Текущая кодировка не поддерживает отображение половины суррогатной пары Юникода.
/// 1
public override void Close()
{
 this.Dispose(true);
 GC.SuppressFinalize(this);
}
// System.IO.StreamWriter
/// Освобождает неуправляемые ресурсы, используемые  (при необходимости освобождает и управляемые ресурсы).
/// 
///           Значение true позволяет освободить управляемые и неуправляемые ресурсы; значение false позволяет освободить только неуправляемые ресурсы. 
/// Текущая кодировка не поддерживает отображение половины суррогатной пары Юникода.
protected override void Dispose(bool disposing)
{
 try
 {
  if (this.stream != null && (disposing || (!this.Closable && this.stream is __ConsoleStream)))
  {
   this.Flush(true, true);
   if (this.mdaHelper != null)
   {
    GC.SuppressFinalize(this.mdaHelper);
   }
  }
 }
 finally
 {
  if (this.Closable && this.stream != null)
  {
   try
   {
    if (disposing)
    {
     this.stream.Close();
    }
   }
   finally
   {
    this.stream = null;
    this.byteBuffer = null;
    this.charBuffer = null;
    this.encoding = null;
    this.encoder = null;
    this.charLen = 0;
    base.Dispose(disposing);
   }
  }
 }
}
И еще до кучи (System.Data.SQLClient.SQLConnection.Dispose()):
protected override void Dispose(bool disposing)
{
  if (disposing)
  {
      this._userConnectionOptions = null;
      this._poolGroup = null;
      this.Close();
  }
  this.DisposeMe(disposing);
  base.Dispose(disposing);
}

понедельник, 1 февраля 2016 г.

Новые возможности C# 6.0

Перевод статьи New Features of C# 6.0

В этой статье мы познакомимся с новыми ключевыми фишками и усовершенствованиями, появившимися в C# 6.0.

Автоматически реализуемые свойства:

Эта штука позволяет нам задать значения свойств на этапе их объявления.
Previously, we use constructor to initialize the auto properties to non-default value but with this new feature in C# 6.0, it doesn’t require to initialize these properties with a constructor aкак показано ниже:

class Customer
{
    public string Firstname{get; set;} = "Csharpstar";
    public string Lastname{get; set;} = "Admin";
    public int Age{get;} = 20;
    public DateTime BirthDate { get; set; }
}
We can use this property with getter/setter and getter only.Using getter only help achieve immutability.

Фильтры исключений:

Microsoft introduced this CLR feature in C# with version 6.0 but it was already available in Visual Basic and F#. To use Exception Filters in C#, we have to declare the filter condition in the same line as that of the catch block and the catch block will execute only if the condition is successfully met as shown below:

try
{
throw new CustomException("Test Exception")
}
catch(CustomException ex) if (ex.Message=="Not Test")
{
//Control will not come here because exception name is not test
}
catch(CustomException ex) if (ex.Message=="Test Exception")
{
//Control will come here because exception name is Test Exception
}
 
Remember that Exception Filter is a debugging feature rather than a coding feature. We will discuss more on this in next post

Await в блоках catch и finally block:

We frequently log exceptions to a log file or a database. Such operations are resource extensive and lengthy as we would need more time to perform I/O. In such circumstances, it would be great if we can make asynchronous calls inside our exception blocks. We may additionally need to perform some cleanup operations in finally block which may also be resource extensive.

try
{
// code that might throw exception
}
catch(Exception ex)
{
await LogExceptionAsync(ex);
}

Getter-only Auto Properties

When you use auto implemented properties in C# 5 and lower, you must provide a get and set. If you want the property value to be immutable, you can use the private accessor on the setter. With C# 6, you can now omit the set accessor to achieve true readonly auto implemented properties:

 
public DateTime BirthDate { get; }

Интерполяция строк

String.Format was used till today to generate the FullName value in the Customer class.A new feature named string interpolation provides a large improvement in this area. Rather than filling placeholders with indexes provide an array of values to be slotted in at runtime, you provide the source of the parameter value instead, and the string.Format call is replaced by a single $ sign. This is how the FullName property declaration looks when using string interpolation in the expression body instead:

 
public string FullName => $"{FirstName} {LastName}";
Apart from this saving a number of key strokes, it should also minimise (if not remove) the possibility of FormatExceptions being generated from inadvertently supplying too few values to the argument list.

Инициализация словарей:

В C# 6.0 появился более прозрачный путь для инициализации словарей (см. ниже):

 
var BookDictionary = new Dictionary<int,string>
{
[1] = "ASP.net",
[2] = "C#.net",
[3] = "ASP.net Razor",
[4] = "ASP.net MVC5"
}
А раньше было так:
Dictionary<int,string> BookDictionary = new Dictionary<int,string>()
{
{1, "ASP.net"},
{2, "C#.net"}
{3, = "ASP.net Razor"},
{4, = "ASP.net MVC5"}}
};

Null – условный оператор:

Null-условный оператор “?” использует одинарный знак вопроса. It can be used to reduce the no. of lines in code file and provide an easy access to check for Null and return the result. The null conditional operator tests for null before accessing a member of an instance. Пример:

using System;

class Program
{ static void Test(string name)
    {
 // Use null-conditional operator.
 // ... If name is not null, check its Length property.
 if (name?.Length >= 3)
 {
     Console.WriteLine(true);
 }
    }
    static void Main()
    {
 Console.WriteLine(1);
 Test(null);
 Console.WriteLine(2);
 Test("Csharpstar"); // True.
 Test("x");
 Test("ExamIron"); // True.
    }
}
Выводится:1
2
True
True

воскресенье, 31 января 2016 г.

Даинамическое отображение полей при вставке записей в список (без SharePoint Designer)

Итак, имеются два вида пользователей - физическое лицо, юридическое лицо. Это хранится в поле выбора "Форма оплаты". В зависимости от выбора формы оплаты из выпадающего списка, нужно отображать соответствующие данные: ФИО, паспорт для физлица и реквизиты для юрлица. Для этого:

1) Заходим в список, выбираем в ленте "Список" -> "Веб-части формы" ->Форма создания по умолчанию".

2) Загрузится форма. Затем нажимаем в верхней панели "Добавить веб-часть" и из группы "Среди и контент" выбираем веб-часть "Редактор контента".

3) Далее нажимаем кнопку "Добавить" и кликаем на поле редактора в самой веб-части.

4) В ленте появятся иконки редактирования контента. Где-то справа в конце будет иконка "HTML".

5) Жмем на иконку в в окно вводим следующий скрипт (см. ниже);

6) Сохраняем изменения для веб-части

7) Всё.

 
Особенность: Ввиду того что поиск производится по атрибуту Title, по началу строки, от атрибут Title одного поля не должен полностью входить в атрибут Title другого поля.
Дополнительно

Открытие диалогового окна на вставку записи из навигационной панели.

Открытие диалогового окна на вставку из навигационной панели.

1) Действия сайта -> Параметры сайта -> Внешний вид и функции ->Верхняя панель ссылок или адрес  http://myserver/_layouts/topnav.aspx

2) Далее жмем "Создать ссылку для перехода"

3) В поле "Введите описание" пишем название в горизонтальном пункта меню.

4) В поле "Введите веб-адрес" пишем адрес следующий java-скрипт одной строкой:

JavaScript:var options=SP.UI.$create_DialogOptions();options.url='http://myserver/Lists/List1/NewForm.aspx';options.height = 800;void(SP.UI.ModalDialog.showModalDialog(options))
Вместо адреса http://myserver/Lists/List1/ указываем свой адрес списка

суббота, 30 января 2016 г.

10 частых вопросов на собеседовании по C# на числа


  1. Как поменять два числа местами в C# без использования временной переменной (Решение)

  2. Write a C# program to determine total ways stairs can be climbed (Решение)

  3. Напишите программу на C# для вычисления факториала без рекурсии (Решение)

  4. Напишите на C# программу вывода n-го числа чисел Фибоначчи (Решение)

  5. Напишите на C# программу получения остатка от деления 2-х целых (Решение)

  6. Напишите на C# программу, проверяющую является ли введенное число числом Армстронга (Решение)

  7. Напишите на C# программу поиска НОК и НОД для 2-х заданных чисел. (Решение)

  8. Напишите на C# программу, проверяющую является ли введенное число простым (Решение)

  9. Напишите на C# программу, проверяющую является ли введенное число Палиндромом (Решение)

  10. Напишите на C# программу, решающую проблему FizzBuzz (Решение)

понедельник, 3 августа 2015 г.

Напоминалочка про BeforeProperties и AfterProperties в EventReceiver

Создавая новое события для списка, я постоянно натыкаюсь на то, что свойства BeforeProperties либо AfterProperties порой не заполнены. Обязательно почитайте этот пост – http://www.synergyonline.com/blog/blog-moss/Lists/Posts/Post.aspx?ID=25 А вот пара шпаргалок, заимствованных оттуда:

Для событий списка:

List BeforeProperties AfterProperties properties.ListItem
ItemAdding No Value No Value Null
ItemAdded No Value No Value New Value
ItemUpdating Original Value Changed Value Original Value
ItemUpdated Original Value Changed Value Changed Value
ItemDeleting No Value No Value Original Value
ItemDeleted No Value No Value Null


Для событий библиотеки:

Library BeforeProperties AfterProperties properties.ListItem
ItemAdding No Value No Value Null
ItemAdded No Value No Value New Value
ItemUpdating Original Value Changed Value Original Value
ItemUpdated Original Value Changed Value Changed Value
ItemDeleting No Value No Value Original Value
ItemDeleted No Value No Value Null

понедельник, 6 октября 2014 г.

SPListItem и ExpandoObject

Обычно к элементу списка в SharePoint мы обращаемся так:
SPListItem item = mylist.GetItemById(id);

      
item["FirstName"] =  "John";
item["LastName"] = "Smith";
item["FullName"] = (string)item["FirstName"] +" "+(string)item["LastName"];
item["Amount"] = (int)item["Amount"] + 100;

С применением ExpandoObject код становится более читаемым.
SPListItem item = mylist.GetItemById(id);

dynamic person = item.Expand(); //см. код расширения ниже 
          

person.FirstName = "John";
person.LastName = "Smith";
person.FullName = person.LastName +" "+person.FirstName; 
person.Amount += 100;

item.Inject((object)person); //также см. код расширения
Исходный код расширения:
    public static class SPListMapperExtension
    {
        public static dynamic Expand(this SPListItem listItem)
        {
            dynamic ex = new ExpandoObject();
            var dynFields = listItem.Fields.OfType().Where(x => !x.Hidden && x.CanBeDisplayedInEditForm);
            foreach (var f in dynFields)
            {
                (ex as IDictionary).Add(f.InternalName, listItem[f.InternalName]);
            }
            return ex;
        }

        public static void Inject(this SPListItem listItem, dynamic obj)
        {
            //dynamic o = (dynamic)obj;
            ExpandoObject ex = obj;
            var dynFields = listItem.Fields.OfType().Where(x => !x.Hidden && x.CanBeDisplayedInEditForm);
            foreach (var f in dynFields)
            {
                listItem[f.InternalName] = 
                    (ex as IDictionary)[f.InternalName];
            }

        }
    }