Friday

remove namespace xml in serialisation by XmlSerializerNamespaces.dot.net/C#/csharp


 public static string toXML(Object obj)
{
XmlSerializer xmlSerializer = new XmlSerializer(obj.GetType());
StringWriter stringWriter = new StringWriter();
XmlWriterSettings writerSettings = new XmlWriterSettings();
writerSettings.OmitXmlDeclaration = true;
writerSettings.Indent = true;


using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter, writerSettings))
{

// Namespace removed in these two lines:
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");


xmlSerializer.Serialize(xmlWriter, obj,ns);

}
return stringWriter.ToString();
}

more...

List XMl serialization/deserialization

To serialize list by using class in previous post :


List<DefaultFeeForNewInvoice> fees = new List<DefaultFeeForNewInvoice>();
fees.Add(new DefaultFeeForNewInvoice() { FeeAmount = (decimal)4.5, FeeSubTypeID = 13, PaymentSourceID = 4 });
fees.Add(new DefaultFeeForNewInvoice() { FeeAmount = (decimal)4.5, FeeSubTypeID = 13, PaymentSourceID = 4 });
fees.Add(new DefaultFeeForNewInvoice() { FeeAmount = (decimal)4.5, FeeSubTypeID = 13, PaymentSourceID = 4 });

string str=CXMLConv.toXML(fees);


But for deserialization it'e required to use different method:


/// <summary>
/// Deserialize List dotnet/csharp
/// fees_con = (List<DefaultFeeForNewInvoice>) CXMLConv.Load(str_con, fees_con.GetType(), "ArrayOfDefaultFeeForNewInvoice");
/// </summary>
/// <param name="XMLString">The XML string.</param>
/// <param name="t">The type</param>
/// <param name="RootElementName">Name of the root element.</param>
/// <returns></returns>
static public object Load(string XMLString, Type t, string RootElementName)
{

XmlSerializer mySerializer =
new XmlSerializer(t, new XmlRootAttribute(RootElementName));

StringReader myReader =
new StringReader(XMLString);

return mySerializer.Deserialize(myReader);

}


sample of the call:

fees_con = (List<DefaultFeeForNewInvoice>) CXMLConv.Load(str_con, fees_con.GetType(), "ArrayOfDefaultFeeForNewInvoice");

more...

Dot.NET webservice to enable remote invoke/testing add to web.config under system.web


<system.web>
<webServices>
<protocols>
<add name="HttpPost" />
<add name="HttpGet" />
</protocols>
</webServices>

more...

xml serializer for xml serialization in c# (dot.net v3.5)



public class CXMLConv
{

public static T fromXML<T>(string x, T obj)
{
try {
XmlSerializer xmlSerializer = new XmlSerializer(obj.GetType());
StringReader stringReader = new StringReader(x);

return (T)xmlSerializer.Deserialize(stringReader);
}
catch (Exception ex) {
Logger.prn("Deserializing problem for XML:"+x,ex);
Assertions.Throw("Incorrect incoming XML specified." );
return obj;
}


}

public static string toXML(Object obj)
{
XmlSerializer xmlSerializer = new XmlSerializer(obj.GetType());
StringWriter stringWriter = new StringWriter();
XmlWriterSettings writerSettings = new XmlWriterSettings();
writerSettings.OmitXmlDeclaration = true;
writerSettings.Indent = true;

using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter, writerSettings))
{
xmlSerializer.Serialize(xmlWriter, obj);
}
return stringWriter.ToString();

}
}

more...

linq serialize xml and deserialize into IEnumerable objects ( XMLSerializer class on top post)


public class ProcessingFeeRuleProperty
{
public int FeeID;
public decimal FeeAmount;
}


[TestFixture]
public class UnitTest1
{
public UnitTest1()
{ }

[Test]
public void TestMethod2()
{
ProcessingFeeRuleProperty pr = new ProcessingFeeRuleProperty() {FeeID = 1, FeeAmount = 12};
ProcessingFeeRuleProperty pr2 = new ProcessingFeeRuleProperty() {FeeID = 2, FeeAmount = 24};


//Logger.prn(CXMLConv.toXML(pr));


List<ProcessingFeeRuleProperty> l=new List<ProcessingFeeRuleProperty>();
l.Add(pr);l.Add(pr2);

IEnumerable<ProcessingFeeRuleProperty> p = l;
Logger.prn(CXMLConv.toXML(p));



string xml_str =@"<ArrayOfProcessingFeeRuleProperty >
<ProcessingFeeRuleProperty>
<FeeID>1</FeeID>
<FeeAmount>12</FeeAmount>
</ProcessingFeeRuleProperty>
<ProcessingFeeRuleProperty>
<FeeID>2</FeeID>
<FeeAmount>24</FeeAmount>
</ProcessingFeeRuleProperty>
</ArrayOfProcessingFeeRuleProperty>
";


ProcessingFeeRuleProperty p2 = new ProcessingFeeRuleProperty();
CXMLConv.fromXML<IEnumerable<ProcessingFeeRuleProperty>>(xml_str,p);
foreach (var c in p) {
Logger.prn(c.FeeID.ToString(), c.FeeAmount.ToString());
}

var sel_fee = from x in p
where x.FeeID == 1
select x;

ProcessingFeeRuleProperty first= sel_fee.First();
Logger.prn("\n\n\n",first.FeeID.ToString(), first.FeeAmount.ToString());
}

XMLSerializer class on upper post
more...

Tuesday

linq group by sum and join example


var fees =
from p in i.AccountFees

group p by p.FeeID into g
select new { FeeID = g.Key, TotalAmount = g.Sum(p => p.Amount) };

foreach (var fee in fees) {
Logger.prn("" + fee.FeeID + ":" + fee.TotalAmount);
}


more...

Thursday

python sum of list/array and any all


::accumulators
def countall(it):return sum(1 for x in it )
if any(x>5 for x in xs): ...
if all(x>y>z for x,y,z in zip(xs,ys,ys)):

from itertools import izip
if all(x>y>z for x,y,z in izip(xs,ys,zs)):

print max(i for i, x in enumerate(xs) if x > 0)

with operator:
with open('myfile.txt') as f:
for aline in f: print alien[3]


more...

python containers:


tuple - immutable sequence : (2,3) tulpe ('ciao')
list - mutable sequence: [2,3] list('ciao')
set / frozenset : set() set ((23,)) set ('ciao')
dict map key-value: {2:3}, {4:5,6:7} dict(ci='oo')

All Containers support :
len(c)
iteration : for x in c
membership: if x in c

more...

python help function/command


to get list of all methods/properties use :
>>dir ('mystring')

to get help for 'center' method of string we use :
>>help(''.center)

more...

linq sum example / csharp


var activefees = from af in invoice.AccountFees
where af.StatusID == EnumStatusType.Open
select af;
return activefees.Sum(af => af.Amount);

// or more complicated with condition
decimal am = 0;
foreach (XAttribute v in rs.RuleAccountFeesToBill(customer_id)){
long f = long.Parse(v.Value);
am += activefees.Sum(acf => acf.AccountFeeSubType.AccountFeeType.FeeTypeID == f ? acf.Amount : 0 );
}


more...

Wednesday

linq to xml example:


using System.Linq;
using System.Xml.Linq;
[Test]
public void TestMethod1()
{
string xml_str = "<BillingTypes> <BillingType ID=\"1\" Description=\"Statement\" /> <BillingType ID=\"2\" Description=\"Coupon\" /> <BillingType ID=\"3\" Description=\"EFT\" /> <BillingType ID=\"4\" Description=\"Visa\" /> </BillingTypes>";
XDocument xml = XDocument.Parse(xml_str);
var allowed = from billingtype in xml.Elements("BillingTypes").Elements("BillingType")
where billingtype.Attribute("ID").Value == "3"
select billingtype;

foreach (var element in allowed){
Debug.Print(element.Attribute("Description").Value);
}

}

more...

linq example - use where for datacontext object


LinqDataObjectsDataContext dc = new LinqDataObjectsDataContext();
Invoice ret = dc.Invoices.Where(e => e.InvoiceID == id).SingleOrDefault();

more...

datacontext linq refresh example C# - linq example how to save object in linq to sql


public string SaveInvoiceXML(string sInvoice){
try{
Invoice inv = new Invoice();
inv = CXMLConv.fromXML<Invoice>(sInvoice, inv);

LinqDataObjectsDataContext dc = new LinqDataObjectsDataContext();

dc.Invoices.Attach(inv);
dc.Refresh(RefreshMode.KeepCurrentValues, inv);
dc.SubmitChanges();

return OK(CXMLConv.toXML(inv));
}
catch (Exception ex)
{
return RegisterError(ex, "SaveInvoiceXML", sInvoice);
}
}


more...

Linq to SQL C# linq join example


try{
LinqDataObjectsDataContext dc = new LinqDataObjectsDataContext();

/* select * from invoice inner join AccountInvoices on
* invoice.cust= AccountInvoices.cust and invoice.sub = AccountInvoices.sub
*/

StringBuilder sb = new StringBuilder();
sb.AppendFormat("<Invoices customer='{0}' sub='{1}'>", cust, sub);

var ret = from invoice in dc.Invoices
join accountInvoice in dc.AccountInvoices on
invoice.InvoiceID equals accountInvoice.InvoiceID
where accountInvoice.SubID ==sub && accountInvoice.CustomerID ==cust
select invoice;

foreach (Invoice i in ret){
sb.Append(CXMLConv.toXML(i));
}

sb.AppendLine("</Invoices>");
return OK(sb.ToString());
} catch (Exception ex) {
return RegisterError(ex, "getInvoicesXML","cust/sub"+cust+"/"+sub);
}

more...

Tuesday

to fix circular reference was detected while serializing an object:

in a c# - in all sub classes find reference to parent class and add
[XmlIgnore] attribute.
Bad news is that you have to do that for all objects every time dbml file was changed.
So I have create simple python script that do this for me:



import os
import re

file_to_patch='LinqDataObjects.designer.cs'
bak_file='LinqDataObjects.designer.cs.bak'
os.rename(file_to_patch,bak_file)

fileHandle = open ('linesToPatch.txt')
linesToPatch = fileHandle.readlines()

f = open(bak_file)
new_file=open(file_to_patch, 'w')
new_file.write("using System.Xml.Serialization;\n")

for aline in f:
new_file.write(aline)
for rline in linesToPatch:
if aline.strip() == rline.strip():
new_file.write("\t[XmlIgnore]\n")
break




linesToPatch.txt - is simple text file that contains all lines those must have XMLIgnore, for example:


[Association(Name="Invoice_AccountFee", Storage="_Invoice", ThisKey="InvoiceID", OtherKey="InvoiceID", IsForeignKey=true)]
[Association(Name="Accounts_basic_AccountInvoice", Storage="_Accounts_basic", ThisKey="CustomerID,SubID", OtherKey="customer_,sub", IsForeignKey=true)]
[Association(Name="Invoice_AccountInvoice", Storage="_Invoice", ThisKey="InvoiceID", OtherKey="InvoiceID", IsForeignKey=true)]
[Association(Name="AccountFeeType_AccountFeeSubType", Storage="_AccountFeeSubTypes", ThisKey="FeeTypeID", OtherKey="stFeeTypeID")]

Saturday

workout heart rates calculation



1. Calculate maximum hear rate for your age : MHR=214-(0.8 * Age)
example: for 33 years it will be 187.6 per min or 31.2 for ten seconds.

2.Comfort range must be between 60%-75% of maximum hear rate :
between MHR*0.6 and MHR*0.75 per minute or
MHR *0.6/6 and MHR*0.75/6

example: for 33 years it will be between 112.5 - 140.7 per minute or
between 18.75-23.45 per 10 seconds

count pulse during 10 second and make sure you are in comfort zone.
example:If you are 33 you must have from 18 to 23 pulses for 10 second.


more...

Friday

to fix wcf soap client error :

WSDLService :Processing service xxx found no port definitions HRESULT=0x80070057: The parameter is incorrect.
update web.config:
...
<services>
<service name="Business.WebService.Service1" behaviorConfiguration="Business.WebService.Service1Behavior">
<!-- Service Endpoints -->
find this line: <endpoint address="" binding="wsHttpBinding" contract="Business.WebService.IService1">
and replace with this one : <endpoint address="" binding="basicHttpBinding" contract="Business.WebService.IService1">

basicHttpBinding is compatible with old soap clients.
more...

imagemagic add text to image

rem different types of text annotations on existing images rem cyan yellow orange gold rem -gravity SouthWest rem draw text and anno...