
Tuesday
dot net resources
NT AUTHORITY\NETWORK SERVICE does not have write access
When you have created virtual directory of your application created in .Net2.0 and application is not running.
Even everything is fine in web.config, still it is giving error in web.config file.
Error :- The current identity (NT AUTHORITY\NETWORK SERVICE) does not have write access to 'C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files'.
Solution is :
goto command prompt then navigate to directory
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727
Now run this command
aspnet_regiis -ga "NT AUTHORITY\NETWORK SERVICE"
Even everything is fine in web.config, still it is giving error in web.config file.
Error :- The current identity (NT AUTHORITY\NETWORK SERVICE) does not have write access to 'C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files'.
Solution is :
goto command prompt then navigate to directory
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727
Now run this command
aspnet_regiis -ga "NT AUTHORITY\NETWORK SERVICE"
Friday
call webservice from sql function
here is function allowing you to do so:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[Call_WebService] (@inId AS VARCHAR(50))
RETURNS XML
AS BEGIN
DECLARE @Object AS INT ;
DECLARE @ResponseText AS VARCHAR(8000) ;
DECLARE @Url AS VARCHAR(MAX) ;
SELECT @Url = 'http://myserver/CCRequestProxy.aspx?RequestID=' + @inId
EXEC sp_OACreate 'MSXML2.XMLHTTP', @Object OUT ;
EXEC sp_OAMethod @Object, 'open', NULL, 'get', @Url, 'false'
EXEC sp_OAMethod @Object, 'send'
EXEC sp_OAMethod @Object, 'responseText', @ResponseText OUTPUT
EXEC sp_OADestroy @Object
EXEC sp_OAStop ;
--load into Xml
DECLARE @XmlResponse AS XML ;
SELECT @XmlResponse = CAST(@ResponseText AS XML)
RETURN @XmlResponse
END
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[Call_WebService] (@inId AS VARCHAR(50))
RETURNS XML
AS BEGIN
DECLARE @Object AS INT ;
DECLARE @ResponseText AS VARCHAR(8000) ;
DECLARE @Url AS VARCHAR(MAX) ;
SELECT @Url = 'http://myserver/CCRequestProxy.aspx?RequestID=' + @inId
EXEC sp_OACreate 'MSXML2.XMLHTTP', @Object OUT ;
EXEC sp_OAMethod @Object, 'open', NULL, 'get', @Url, 'false'
EXEC sp_OAMethod @Object, 'send'
EXEC sp_OAMethod @Object, 'responseText', @ResponseText OUTPUT
EXEC sp_OADestroy @Object
EXEC sp_OAStop ;
--load into Xml
DECLARE @XmlResponse AS XML ;
SELECT @XmlResponse = CAST(@ResponseText AS XML)
RETURN @XmlResponse
END
disable cache on asp page
add following instruction on top of the page
<%@ OutputCache Location="None" VaryByParam="None" %>
<%@ OutputCache Location="None" VaryByParam="None" %>
Thursday
Relevance in Fulltext Search
Create Fulltext index first:
CREATE FULLTEXT INDEX indx_text
ON attachment (text)
Add relevance field for select:
SELECT MATCH('text') AGAINST ('financial') as Relevance FROM attachment WHERE MATCH
('text ') AGAINST('+financial +bank' IN
BOOLEAN MODE) HAVING Relevance > 0.2 ORDER
BY Relevance DESC
full search documentation
CREATE FULLTEXT INDEX indx_text
ON attachment (text)
Add relevance field for select:
SELECT MATCH('text') AGAINST ('financial') as Relevance FROM attachment WHERE MATCH
('text ') AGAINST('+financial +bank' IN
BOOLEAN MODE) HAVING Relevance > 0.2 ORDER
BY Relevance DESC
full search documentation
SQL update with join : update table with count from another table
let's say we have two tables connected like this:
SELECT a.saved_list_id, COUNT(b.saved_list_entry_id)
FROM saved_list a
LEFT OUTER JOIN saved_list_entry b ON (a.saved_list_id = b.saved_list_id)
GROUP BY a.saved_list_id;
so update will be looking like follows:
update saved_list p JOIN saved_list_entry c ON p.saved_list_id = c.saved_list_id
SET p.`number_entries` = (SELECT count(saved_list_entry_id) as number_entries
FROM saved_list_entry c where c.saved_list_id = p.saved_list_id)
SELECT a.saved_list_id, COUNT(b.saved_list_entry_id)
FROM saved_list a
LEFT OUTER JOIN saved_list_entry b ON (a.saved_list_id = b.saved_list_id)
GROUP BY a.saved_list_id;
so update will be looking like follows:
update saved_list p JOIN saved_list_entry c ON p.saved_list_id = c.saved_list_id
SET p.`number_entries` = (SELECT count(saved_list_entry_id) as number_entries
FROM saved_list_entry c where c.saved_list_id = p.saved_list_id)
Monday
Team Foundation Server (TFS) - How to see history of whole project or see last changed files
How to see history of whole project in Team Foundation Server (TFS) or see last changed files:
-Locate Team Foundation Server Client -tf.exe file, usually located into
"c:\Program Files\Microsoft Visual Studio 8\Common7\IDE\TF.exe"
-Run this from console inside project:
"c:\Program Files\Microsoft Visual Studio 8\Common7\IDE\TF.exe" history /recursive *
it will return list of changesets,click on changeset to view list of files
-Locate Team Foundation Server Client -tf.exe file, usually located into
"c:\Program Files\Microsoft Visual Studio 8\Common7\IDE\TF.exe"
-Run this from console inside project:
"c:\Program Files\Microsoft Visual Studio 8\Common7\IDE\TF.exe" history /recursive *
it will return list of changesets,click on changeset to view list of files
Tuesday
alter table with check constraint
SET ANSI_PADDING OFF
GO
ALTER TABLE [dbo].[web_contracts] WITH NOCHECK ADD CONSTRAINT [CK_web_contracts] CHECK NOT FOR REPLICATION (([payment_source]=(3) AND len(isnull([eft_routing_number],''))=(9)))
GO
ALTER TABLE [dbo].[web_contracts] CHECK CONSTRAINT [CK_web_contracts]
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Routing number is not specified' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'web_contracts', @level2type=N'CONSTRAINT',@level2name=N'CK_web_contracts'
ASP.NET/csharp:FileUpload inside AJAX Update panel
To make it working it's required :
1.Created interface:
2.implement this interface on page containing ajax update panel:
3.Add button inside of control as trigger:
1.Created interface:
public interface ITriggerable {
void RegisterPostbackTrigger(Control parent,Control trigger);
}
2.implement this interface on page containing ajax update panel:
public void RegisterPostbackTrigger(Control parent,Control button){
PostBackTrigger trigger = new PostBackTrigger();
trigger.ControlID =((Button) button).UniqueID;
UpdatePanel1.Triggers.Add(trigger);
}
3.Add button inside of control as trigger:
protected override void OnInit(EventArgs e){
base.OnInit(e);
((ITriggerable)this.Page).RegisterPostbackTrigger(this, btnRename);
}
WebRequest Exception 401: The remote server returned an error: (401) Unauthorized.
it's required to add default credentials:
request.Credentials = CredentialCache.DefaultCredentials;
See this post for complete source.
request.Credentials = CredentialCache.DefaultCredentials;
See this post for complete source.
Charp (C#):validate http links
public bool ImageExists(string url) {
Uri urlCheck = new Uri(url);
WebRequest request = WebRequest.Create(urlCheck);
request.Credentials = CredentialCache.DefaultCredentials;
request.Timeout = 15000;
WebResponse response;
try {
//get URL web response
response = request.GetResponse();
return true;
}
catch (Exception){
return false; //url does not exist
}
}
JQuery working inside UpdatePanel
To make jquery works inside Update panel you have to add handler to updatepanel reload with restorig jquery bindings :
1. create jquery binding function , to specific links for example:
2 on document ready add handling UpdatePanel reload
1. create jquery binding function , to specific links for example:
function re_init(p1,p2){
$('a[name=modal]').click(function(e) {
// Add your jquery bindings here
// ...
//
}
}
2 on document ready add handling UpdatePanel reload
$(document).ready(function() {
re_init(null,null);
// add re-initialisation after update panel reloading
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(re_init);
});
Friday
authentication in active directory
using System.Security;
public User Login(string login_name, string password){
ICredValidator cv = new LdapCredValidator(); //LanCredValidator();
User u = new User(conn);
if (cv.ValidateCred("MY-DOM", login_name, password))
{
// validation sucess
}else Throw("Login failed for {0}",login_name);
return u;
}
active directory - get computer lists
public void AD_ComputerList()
{
DirectoryEntry entry = new DirectoryEntry("LDAP://my-dom");
DirectorySearcher mySearcher = new DirectorySearcher(entry);
mySearcher.Filter = ("(objectClass=computer)");
Console.WriteLine("Listing of computers in the Active Directory");
Console.WriteLine("============================================");
foreach(SearchResult resEnt in mySearcher.FindAll())
{
Console.WriteLine("Name: {0}", resEnt.GetDirectoryEntry().Name.ToString());
}
Console.WriteLine("=========== End of Listing =============");
}
C# how to get current windows login
public void WinIdentity() {
System.Security.Principal.WindowsIdentity i = System.Security.Principal.WindowsIdentity.GetCurrent();
Console.WriteLine("name: {0}, token: {1}", i.Name, i.Groups[0].ToString());
Assert.IsNotNull(i);
}
webservice logging incoming/outgoing data
add following to web.config under system.web
<httpModules>
<add name="RequestResponseLogger" type="LoggingFilter, LoggingFilter"/>
</httpModules>
<customErrors mode="Off"/>
</system.web>
<microsoft.web.services2>
<diagnostics>
<trace enabled="true" input="D:\Logs\in.txt" output="D:\Logs\out.txt"/>
</diagnostics>
</microsoft.web.services2>
</configuration>
php function for dot.net webservice submission
<?
function web_service($serv,$plain_data){
$curl_handle = curl_init();
curl_setopt($curl_handle, CURLOPT_URL, "https://myserver.com/myService.asmx/".$serv);
curl_setopt($curl_handle, CURLOPT_HEADER, 1);
curl_setopt($curl_handle, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl_handle, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl_handle, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl_handle, CURLOPT_POST, 1);
curl_setopt($curl_handle, CURLOPT_POSTFIELDS, $plain_data);
$response = curl_exec ($curl_handle) or die ( "There has been an error connecting");
#echo $response;
curl_close ($curl_handle);
$response= strstr($response, '<?xml version="1.0" encoding="utf-8"?>');
$re = str_replace('>','>',str_replace('<','<',$response));
$re1= str_replace('<string xmlns="http://tempuri.org/">',"<string>",$re);
return $re1;
}
function web_method($f,$u){
$data="Subscriber=".$f['studid']."&Affiliate=".$u['referral']
$re1= msi_service("MyMethodName1",$data);
$xml = simplexml_load_string($re1);
$result = $xml->xpath("/string"); // <- parsing result
foreach($result as $result_code) {
return $result_code;
}
return $re1;
}
?>
here is post how to configure web service to allow remote post/get submission
rework dynamic sql into stored procedure with optional parameters
CREATE PROCEDURE TestProc
(
@Param1 varchar(50) = NULL,
@Param2 varchar(50) = NULL,
@Param3 varchar(50) = NULL
)
AS
SELECT
*
FROM
TestTable
WHERE
((@Param1 IS NULL) OR (col1 = @Param1)) AND
((@Param2 IS NULL) OR (col2 = @Param2)) AND
((@Param3 IS NULL) OR (col3 = @Param3))
Monday
c# property with using cache (expiration added)
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));
}
}
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...
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...