public static int CacheDyration = 10;
/// <summary>
/// Cached Merchant table
/// </summary>
public static Hashtable MerchantHash
{
get
{
Hashtable retValue = null;
// Check if cache has Merchant saved
if (HttpContext.Current.Cache["MerchantHash"] != null)
{ // Return cached version
retValue = (Hashtable)HttpContext.Current.Cache["MerchantHash"];
}
else
{
// initializing new instance, you can change this initialization with using BLL classes
MerchantTableAdapter da = new MerchantTableAdapter();
retValue = Hashmaker.Hash(da.GetData(), "merchant_id", "merchantname");
if (retValue.Count > 0)
{
HttpContext.Current.Cache.Insert("MerchantHash", retValue, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, CacheDyration, 0));
}
}
return retValue;
}
set
{ // Check if item is already in there
if (HttpContext.Current.Cache["MerchantHash"] != null)
{
// Remove old item
HttpContext.Current.Cache.Remove("MerchantHash");
} // Place a new one
HttpContext.Current.Cache.Insert("MerchantHash", value, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, CacheDyration, 0));
}
}
Monday
c# property with using cache (expiration added)
clear cache in ASP.NET VB.NET
Private Sub ClearCache()
For Each CacheKey As DictionaryEntry In Cache
If CacheKey.Key.GetType.Equals(GetType(System.String)) Then
Dim MyKey As String = CacheKey.Key
Cache.Remove(CacheKey.Key)
End If
Next
End Sub
more...
Friday
Tuesday
Duplicate filename:7z:creating archive files from list
you have list of files from differen folders in text file.
To create zip archive use this command:
"c:\Program Files\7-Zip\7z.exe" a -tzip archive.zip @c:\listfile.txt
when you get error Duplicate filename: because of file with the same name in different folders, remove drive name from list file.

To create zip archive use this command:
"c:\Program Files\7-Zip\7z.exe" a -tzip archive.zip @c:\listfile.txt
when you get error Duplicate filename: because of file with the same name in different folders, remove drive name from list file.

Sunday
System.Data.StrongTypingException
to fix this exception in strong-type dataset use method IsNull method before reading value to avoid this exception.
in C# it will be like :
if (!logins[0].Isincorrect_attempt_dateNull())
{
incor_pass_hours_ago = DateTime.Now.Subtract((DateTime)logins[0].incorrect_attempt_date).TotalHours;
}

in C# it will be like :
if (!logins[0].Isincorrect_attempt_dateNull())
{
incor_pass_hours_ago = DateTime.Now.Subtract((DateTime)logins[0].incorrect_attempt_date).TotalHours;
}

fix "SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM."
Use System.Data.SqlTypes.SqlDateTime.MinValue.Value insted DateTime.MinValue and System.Data.SqlTypes.SqlDateTime.MaxValue.Value instead DateTime.MinValue.


Saturday
to transfer file by pscp (putty scp) to sftp (secured ftp) server:
source file: source1.txt
server ip : 61.155.5.15
server shh port : 2222
destination file:d\target1.txt
command line:
pscp -l al -P 2222 source1.txt user@67.155.5.15:d\target1.txt
pscp help:
PuTTY Secure Copy client
Release 0.57
Usage: pscp [options] [user@]host:source target
pscp [options] source [source...] [user@]host:target
pscp [options] -ls [user@]host:filespec
Options:
-p preserve file attributes
-q quiet, don't show statistics
-r copy directories recursively
-v show verbose messages
-load sessname Load settings from saved session
-P port connect to specified port
-l user connect with specified username
-pw passw login with specified password
-1 -2 force use of particular SSH protocol version
-C enable compression
-i key private key file for authentication
-batch disable all interactive prompts
-unsafe allow server-side wildcards (DANGEROUS)
-V print version information
-sftp force use of SFTP protocol
-scp force use of SCP protocol

server ip : 61.155.5.15
server shh port : 2222
destination file:d\target1.txt
command line:
pscp -l al -P 2222 source1.txt user@67.155.5.15:d\target1.txt
pscp help:
PuTTY Secure Copy client
Release 0.57
Usage: pscp [options] [user@]host:source target
pscp [options] source [source...] [user@]host:target
pscp [options] -ls [user@]host:filespec
Options:
-p preserve file attributes
-q quiet, don't show statistics
-r copy directories recursively
-v show verbose messages
-load sessname Load settings from saved session
-P port connect to specified port
-l user connect with specified username
-pw passw login with specified password
-1 -2 force use of particular SSH protocol version
-C enable compression
-i key private key file for authentication
-batch disable all interactive prompts
-unsafe allow server-side wildcards (DANGEROUS)
-V print version information
-sftp force use of SFTP protocol
-scp force use of SCP protocol

Wednesday
python post example
from httplib2 import Http
from urllib import urlencode
url = 'http://de.gigajob.com/req.ax'
#body = {'USERNAME': 'foo', 'PASSWORD': 'bar'}
#headers = {'Content-type': 'application/x-www-form-urlencoded'}
body={'xajax':'ajax_get_sgd_html_display' ,'xajaxargs':'<xjxobj><e><k>searchword</k><v>C%23</v></e><e><k>zip</k><v></v></e><e><k>adtype</k><v>offer</v></e><e> <k>distance</k><v>25</v></e><e><k>country</k><v>all</v></e><e><k>language</k><v>de</v></e><e><k>page</k><v>1</v></e><e><k>sort</k><v>age</v></e><e><k>location</k><v></v></e><e><k>age</k><v>999</v></e></xjxobj>' ,'xajaxargs':'1' ,'xajaxargs':'1' ,'xajaxr':'1234400546535'}
h = Http()
response, content = h.request(url,'POST',urlencode(body))
print response
print content
more...
Tuesday
C# regexps to correct reflector dissamble:
correct property setting:
.set_(?'n'.*?)\((?'v'.*?)\);
.${n}=${v};
.set_(?'n'.*?)\((?'v'.*?)\);
.${n}=${v};
Friday
easy_install.exe for Python 2.6 on Windows
get ez_setup.py and setuptools-0.6c9-py2.6.egg.
type: python ez_setup.py setuptools-0.6c9-py2.6.egg and that should get setuptools installed.
2. Now that you have setuptools installed, in your Python 2.6 directory there is a directory called Scripts. If you go to that directory (C:\Python26\Scripts on the systems I worked on) you’ll see easy_install.exe.
type: python ez_setup.py setuptools-0.6c9-py2.6.egg and that should get setuptools installed.
2. Now that you have setuptools installed, in your Python 2.6 directory there is a directory called Scripts. If you go to that directory (C:\Python26\Scripts on the systems I worked on) you’ll see easy_install.exe.
Monday
aspnet_compiler.exe [HttpCompileException]: External component has thrown an exception.
I was getting this error during the pre-compilation of website:
[HttpCompileException]: External component has thrown an exception.
the cause of the problem was incorrect references in web.config.
Here's rebuild.bat file for precompilation website without opening Visual Studio 2008:
compilation of about 500 classes taking about 15 min , sndrec32 string for notifying that build complete.
[HttpCompileException]: External component has thrown an exception.
the cause of the problem was incorrect references in web.config.
Here's rebuild.bat file for precompilation website without opening Visual Studio 2008:
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_compiler.exe -v "/beta " -p "beta\\" -u -f -d -fixednames "PrecompiledWeb\beta\\" -errorstack
sndrec32.exe /play /embedding c:\tools\saundz\phone_1.wav
pause
compilation of about 500 classes taking about 15 min , sndrec32 string for notifying that build complete.
python indentation fixing:by removing tabs
to remove tabs and correct indentation use this command in VIM:
:set expandtab
:retab!
Friday
variables in dot net regular expressions
search pattern : \s*<Merchant>\s*<ID>(?'d'.*?)</ID>
replace pattern:
NF:${d}.xml
<Merchant>
<ID>${d}</ID>
As you can see d is variable declared in search pattern and used into replace:
Also here is interpretation of search pattern :
Options: dot matches newline; free-spacing
Match a single character that is a “whitespace character” (spaces, tabs, line breaks, etc.) «\s*»
Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
Match the characters “<Merchant>” literally «<Merchant>»
Match a single character that is a “whitespace character” (spaces, tabs, line breaks, etc.) «\s*»
Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
Match the characters “<ID>” literally «<ID>»
Match the regular expression below and capture its match into backreference with name “d” «(?'d'.*?)»
Match any single character «.*?»
Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Match the characters “</ID>” literally «</ID>»
replace pattern:
NF:${d}.xml
<Merchant>
<ID>${d}</ID>
As you can see d is variable declared in search pattern and used into replace:
Also here is interpretation of search pattern :
Options: dot matches newline; free-spacing
Match a single character that is a “whitespace character” (spaces, tabs, line breaks, etc.) «\s*»
Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
Match the characters “<Merchant>” literally «<Merchant>»
Match a single character that is a “whitespace character” (spaces, tabs, line breaks, etc.) «\s*»
Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
Match the characters “<ID>” literally «<ID>»
Match the regular expression below and capture its match into backreference with name “d” «(?'d'.*?)»
Match any single character «.*?»
Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Match the characters “</ID>” literally «</ID>»
Tuesday
mask credit card by regular expressions (regexp) in (Regex.Replace/vb.net)
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim regFind As String = "<AccountNumber>(?'f'\d?)\d\d\d\d\d\d\d\d\d\d(?'e'.*?)</AccountNumber>"
Dim regReplace As String = "<AccountNumber>${f}**${e}</AccountNumber>"
TextBox1.Text = Regex.Replace(TextBox1.Text, regFind, regReplace)
End Sub
dot.net 3.5 from visual studio 2008
Monday
sql xml remove tag (sql server 2008)
DECLARE @x XML;
SELECT @x = N'<?xml version="1.0" ?>
<Address>
<Street>1 MICROSOFT WAY</Street>
<City>REDMOND</City>
<State>WA</State>
<Zip>98052</Zip>
<Country>US</Country>
<Website></Website>
</Address>';
SET @x.modify('
delete /Address/Website
');
SELECT @x;
Thursday
get list of installed software on computer
with Powershell
:
$Keys = Get-ChildItem HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall
$Items = $keys |foreach-object {Get-ItemProperty $_.PsPath}
foreach ($item in $items)
{
echo $item.Displayname
echo $item.DisplayVersion
echo $item.Publisher
echo $item.InstallDate
echo $item.HelpLink
echo $item.UninstallString
}
more...
remove blinking on aspx page reloading
add these two lines to page source to eliminate this problem :
<meta http-equiv="Page-Enter" content="blendTrans(Duration=0.2)"/>
<meta http-equiv="Page-Exit" content="blendTrans(Duration=0.2)"/>
this will solve page blinking problem for internet explorer.
more...
<meta http-equiv="Page-Enter" content="blendTrans(Duration=0.2)"/>
<meta http-equiv="Page-Exit" content="blendTrans(Duration=0.2)"/>
this will solve page blinking problem for internet explorer.
more...
Saturday
remove banners in google chrome
I'm going to try privoxy. this little proxy server that allows to remove ads by specifying patterns.
Actually firefox Adblock Plus did perfect job,but chrome is much fester .
Probably it's possible to modify privoxy (it's open source) for working with banners lists like EasyList (USA)
http://easylist.adblockplus.org/adblock_rick752.txt
And add some new pages to privoxy, that allows to add new patterns on fly.
Or just wait when adblock will be ported on Google Chrome :)
what do you think?
Actually firefox Adblock Plus did perfect job,but chrome is much fester .
Probably it's possible to modify privoxy (it's open source) for working with banners lists like EasyList (USA)
http://easylist.adblockplus.org/adblock_rick752.txt
And add some new pages to privoxy, that allows to add new patterns on fly.
Or just wait when adblock will be ported on Google Chrome :)
what do you think?
Friday
Convert WMA Into MP3 (free/no-installation)
0. download and unpack these apps : MPlayer and lame
1. Convert the WAV file by this command:
mplayer -vo null -vc dummy -af resample=44100 -ao pcm "Song 1.wma"
1. Convert the WAV file by this command:
mplayer -vo null -vc dummy -af resample=44100 -ao pcm "Song 1.wma"
2. convert into MP3 the result of step 1 (audiodump.wav).
lame audiodump.wav "Song 1.mp3"
3. delete large wav file created in step 1(audiodump.wav)
Wednesday
dump dataset structure in debug/runtime
EmployeeDetail_Dataset.WriteXml("c:\temp.xml")
now xml reflecting the dataset will be in c:\temp.xml
more...
now xml reflecting the dataset will be in c:\temp.xml
more...
dot.net application or dot.net dll location VB.NET/C#
here's few ways to get application/dot net dll location :
System.AppDomain.CurrentDomain.BaseDirectory
System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase
for ASP.NET u can use following :
Server.MapPath(".")
more...
System.AppDomain.CurrentDomain.BaseDirectory
System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase
for ASP.NET u can use following :
Server.MapPath(".")
more...
Javascript log/debug window for client-site logging
1.Add this code to page or include
use log('my message') function in javascript to show data in window during javascript execution.
more...
var okno;
okno=window.open("", "Debug", "left=0,top=0,width=300,height=700,scrollbars=yes," +"status=yes,resizable=yes");
function log(msg){
okno.document.write("<br>"+msg);
}
use log('my message') function in javascript to show data in window during javascript execution.
more...
Tuesday
Regular Expressions - Strong Password Validation
string r =
@"(?x)" + // Ignore spaces within regex expression, for readability
@"^" + // Anchor at start of string
@"(?=.* ( \d | \p{P} | \p{S} ))" + // String must contain a digit or punctuation char or symbol
@".{6,}"; // String must be at least 6 characters in length
Console.WriteLine (Regex.IsMatch ("abc12", r));
Console.WriteLine (Regex.IsMatch ("abcdef", r));
Console.WriteLine (Regex.IsMatch ("ab88yz", r));
more...
Grouping with LINQ to SQL filtered
// The following groups purchases by year, then returns only those groups where
// the average purchase across the year was greater than $1000:
from p in Purchases
group p.Price by p.Date.Year into salesByYear
where salesByYear.Average (x => x) > 1000
select new
{
Year = salesByYear.Key,
TotalSales = salesByYear.Count(),
AvgSale = salesByYear.Average(),
TotalValue = salesByYear.Sum()
}
more...
LINQ Join vs SelectMany:what is faster?
Customer[] customers = Customers.ToArray();
Purchase[] purchases = Purchases.ToArray();
var slowQuery =
from c in customers
from p in purchases where c.ID == p.CustomerID
select c.Name + " bought a " + p.Description;
var fastQuery =
from c in customers
join p in purchases on c.ID equals p.CustomerID
select c.Name + " bought a " + p.Description;
slowQuery.Dump ("Slow local query with SelectMany");
fastQuery.Dump ("Fast local query with Join");
more...
Monday
convert sources into html /free
Generate XML with LINQ (C#)
var customers =
new XElement ("customers",
from c in Customers
select
new XElement ("customer", new XAttribute ("id", c.ID),
new XElement ("name", c.Name),
new XElement ("buys", c.Purchases.Count)
)
);
customers.Dump();
more...
command line xml parser ( free, open source)
located @ http://xmlstar.sourceforge.net/
more...
XMLStarlet Toolkit: Command line utilities for XML
Usage: xml [] [ ]
whereis one of:
ed (or edit) - Edit/Update XML document(s)
sel (or select) - Select data or query XML document(s) (XPATH, etc)
tr (or transform) - Transform XML document(s) using XSLT
val (or validate) - Validate XML document(s) (well-formed/DTD/XSD/RelaxNG)
fo (or format) - Format XML document(s)
el (or elements) - Display element structure of XML document
c14n (or canonic) - XML canonicalization
ls (or list) - List directory as XML
esc (or escape) - Escape special XML characters
unesc (or unescape) - Unescape special XML characters
pyx (or xmln) - Convert XML into PYX format (based on ESIS - ISO 8879)
p2x (or depyx) - Convert PYX into XMLare:
--version - show version
--help - show help
Wherever file name mentioned in command help it is assumed
that URL can be used instead as well.
Type: xml--help for command help
XMLStarlet is a command line toolkit to query/edit/check/transform
XML documents (for more information see http://xmlstar.sourceforge.net/)
more...
Sunday
how to change header in blogger
U can create script like that :
more...
<script type="text/javascript">
var container = document.getElementById("header-inner");
container.innerHTML ="http://sourcefield.blogspot.com";
</script>
more...
Monday
Service has zero application (non-infrastructure) endpoints FIX
During installation of the webservice I discovered inresting error:
This is more IIS issue, webserver has default directory that was deleted and currently not exists.
That caused the problem,so after changing default directory all started working.
more...
WebHost failed to process a request.
Sender Information: System.ServiceModel.Activation.HostedHttpRequestAsyncResult/25773083
Exception: System.ServiceModel.ServiceActivationException: The service '/Business/Service.svc' cannot be activated due to an exception during compilation.
The exception message is: Service 'Business.WebService.Service' has zero application (non-infrastructure) endpoints. This might be because no configuration file was found for your application, or because no service element matching the service name could be found in the configuration file, or because no endpoints were defined in the service element..
System.InvalidOperationException: Service 'Business.WebService.Service' has zero application (non-infrastructure) endpoints. This might be because no configuration file was found for your application, or because no service element matching the service name could be found in the configuration file, or because no endpoints were defined in the service element.
at System.ServiceModel.Description.DispatcherBuilder.EnsureThereAreNonMexEndpoints(ServiceDescription description)
at System.ServiceModel.Description.DispatcherBuilder.InitializeServiceHost(ServiceDescription description, ServiceHostBase serviceHost)
at System.ServiceModel.ServiceHostBase.InitializeRuntime()
at System.ServiceModel.ServiceHostBase.OnBeginOpen()
at System.ServiceModel.ServiceHostBase.OnOpen(TimeSpan timeout)
at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
at System.ServiceModel.ServiceHostingEnvironment.HostingManager.ActivateService(String normalizedVirtualPath)
at System.ServiceModel.ServiceHostingEnvironment.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath)
--- End of inner exception stack trace ---
at System.ServiceModel.AsyncResult.End[TAsyncResult](IAsyncResult result)
at System.ServiceModel.Activation.HostedHttpRequestAsyncResult.End(IAsyncResult result)
Process Name: w3wp
Process ID: 1680
This is more IIS issue, webserver has default directory that was deleted and currently not exists.
That caused the problem,so after changing default directory all started working.
more...
Wednesday
vb6 or asp xsl transform (transformNode)
Private Function Transform(xml_string, xsl_file) As String
Dim xsl, XML
Set xsl = CreateObject("Microsoft.XMLDOM")
Set XML = CreateObject("Microsoft.XMLDOM")
xsl.Load (xsl_file)
XML.LoadXml (xml_string)
Transform = XML.transformNode(xsl)
End Function
more...
Friday
LINQ:check if IEnumerable is empty (CSharp/C#)
public static void NonEmpty<T>(IEnumerable<T> source,string m){
if (source == null) Throw(m);
if (!source.Any()) Throw(m);
}
more...
Local sequence cannot be used in LINQ to SQL implementation of query operators except the Contains() operator
System.NotSupportedException: Local sequence cannot be used in LINQ to SQL implementation of query operators except the Contains() operator
Method has no supported translation to SQL
The cause of these errors may be mismatch b/w server and client side properties.
Or b/w properties those have SQL presentation and that hasn't:
private IQueryable<Invoice> AttachInvoices(LinqDataObjectsDataContext dc,string sInvoices) {
List<InvArg> ral = new List<InvArg>();
ral = (List<InvArg>)CXMLConv.Load(sInvoices, ral.GetType(), "ArrayOfInvArg") ;
IEnumerable<InvArg> ra = ral;
var inv = from i in dc.Invoices
join r in ra on i.InvoiceID equals r.InvoiceID
select i;
return inv;
}
must be modified to :
private List<Invoice> AttachInvoices(LinqDataObjectsDataContext dc,string sInvoices) {
List<InvArg> ral = new List<InvArg>();
ral = (List<InvArg>)CXMLConv.Load(sInvoices, ral.GetType(), "ArrayOfInvArg");
long[] s=ral.Select(p => p.InvoiceID).ToArray();
var inv = from i in dc.Invoices
where s.Contains(i.InvoiceID)
select i;
return inv.ToList();
}
more...
Thursday
display html on vb6 form
1.add Microsoft Internet controls to link reference.
2.Place control on form, I used 'Browser' as control name.
use this function to display :
more...
2.Place control on form, I used 'Browser' as control name.
use this function to display :
Private Sub ShowHtml(s As String)
Browser.Navigate ("about:blank")
' Dim doc As IHTMLDocument2
Set boxDoc = Browser.Document
boxDoc.Write (s)
boxDoc.Close
End Sub
more...
play sound in console or bat file
to play sound in console or bat file use this line
sndrec32.exe /play /embedding c:\i386\Blip.wav
more...
sndrec32.exe /play /embedding c:\i386\Blip.wav
more...
Wednesday
run regsvr32 command for all files in folder
you can create simple bat file with one line
--regdir--
for %%f in (%1\*.ocx) do (regsvr32 /s "%%f")
--end of regdir--
then run >: regdir c:\mylibs
that might be useful if you want to run command for all files
more...
--regdir--
for %%f in (%1\*.ocx) do (regsvr32 /s "%%f")
--end of regdir--
then run >: regdir c:\mylibs
that might be useful if you want to run command for all files
more...
Tuesday
allow opening chm file from network drives
add this key to registry, or copy-paste it into reg file execute:
---Begin Reg FILE--
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\HTMLHelp\1.x\ItssRestrictions]
"MaxAllowedZone"=dword:00000001
---End Reg FILE--
more...
---Begin Reg FILE--
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\HTMLHelp\1.x\ItssRestrictions]
"MaxAllowedZone"=dword:00000001
---End Reg FILE--
more...
Monday
Thursday
content length quota (8192) has been exceeded fix
to fix this error in Acessing WCF service:
do folowing :
1.Open web.config file and add these content under system.serviceModel:
2.Find this line and add bindingConfiguration :
more...
The formatter threw an exception while trying to deserialize the message:
Error in deserializing body of request message for operation 'FreezeInvoices'.
The maximum string content length quota (8192) has been exceeded while reading XML data.
This quota may be increased by changing the MaxStringContentLength property on the XmlDictionaryReaderQuotas object used when creating the XML reader. Line 1,
do folowing :
1.Open web.config file and add these content under system.serviceModel:
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="Binding1" closeTimeout="00:11:00" openTimeout="00:11:00" receiveTimeout="00:10:00" sendTimeout="00:10:00" allowCookies="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="9965536" maxBufferPoolSize="9524288" maxReceivedMessageSize="9965536" messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" >
<readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
<security mode="None" />
</binding>
</basicHttpBinding>
</bindings>
2.Find this line and add bindingConfiguration :
<endpoint address="" binding="basicHttpBinding" contract="Business.WebService.IService" bindingConfiguration="Binding1">
more...
Wednesday
python setdefault in indexing text file
indx={}
with open(filename) as f:
for n,line in enumerate(f):
for word in line.split():
indx.setdefault(word,[]).append(n)
#emit in alphabetical order
for word in sorted(indx):
print "%s:" % word
for n in indx[word]: print n,
more...
python property & dunder special methods
#property sample
class blah(object)
def getter(self):
return ...
def setter(self,value):
....
name=property(getter,setter)
inst=blah()
print inst.name #calls inst.getter()
inst.name=23 #like call inst.setter(23)
python special methods (dobleundescore aka dunder):
__new__ __init__ __del__ # ctor,init, finalize
__repr__ __str__ __int__ # convert
__lt__ __gt__ __eq__ # compare
__add__ __sub__ __mul__ # arithmetic
__call__ __hash__ __nonzero__ # ()
__getattr__ __setattr__ __delattr__ #
__getitem__ __setitem__ __delitem__ #
__len__ __iter__ __contains__ #
__get__ __set__ __enter__ __exit__
here's sample of using special methods
class fib(object):
def __init__(self): self.i=self.j=1
def __iter__(self): return self
def next(self):
r,self.i=self.i,self.j
self.j+=r
return r
for r in fib():
print r,
if r > 100: break
1 1 2 3 5 8 13 21 34 55 89 144
more...
python functions generators closures decorators
Types of arguments:
#default values:
def sub1( a,b='default',i=0)named arguments
def info(spacing=15, object=odbchelper):tuple (args,params)
def sumsq2(*a): return sum(x*x for x in a)dictionary
def sumsq2(**a):generators in python - used yield insted of return
def fibonacci()
i=j=1
while True:
r,i,j = i,j,i+j
yield r
for rabbits in fibonacci():
print rabbits
if rabbit > 100 : break
>>
1 1 2 3 5 8 13 21 34 55 89 144Closures
def makeAdder(addend):
def adder(augend):
return audend + addend
return adder
a23=MakeAdder(23)
a42=MakeAdder(42)
print a23(100) , a42(100) , a23(a42(100))
>> 123 142 165decorators
@<decor>
def <name>
#is like
def (name)
name = <decor>(<name>)
#or another example
@dec2
@dec1
def func(arg1, arg2, ...):
pass
#This is equivalent to:
def func(arg1, arg2, ...):
pass
func = dec2(dec1(func))and singleton example
def singleton(cls):
instances = {}
def getinstance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return getinstance
@singleton
class MyClass:
...
more...
XElement.Parse using and create xml with linq:
linq transformation sample xml xelement.parse used
XElement project = XElement.Parse (@"
<Project DefaultTargets=""Build"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">
<PropertyGroup>
<Platform Condition="" '$(Platform)' == '' "">AnyCPU</Platform>
<ProductVersion>9.0.11209</ProductVersion>
</PropertyGroup>
<ItemGroup>
<Compile Include=""ObjectGraph.cs"" />
<Compile Include=""Program.cs"" />
<Compile Include=""Properties\AssemblyInfo.cs"" />
<Compile Include=""Tests\Aggregation.cs"" />
<Compile Include=""Tests\Advanced\RecursiveXml.cs"" />
</ItemGroup>
</Project>");
XNamespace ns = project.Name.Namespace;
var query =
new XElement ("ProjectReport",
from compileItem in project.Elements (ns + "ItemGroup").Elements (ns + "Compile")
let include = compileItem.Attribute ("Include")
where include != null
select new XElement ("File", include.Value)
);
query.Dump();
and results will be:
<ProjectReport>
<File>ObjectGraph.cs</File>
<File>Program.cs</File>
<File>Properties\AssemblyInfo.cs</File>
<File>Tests\Aggregation.cs</File>
<File>Tests\Advanced\RecursiveXml.cs</File>
</ProjectReport>
more...
Saturday
wcf 404 not found on .csv file (server 2003) .NET 3.0/3.5
To fix this 404 error when openening .csv file
in browser see
this post:
it has basic steps of wcf (Windows Communication Foundation) dot.NET 3.0/3.5 initialization on IIS 6.
in browser see
this post:
it has basic steps of wcf (Windows Communication Foundation) dot.NET 3.0/3.5 initialization on IIS 6.
Friday
get last date of month - csharp
private DateTime LastDayOfMonth(DateTime d)
{
DateTime d = new DateTime(d.Year, d.Month, 1);
return d.AddMonths(1).AddDays(-1);
}
more...
register wcf service on iis by servicemodelreg.exe
I reinstalled aspnet (just in case) this step may be omited:
1.Run service modeling utility: ServiceModelReg.exe /i /x
2. run it again with this key: ServiceModelReg.exe /s:W3SVC
As optional you may refresh this :
c:\WINDOWS\Microsoft.NET\Framework\v3.5\WFServicesReg.exe /r
c:\WINDOWS\Microsoft.NET\Framework\v3.5\WFServicesReg.exe /c
http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/95bdf2fa-3e2d-489d-8873-31f0da816577/
more...
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727>aspnet_regiis.exe -i
Start installing ASP.NET (2.0.50727).
..........................
Finished installing ASP.NET (2.0.50727).
1.Run service modeling utility: ServiceModelReg.exe /i /x
C:\WINDOWS\Microsoft.NET\Framework\v3.0\Windows Communication Foundation>ServiceModelReg.exe /i /x
Microsoft(R) Windows Communication Foundation Installation Utility
[Microsoft (R) Windows (R) Communication Foundation, Version 3.0.4506.2152]
Copyright (c) Microsoft Corporation. All rights reserved.
Installing: Machine.config Section Groups and Handlers
Installing: System.Web Build Provider
Installing: System.Web Compilation Assemblies
Installing: HTTP Handlers
Installing: HTTP Modules
Installing: Web Host Script Mappings
Installing: WMI Classes
Installing: Windows CardSpace (idsvc)
Installing: Net.Tcp Port Sharing Service (NetTcpPortSharing)
Installing: HTTP Namespace Reservations
2. run it again with this key: ServiceModelReg.exe /s:W3SVC
C:\WINDOWS\Microsoft.NET\Framework\v3.0\Windows Communication Foundation>Service
ModelReg.exe /s:W3SVC
Microsoft(R) Windows Communication Foundation Installation Utility
[Microsoft (R) Windows (R) Communication Foundation, Version 3.0.4506.2152]
Copyright (c) Microsoft Corporation. All rights reserved.
Installing: Web Host Script Mappings
As optional you may refresh this :
c:\WINDOWS\Microsoft.NET\Framework\v3.5\WFServicesReg.exe /r
c:\WINDOWS\Microsoft.NET\Framework\v3.5\WFServicesReg.exe /c
http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/95bdf2fa-3e2d-489d-8873-31f0da816577/
more...
Thursday
add google search to website
To add google search box please copy code below. (replace sourcefield.blogspot.com with your address)
Also you can get free virus protection from google within google pack.
Also you can get free virus protection from google within google pack.
<input class="BlogSearch" type="text" name="searchBox" id="blogSearchText" value="" onkeypress="return blogSearch(event, this);">
<input type="button" value="Search" onclick="return blogSearch2('blogSearchText');" class="BlogSearchButton">
<script type="text/javascript">
function blogSearch(event, oInput) {
var keyCode = (event) ? event.keyCode : keyStroke.which;
if (keyCode == 13) {
top.location = 'http://www.google.com/search?q=' + escape(oInput.value) + '+site%3Asourcefield.blogspot.com';
return false;
} return true;
}
function blogSearch2(oInputId) {
var oInput = document.getElementById(oInputId);
top.location = 'http://www.google.com/search?q=' + escape(oInput.value) + '+site%3Asourcefield.blogspot.com';
return false;
}
</script>
where to buy visual studio 2008
I downloaded Free 90-Day Trial from Microsoft and was defying all challenges with success :).
Now time has come today to buy, so I was looking for deals on studio in the market.
There is a lot academic versions software for students on "Academic superstore" for teachers students and schools.
First obvious thing I can buy standard edition or professional edition on Amazon, they have free shipping,
but there are a lot of other hot deals as well, let's compare prices:
Visual.EverythingOutlet from $149
SoftwareKing - from $149
AcademicSuperstore - from $195
Amazon - 249.99
buypcsoft has it from $679.95
I'm still looking for visual studio so if anybody did it , please share your experience.
more...
Now time has come today to buy, so I was looking for deals on studio in the market.
There is a lot academic versions software for students on "Academic superstore" for teachers students and schools.
First obvious thing I can buy standard edition or professional edition on Amazon, they have free shipping,
but there are a lot of other hot deals as well, let's compare prices:
Visual.EverythingOutlet from $149
SoftwareKing - from $149
AcademicSuperstore - from $195
Amazon - 249.99
buypcsoft has it from $679.95
I'm still looking for visual studio so if anybody did it , please share your experience.
more...
linq examples in linqpad
just downloaded linqpad, it contains a lot of examples linq to sql from C# 3.0 in a Nutshell book.
including linq grouping and linq join ,nice linq tutorial that allows to run your own linq queries.
more...
including linq grouping and linq join ,nice linq tutorial that allows to run your own linq queries.
more...
Monday
linq transactions support/Charp/dot.net 3.5
[Test]
public void StoredProcedure_and_LinqUpdates_Test()
{
// dx is datacontext instance
dx.Connection.Open();
dx.Transaction = dx.Connection.BeginTransaction();
// calling stored procedure from linq here
var result = dx.PaymentServices_ApplyPaymentToAccount(89);
// updating objects from context
Invoice i = customerService.getInvoice(277);
i.DueDate = Convert.ToDateTime("11/5/2008");
// submitting changes and committing transaction
dx.SubmitChanges();
dx.Transaction.Commit();
// rollback transactions and
// no changes made in object or by stored procedure will be stored
dx.Transaction.Rollback();
}
more...
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 :
But for deserialization it'e required to use different method:
sample of the call:
more...
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:
linesToPatch.txt - is simple text file that contains all lines those must have XMLIgnore, for example:
[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:
...
basicHttpBinding is compatible with old soap clients.
more...
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...
Tuesday
javascript transformnode or javascript transform xml
XSL transformation in javascript
// ake xmldoc for client -side transformations
function MakeXMLDoc()
{
var xmlDoc;
// code for IE
if (window.ActiveXObject){
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
}
// code for Mozilla, Firefox, Opera, etc.
else if (document.implementation && document.implementation.createDocument) {
xmlDoc=document.implementation.createDocument("","",null);
}else{
alert('Your browser cannot handle this script');
}
xmlDoc.async=false;
return(xmlDoc);
}
function XSLTrasformer(xml,xsl,span_name) // >[:>]
{
//xml=loadXMLDoc("1.xml");
//xsl=loadXMLDoc("NovaSettleResponse.xsl");
// code for IE
if (window.ActiveXObject)
{
ex=xml.transformNode(xsl);
document.getElementById(span_name).innerHTML=ex;
}
// code for Mozilla, Firefox, Opera, etc.
else if (document.implementation
&& document.implementation.createDocument)
{
xsltProcessor=new XSLTProcessor();
xsltProcessor.importStylesheet(xsl);
resultDocument = xsltProcessor.transformToFragment(xml,document);
document.getElementById(span_name).appendChild(resultDocument);
}
}
function XMLPopup(xml_string,xsl_file){
xsl=MakeXMLDoc(); xml=MakeXMLDoc();
xsl.load(xsl_file);
xml.loadXML(xml_string);
ex=xml.transformNode(xsl);
//document.getElementById(span_name).innerHTML=ex;
var dbgwin;
//left=0,top=0,
dbgwin=window.open("", "xml_pop", "width=420,height=540,scrollbars=yes,status=yes,resizable=yes");
dbgwin.document.write(ex);
dbgwin.document.write("<p><input type='button' onclick='window.close();' value='close'></p>");
}
call web service from classic asp or vb6 (SOAP Toolkit 3.0)
1.download and install SOAP Toolkit 3.0 from microsoft website
2.here is sample of calling asp.net web service from classic asp:
on this sample XML returning from one of services methods will transformed by xslt and writed on page.
more...
2.here is sample of calling asp.net web service from classic asp:
on this sample XML returning from one of services methods will transformed by xslt and writed on page.
<%
Dim SoapClient
Application.Lock
Set SoapClient = Server.CreateObject("MSSOAP.SoapClient30")
SoapClient.ClientProperty("ServerHTTPRequest") = True
'production url
SoapClient.MSSoapInit "https://services.server.com/clientalerts/alert.asmx?WSDL"
'add
Set Application("CalcRpcAspVbsClient") = SoapClient
Application("CalcRpcAspVbsClientInitialized") = True
Application.UnLock
'call as usual
Response.Write SoapClient.Transformdata("c:\xslt\setup.xslt", SoapClient.getSubscriptions(Session("DealerId")))%>
more...
System.Web.HttpException: Maximum request length exceeded
to fix this exception add line to web.config :
Transferring large objects over webservice (MSDN)
more...
<httpRuntime maxRequestLength="81920" executionTimeout="900" />
</system.web>
</configuration>
Transferring large objects over webservice (MSDN)
more...
Monday
System.Net.WebException: The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.
[Web Service in .net , webservice security]
when call webservice with bad certificate (VB.NET)
more...
when call webservice with bad certificate (VB.NET)
1.Add imports
Imports System.Net.Security
Imports System.Security.Cryptography.X509Certificates
2.before calling webservice:
ServicePointManager.ServerCertificateValidationCallback = New RemoteCertificateValidationCallback(AddressOf customXertificateValidation)
3.Custom certificate runner:
Private Shared Function customXertificateValidation(ByVal sender As Object, ByVal cert As X509Certificate, ByVal chain As X509Chain, ByVal Errora As SslPolicyErrors) As Boolean
Return True
End Function
more...
Saturday
Autojump: Jumping game script : autohotkey
SetKeyDelay, 75, 75
;Exits AutoHotKey application.
$^CapsLock::
ExitApp
return
;Pauses AutoHotKey Script.
F6::Pause, Toggle, 1
$x::
Loop {
Send, {Space}
sleep 60
Send, {Space}
sleep 60
Send, {Space}
sleep 60
Send, {Space}
}
more...
Wednesday
Ho wto fix "the definition of object * has changed since it was compiled." error:
run fololowing :
exec sp_recompile sp_your_name
OUTPUT:
Object 'sp_yourname' was successfully marked for recompilation.
more...
exec sp_recompile sp_your_name
OUTPUT:
Object 'sp_yourname' was successfully marked for recompilation.
more...
Tuesday
make xsd from xml (C#/csharp)
[Test]
public void generateXsd() {
DataSet d = new DataSet();
d.ReadXml(@"C:\projects\LeadInformation.xml");
d.WriteXmlSchema(@"C:\projects\LeadInformation.xsd");
}
more...
Thursday
grep how to find recursively all files with keywords from keyword file
assume that kw.txt is text file with keywords we have to find , then :
grep -irn -f ../kw.txt . *
more...
grep -irn -f ../kw.txt . *
more...
TSQL:MS SQL SERVER:Find stored procedure by keyword or column
SELECT sys.sysobjects.name, sys.syscomments.text
FROM sys.sysobjects INNER JOIN syscomments
ON sys.sysobjects.id = sys.syscomments.id
WHERE sys.syscomments.text LIKE '%single_pay_renew%'
AND sys.sysobjects.type = 'P'
ORDER BY sys.sysobjects.NAME
more...
Friday
WINService in python sample
import win32serviceutil
import win32service
import win32event
class SmallestPythonService(win32serviceutil.ServiceFramework):
_svc_name_ = "SmallestPythonService"
_svc_display_name_ = "The smallest possible Python Service"
def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, args)
# Create an event which we will use to wait on.
# The "service stop" request will set this event.
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
def SvcStop(self):
# Before we do anything, tell the SCM we are starting the stop process.
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
# And set my event.
win32event.SetEvent(self.hWaitStop)
def SvcDoRun(self):
# We do nothing other than wait to be stopped!
win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)
if __name__=='__main__':
win32serviceutil.HandleCommandLine(SmallestPythonService)
more...
Thursday
port forwarding RDP;cannot connect to localhost
symptoms:
"The client could not connect. You
are already connected to the console of this computer. A new console
session cannot be established".
Procedure:
1. Create a folder (For example c:\TSclient) on your XP box
2. Copy mstsc.exe and mstscax.dll from your XP's %systemroot%\system32
to this folder.
3. Right click mstsc.exe and go to the properties of it.
4. Select the Compatibility tab
5. Check "Run this program in compatibility mode for"
6. Select "Windows 98/ Windows Me"
7. Click on OK
8. Connect your SSH to the remote network or machine
9. Forward another port than 3389, for example 3390
10. Use the newly copied mstsc.exe to connect to 127.0.0.1:3390
more...
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\...
-
get ez_setup.py and setuptools-0.6c9-py2.6.egg . type: python ez_setup.py setuptools-0.6c9-py2.6.egg and that should get setuptools install...










