using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; public class BinBuilder { public BinaryWriter writer; public MemoryStream requestMemoryStream = new MemoryStream(); public BinBuilder(string a) : this(ASCIIEncoding.Default.GetBytes(a)) { } public BinBuilder(byte[] init):this() { writer.Write(init); } public void Append(ushort us) { this.Append(BitConverter.GetBytes(us)); } public void AppendCRC(ushort us) { var a=BitConverter.GetBytes(us); writer.Write(a[1]); writer.Write(a[0]); } public void Append(char us) { this.Append(BitConverter.GetBytes((ushort)us)); } public void Append(byte[] init) { writer.Write(init); } public BinBuilder() { writer = new BinaryWriter(requestMemoryStream); } public byte[] ToArray() { writer.Flush(); return requestMemoryStream.ToArray(); } }
Showing posts with label c#. Show all posts
Showing posts with label c#. Show all posts
Tuesday
BinBuilder - equivalent of StringBuilder for binary objects
Friday
linq join on multiple fields by OR sample
Linq doesn't allow to do on t1.field1=t2.field1 or t1.field2=t2.field2
therefor it can be done by using OR in where statement:
therefor it can be done by using OR in where statement:
var profiles = (from b in invoiceContext.bills
join p in invoiceContext.PaymentProfiles on 1 equals 1
where b.ProfileID == p.Id || b.ProfileType == p.Id
select p.Name).ToList();
Wednesday
linq subquery for in
for example following sql
will have this equivalent in linq:
select * from AccountTransactions a
where
a.TransactionId =19687 OR
a.TransactionId in (select ChildId from AccountTransactionRelations where InvoiceId=19687)
will have this equivalent in linq:
var records = from t in odc.AccountTransactions
join r in odc.AccountTransactionRelations on t.TransactionId equals r.InvoiceId into rel
where t.TransactionId == transactionId || rel.Select(o => o.ChildId).Contains(transactionId)
select t;
Tuesday
dday ical example
// #1: Monthly meetings that occur on the last Wednesday from 6pm - 7pm
// Create an iCalendar
iCalendar iCal = new iCalendar();
// Create the event
Event evt = iCal.Create<Event>();
evt.Summary = "Test Event";
evt.Start = new iCalDateTime(2008, 1, 1, 18, 0, 0); // Starts January 1, 2008 @ 6:00 P.M.
evt.Duration = TimeSpan.FromHours(1);
// Add a recurrence pattern to the event
RecurrencePattern rp = new RecurrencePattern();
rp.Frequency = FrequencyType.Monthly;
rp.ByDay.Add(new DaySpecifier(DayOfWeek.Wednesday, FrequencyOccurrence.Last));
evt.AddRecurrencePattern(rp);
// #2: Yearly events like holidays that occur on the same day each year.
// The same as #1, except:
RecurrencePattern rp = new RecurrencePattern();
rp.Frequency = FrequencyType.Yearly;
evt.AddRecurrencePattern(rp);
// #3: Yearly events like holidays that occur on a specific day like the first monday.
// The same as #1, except:
RecurrencePattern rp = new RecurrencePattern();
rp.Frequency = FrequencyType.Yearly;
rp.ByMonth.Add(3);
rp.ByDay.Add(new DaySpecifier(DayOfWeek.Monday, FrequencyOccurrence.First));
evt.AddRecurrencePattern(rp);
/*
Note that all events occur on their start time, no matter their
recurrence pattern. So, for example, you could occur on the first Monday
of every month, but if your event is scheduled for a Friday (i.e.
evt.Start = new iCalDateTime(2008, 3, 7, 18, 0, 0)), then it will first
occur on that Friday, and then the first Monday of every month after
that.
*/
Monday
get country name in winforms c#
// return two letter iso number like :"ES", "SE", "CA", "BE", "DE", "AT", "NL", "NO", "CH", "FI", "FR", "IR", "LU", "SW", "AU", "UK",
public string getCountry()
{
return RegionInfo.CurrentRegion.TwoLetterISORegionName.ToUpper();
}
Thursday
caching in .net system.runtime.caching example
using System.Runtime.Caching;
public class UseCacheSample {
private static void UseCacheSampleMethod()
{
Demo demo;
ObjectCache cache = MemoryCache.Default;
if (cache.Contains("demo"))
{
demo = (Demo)cache.Get("demo");
}
else
{
demo = new Demo();
demo.SetTimes();
cache.Add("demo", demo, new CacheItemPolicy());
}
}
}
Wednesday
singelton c# (thread safe, lazy initialization )
public sealed class Singleton
{
Singleton()
{
}
public static Singleton Instance
{
get
{
return Nested.instance;
}
}
class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested()
{
}
internal static readonly Singleton instance = new Singleton();
}
}
Monday
distinct linq example
1.Create IEqualityComparer class
2. Comparer can be used as follows:
public class DistinctTitle : IEqualityComparer<SourceType> {
public bool Equals(SourceType x, SourceType y) {
return x.title.Equals(y.title);
}
public int GetHashCode(SourceType obj) {
return obj.title.GetHashCode();
}
}
2. Comparer can be used as follows:
var x = (from t in dc.table
where t.sourceId = 5
order by t.itemId descending
select t)
.Distinct(new DistinctTitle())
.Select(t=>new{t.itemId, t.sourceId, t.title });
links for learning dot.net/c#
- XNA RPG - изучение XNA на примере построения RPG-игры (руководство из 26 частей) (link);
ASP.NET MVC
- ASP.NET MVC 3 для начинающих: добавляем ввод даты с помощью jQueryUI и NuGet (link);
- Руководство по Orchard, часть 1 - запуск блога (link);
- Руководство по Orchard, часть 2 (link);
- Custom Role Provider. Часть 1 (link);
- Настройка шаблонов T4 MvcScaffolding (link);
- Управление сессиями NHibernate в приложениях ASP.NET MVC (link);
- patterns & practices- Project Silk Drop 7 (link);
- Исопльзование Entity Framework Fluent API и Code First в ASP.NET MVC (link);
HTML5, JavaScript, веб-стандарты:
- Работа с CSS 3 в Expression Web (link)
- Мнение о том, когда использовать Canvas и SVG (link);
- Новые полезные JavaScript CSS решения 2011 года. 16 свежих плагинов для веб-разработчика (link);
- Результаты тестирования скорости JS в браузерах (link);
- IE9 Compat Inspector - инструмент анализа сайта на проблемы с JavaScript (link);
- Фрактал на JavaScript с помощью HTML5 (link);
- 14 браузерных javascript - игр, использующих HTML5 (link);
- Расширение ваших jQuery-приложений с Amplify.js (link);
- Useful jQuery Plugins - April 2011 (link);
- Взрывной логотип с помощью CSS3 и MooTools или jQuery (link);
Silverlight/WP7:
- Создание приложения для Windows Phone 7 от начала до конца (link);
- Обновление Silverlight 4 от 19 апреля (link);
- Новый конкурс мобильных приложений под Windows Phone 7 (link);
- Официальный гайдлайн по использованию кнопки Download for Windows Phone 7 (link);
- Официальное руководство по построению WP7-приложений для работы с SharePoint и UAG (link);
- Silverlight 5.0- Custom Markup Extensions and Roles (link);
- Лучшие БЕСПЛАТНЫЕ платформы, инструменты и элементы управления для Windows Phone 7 (link);
- Выпущены инструменты Phoney Tools 1.0 (link);
- Уроки по Silverlight PivotViewer (link);
- Silverlight 5 Beta Rough Notes–Linked RichTextBoxes (link);
- Доступны исходные коды Silverlight 5 3D-проекта Housebuilder, показанного на MIX11 (link);
- XAML и Data Binding- Расширенные возможности разметки и связывания данных в Silverlight (link);
Облачные технологии:
- Апрельское обновление Windows Azure AppFabric SDK и анонс доступности сервиса Windows Azure AppFabric Caching Service (link);
- 17 диаграмм Visio с описанием работы сценариев Windows Azure AppFabric Access Control Service (link);
- Простая организация VPN с помощью Windows Azure Connect (link);
- Сбор диагностических данных в вашем приложении Windows Azure (link);
- Размещение Ruby on Rails на Windows Azure - часть 2 (link);
- Как добавить тип проекта MVC 3.01 в мастер Azure Cloud Service (link);
- Расширения IIS для Windows Azure (link);
Инструменты:
- Выпущена новая версия пакетного менеджера NuGet 1.3 (link);
- Выпущена предварительная версия SQL Server 2008 R2 Service Pack 1 (link);
- Выпущены новые версии инструментов для миграции баз данных Oracle, Sybase, Access и MySQL на SQL (link);
- А еще в Visual Studio есть External Tools… (link);
- Обзор новых инструментов от команды WCF, которые были представлены на MIX11 (link);
- Reflector Умер? Да здравствует JustDecompiler (link);
Другое:
- Сертифицированным специалистам Microsoft платят на 21 % больше (link);
- Продукты Microsoft Windows 7, Windows Server 2008 R2 и SQL Server 2008 SP2 получили сертификацию (link);
- Dependency Injection pattern- три способа реализации (link);
- Associations in EF 4.1 Code First- Part 4 – Table Splitting (link);
- Entity Framework- Database Initializers and EF Code First (link);
- Ускоряя Stackoverflow.com (link);
Friday
calculate lrc
here is procedure how to claculate LRC for a string in c#
public static byte calculateLRC(byte[] ba, int offset, int length)
{
byte lrc = 0x0;
for (int i = offset; i < length; i++)
lrc ^= ba[i];
return lrc;
}
public static byte calculateLRC(string s, int offset, int length)
{
byte[] b = Encoding.ASCII.GetBytes(s);
byte l = calculateLRC(b, offset, length);
return l;
}
public static byte calculateLRC(string s)
{
byte l = calculateLRC(s, 0, s.Length);
return l;
}
binary serializer c
below is binary serializer class sample, could be used for serialization objects into strings (not XML , fixed length string) and back.
This class is good for creation network transport protocol layer classes.
here is sample of object to serialize
This class is good for creation network transport protocol layer classes.
here is sample of object to serialize
using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using CSharp.Core;
using CSharp.Core.Utility;
namespace CCLib.CCEngine
{
namespace COMDATA
{
public class ControlCharacters
{
public const byte STX = 0x2;
public const byte EOT = 0x4;
public const byte NAK = 0x15;
public const byte ACK = 0x06;
public static Char StartOfText = Convert.ToChar(0x02);
public static Char FieldSeparator = Convert.ToChar(0x1C); //Convert.ToChar(28);
public static Char RecordSeparator = Convert.ToChar(0x1D);
public static Char EndOfText = Convert.ToChar(0x03);
public static Char MessageDelimiter = Convert.ToChar(".");
}
public class ControlBytes
{
public static byte StartOfText = 0x02;
public static byte EndOfText = 0x03;
}
/// <summary>
/// Class used for converting data-structures into byte
/// </summary>
public class BinFormatter
{
public static string RemoveContrChars(string s)
{
string rt = String.Empty;
if (!String.IsNullOrEmpty(s))
{
try
{
int si = s.IndexOf(ControlCharacters.StartOfText);
int se = s.IndexOf(ControlCharacters.EndOfText);
int spos = si + 1;
int epos = se - 1;
if (epos > spos) s = s.Substring(spos, epos - spos - 1);
rt = s.Replace(ControlCharacters.FieldSeparator, '|').Replace(ControlCharacters.RecordSeparator,'?');
//replace non printable characters with whitespace
rt = Regex.Replace(rt,"[\x01-\x1F]", "");
}
catch (Exception ex)
{
Logger.prn(ex);
}
}
return rt;
}
public static string Cut(string s)
{
int st = s.IndexOf(ControlCharacters.StartOfText);
int end = s.IndexOf(ControlCharacters.EndOfText);
return s.Substring(st + 1, end - st);
}
public static byte[] AddControlCharsAndLRC(string s)
{
return AddControlCharsAndLRC(Encoding.ASCII.GetBytes(s));
}
public static byte[] AddControlCharsAndLRC(byte[] s)
{
byte[] r = new byte[s.Length + 3];
r[0] = ControlBytes.StartOfText;
s.CopyTo(r, 1);
r[s.Length + 1] = ControlBytes.EndOfText;
r[s.Length + 2] = calculateLRC(r, 1, s.Length + 2);
return r;
}
public static object RawDeserializeStr(string s, Type anytype)
{
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] data = encoding.GetBytes(s);
return RawDeserializeEx(data, anytype);
}
public static object RawDeserializeEx(byte[] rawdatas, Type anytype)
{
int rawsize = Marshal.SizeOf(anytype);
if (rawsize > rawdatas.Length)
return null;
GCHandle handle = GCHandle.Alloc(rawdatas, GCHandleType.Pinned);
IntPtr buffer = handle.AddrOfPinnedObject();
object retobj = Marshal.PtrToStructure(buffer, anytype);
handle.Free();
return retobj;
}
public static byte calculateLRC(byte[] ba, int offset, int length)
{
byte lrc = 0x0;
for (int i = offset; i < length; i++)
lrc ^= ba[i];
return lrc;
}
public static byte calculateLRC(string s, int offset, int length)
{
byte[] b = Encoding.ASCII.GetBytes(s);
byte l = calculateLRC(b, offset, length);
return l;
}
public static byte calculateLRC(string s)
{
byte l = calculateLRC(s, 0, s.Length);
return l;
}
public static byte[] RawSerializeEx(object anything)
{
int rawsize = Marshal.SizeOf(anything);
byte[] rawdatas = new byte[rawsize];
GCHandle handle = GCHandle.Alloc(rawdatas, GCHandleType.Pinned);
IntPtr buffer = handle.AddrOfPinnedObject();
Marshal.StructureToPtr(anything, buffer, false);
handle.Free();
return rawdatas;
}
public string StrFromByte(byte[] des2)
{
ASCIIEncoding utf82 = new ASCIIEncoding();
string uf82 = utf82.GetString(des2);
return uf82;
}
public static string RawSerializeStr(object anything)
{
byte[] des2 = RawSerializeEx(anything);
ASCIIEncoding utf82 = new ASCIIEncoding();
string uf82 = utf82.GetString(des2);
return uf82;
}
public static string sSet(string st, int plen)
{
if (st == "" || st.Length == plen)
{
return st;
}
else
{
char[] pro = Set(st, plen);
return new string(pro);
}
}
public static string CutTill(string st, int plen)
{
if (st.Length > plen)
{
return st.Substring(0, plen);
}
else
{
return st;
}
}
public static char[] Set(string st, int plen)
{
return Set(st, plen, ' ');
}
public static char[] Set(char st)
{
char[] pro = new char[1];
pro[0] = st;
return pro;
}
public static char[] Set(string st, int plen, char white_space)
{
int slen = st.Length;
char[] pro = new string(white_space, plen).ToCharArray();// new char[plen];
int count = slen > pro.Length ? pro.Length : slen;
st.CopyTo(0, pro, 0, count);
return pro;
}
public static string GetStringFromHex(string s)
{
string result = "";
string s2 = s.Replace(" ", "");
for (int i = 0; i < s2.Length; i += 2)
{
result += Convert.ToChar(int.Parse(s2.Substring(i, 2), System.Globalization.NumberStyles.HexNumber));
}
return result;
}
public static string GetLRC(string s)
{
int checksum = 0;
foreach (char c in GetStringFromHex(s))
{
checksum ^= Convert.ToByte(c);
}
return checksum.ToString("X2");
}
}
}
}
binary serialize object c
here's sample of the object that could be serialized into string (binary not xml! ) and can be deserialized back.
it useful for creation protocols layer classes and here is example of
binary serializer .
it useful for creation protocols layer classes and here is example of
binary serializer .
using System.Runtime.InteropServices;
using System.Text;
using CCLib.CCEngine.COMDATA;
namespace CCLib.CCEngine
{
namespace COMDATA
{
public class CApprovalCode
{
#region "Internal structures"
private SApprovalCode struc;
[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi)]
public struct SApprovalCode
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)]
public char[] ApprovalCode;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 12)]
public char[] RetrievalRefNumber;
}
public const int struc_size = 18;
#endregion
#region "Properties"
public string ApprovalCode
{
set { struc.ApprovalCode = BinFormatter.Set(value, 6); }
get { return new string(struc.ApprovalCode); }
}
public string RetrievalRefNumber
{
set { struc.RetrievalRefNumber = BinFormatter.Set(value, 12); }
get { return new string(struc.RetrievalRefNumber); }
}
#endregion
#region "Methods"
public CApprovalCode()
{
struc = new SApprovalCode();
struc.ApprovalCode = BinFormatter.Set("", 6);
struc.RetrievalRefNumber = BinFormatter.Set("", 12);
}
/// <summary>
/// Method for serializing structure into string
/// </summary>
public string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append(BinFormatter.RawSerializeStr(struc));
return sb.ToString();
}
/// <summary>
/// Method for de-serializing structure
/// </summary>
public void Parse(string s)
{
if (s != null && s != "")
{
struc = (SApprovalCode)BinFormatter.RawDeserializeStr(s.Substring(0, struc_size), struc.GetType());
}
}
#endregion
} //end CApprovalCode
}
}
convert object to string
using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using CSharp.Core;
using CSharp.Core.Utility;
// serializing object into byte array
public static byte[] RawSerializeEx(object anything)
{
int rawsize = Marshal.SizeOf(anything);
byte[] rawdatas = new byte[rawsize];
GCHandle handle = GCHandle.Alloc(rawdatas, GCHandleType.Pinned);
IntPtr buffer = handle.AddrOfPinnedObject();
Marshal.StructureToPtr(anything, buffer, false);
handle.Free();
return rawdatas;
}
// serializing object into string
public static string RawSerializeStr(object anything)
{
byte[] des2 = RawSerializeEx(anything);
ASCIIEncoding utf82 = new ASCIIEncoding();
string uf82 = utf82.GetString(des2);
return uf82;
}
convert byte array to string c
public string StrFromByte(byte[] des2)
{
ASCIIEncoding utf82 = new ASCIIEncoding();
string uf82 = utf82.GetString(des2);
return uf82;
}
convert string into array
byte[] s = Encoding.ASCII.GetBytes("convert this string into byte array");
the maximum array length quota 16384 has been exceeded while reading
this is client-side error, below is the correct way to call service:
[Test]
public void CC_Test_HTTPS()
{
//var svc = new Service();
//Console.WriteLine(svc.TransactionReport(args));
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(IgnoreCertificateErrorHandler);
var endpointAddress = new EndpointAddress("https://dev/CreateAccount/Service.svc");
var wsHttpBinding = new WSHttpBinding(SecurityMode.Transport)
{
MaxReceivedMessageSize = 2147483647,
MaxBufferPoolSize = 2147483647,
ReaderQuotas =
{
MaxStringContentLength = 2147483647,
MaxArrayLength = 2147483647,
MaxBytesPerRead = 2147483647,
MaxDepth = 2147483647
}
};
var s = ChannelFactory<IService>.CreateChannel(wsHttpBinding, endpointAddress);
NewAccountResp newAccountResp = s.CreateAccount(CCTestRequest);
}
Tuesday
constant array in c#
static readonly ArrayList a = new ArrayList() { "1", "2", "3", "4", "5", "6", "7", "8" };
public bool CheckIfContains(uint i)
{
return a.Contains(""+i);
}
template engine .net
using System.Collections;
namespace Business.CustomerServices
{
public class SimpleTemplateEngine
{
public string ReadFile(string f)
{
System.IO.StreamReader file = new System.IO.StreamReader(f);
string testxmldata = file.ReadToEnd(); file.Close();
return testxmldata;
}
public string RenderFile(Hashtable values, string fileName)
{
return Render(values, ReadFile(fileName));
}
public string Render(Hashtable values, string template)
{
foreach (DictionaryEntry entry in values)
{
template = template.Replace("{$" + entry.Key + "}",""+ entry.Value);
}
return template;
}
}
}
Wednesday
cannot convert from 'string' to 'System.Xml.Linq.XElement'
we can use XElement.Parse(modeldetail); to convert string into XElement.
Monday
wcf test client visual studio 2010
here is simple wcf service tester source:
using System;
using System.ServiceModel;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Business.CustomerServices;
using Business.WebService;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NUnit.Framework;
namespace BusinessWeb.Tests
{
[TestClass]
public class CreateAccountTester
{
[Test]
[Timestamp]
public void CreateAccount_Test()
{
var endpointAddress = new EndpointAddress(@"http://it003/CreateAccount/Service.svc");
var basicHttpBinding = new BasicHttpBinding();
basicHttpBinding.MaxReceivedMessageSize = 2147483647;
basicHttpBinding.ReaderQuotas.MaxStringContentLength = 2147483647;
var s = ChannelFactory<IService>.CreateChannel(basicHttpBinding, endpointAddress);
// now I can call webservice
NewAccountResp newAccountResp = s.CreateAccount(_newAccountArgs);
Console.WriteLine(newAccountResp.AuthResponse);
}
}
}
Subscribe to:
Posts (Atom)
make ubuntu business casual
to make ubuntu business casual - make it black remove background: gsettings set org.gnome.desktop.background picture-options ...
-
2010-11-24 Update: Please download latest version of Pidgin , that has this problem fixed , no additional steps required. Here are 3 ways to...
-
$dllPath = "C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\...
-
Error:The element 'Schedule' has invalid child element 'RecurrenceRule'. List of possible elements expected: 'Occurring...