Friday

C# csharp read from file write into file


public static string ReadFile(string f){
System.IO.StreamReader file = new System.IO.StreamReader(f);
string testxmldata = file.ReadToEnd(); file.Close();
return testxmldata;
}
public void WriteIntoFile(string path,string m) {
if (!File.Exists(path)) {
// Create a file to write to.
using (StreamWriter sw = File.CreateText(path)) {
sw.WriteLine(m);
}
}
else {
// This text is always added, making the file longer over time
// if it is not deleted.
using (StreamWriter sw = File.AppendText(path)) {
sw.WriteLine(m);
}
}
}

more...

Thursday

remove bing from internet explorer

Go to this page and setup different provider (google for example):
http://www.ieaddons.com/en/searchproviders

In internet explorer menu open Tools/Manage addons /Search providers
Right click on Bing, then select remove from popup menu.

more...

Tuesday

Passing NULL values to SqlCommand.Parameters.AddWithValue

this code might help
       
SqlCommand sqlCmd = new SqlCommand(sqlStatment, dbConn);
sqlCmd.Parameters.AddWithValue("@Name", name);
sqlCmd.Parameters.AddWithValue("@Surname", surname);
foreach (SqlParameter Parameter in sqlCmd.Parameters)
{
if (Parameter.Value == null)
{
Parameter.Value = DBNull.Value;
}
}

more...

Friday

The wave header is corrupt fix Or how to play wav file with System.Media.SoundPlayer in dot.Net C#

1.add this MediaPlayer class
class MediaPlayer
{
System.Media.SoundPlayer soundPlayer;
public MediaPlayer(byte[] buffer)
{
MemoryStream memoryStream = new MemoryStream(buffer, true);
soundPlayer = new System.Media.SoundPlayer(memoryStream);
}
public void Play() {soundPlayer.Play();}
public void Play(byte[] buffer)
{
soundPlayer.Stream.Seek(0, SeekOrigin.Begin);
soundPlayer.Stream.Write(buffer, 0, buffer.Length);
soundPlayer.Play();
}
}

2. Then file playing procedure will be looking like this:
private void PlayMyFile()
{
string file1 = @"c:\sample.wav";
List<byte> soundBytes = new List<byte>(File.ReadAllBytes(file1));
//create media player loading the first half of the sound file
MediaPlayer mPlayer = new MediaPlayer(soundBytes.ToArray());
//begin playing the file
mPlayer.Play();
}

more...

Thursday

C# generic list copy with constructor

     
using System;
using System.Collections;
using System.Collections.Generic;
namespace Business.Web.Models {
public class DtoMapper {
// this is generic method replacing non-generic metod
// InvoiceDto_OLD provided in source below
public List<T2> Transform<T1,T2>(List<T1> i, Func<T1,T2> del)
{
List<T2> ret = new List<T2>();

foreach (T1 val in i) {
ret.Add(del(val));
}
return ret;
}

// generic method can be called as follows:
public List<InvoiceDto> InvoiceDto(List<Invoice> i) {
return Transform<Invoice,InvoiceDto> (i.ToList(),l=>new InvoiceDto(l));
}

// this is sample of old non-generic method
public List<InvoiceDto> InvoiceDto_OLD(List<Invoice> i) {
List<InvoiceDto> ret = new List<InvoiceDto>();

foreach (Invoice invoice in i) {
ret.Add(new InvoiceDto(invoice) );
}
return ret;
}
}
}

more...

Tuesday

view GAC, add dll to GAC


to view registred dlls in GAC open this folder in explorer:
C:\WINDOWS\assembly

To Register GAC , use following command:
c:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\gacutil.exe /i [mydll]
more...

Saturday

To analyze website with FxCop

Open FxCop click newProject/AddTargets and find your website compiled here:
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\[yourwebsitename]
Press Ctrl+A and add all dlls.

more...

open web page in android application:

don't forget to set permission


package com.test2;
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
@Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
android.webkit.WebView wv =
(android.webkit.WebView)this.findViewById(R.id.WebView01);
wv.loadUrl("http://sourcefield.blogspot.com");
}
}

Could not load file or assembly Microsoft.ReportViewer.WebForms:

usually it's located into c:\Program Files\Microsoft Visual Studio 9.0\ReportViewer\

For visual Studio 2005 run this installer to add this to GAC:
C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\BootStrapper\Packages\ReportViewer\ReportViewer.exe
more...

Thursday

fix:android.webkit.WebView

In order to allow WebView to display pages,android.permission.INTERNET permission has to be added :

<uses-permission android:name="android.permission.INTERNET"></uses-permission>


Can also be edited graphically in Eclipse plugin through permissions tab.

Monday

AutoHotkey autoplayer for Online games

Here is auto-click script for 'point and click' games , you will need AutoHotkey and save this as .ahk file .

SetKeyDelay, 75, 75
;Exits AutoHotKey application.
$^CapsLock::
ExitApp
return
;Pauses AutoHotKey Script.
F6::Pause, Toggle, 1
$x::
Loop {
MouseClick
sleep 10
}

more...

C# source to find XML tag recursively


 [TestFixture]
public class test
{
[Test]
public void XPathTest()
XmlDocument doc = new XmlDocument();
doc.Load(@"c:\LinqObjects.xsd");

foreach (XmlNode node in doc.DocumentElement.ChildNodes)
{
ProcesNode(node, doc.DocumentElement.Name);
}
}



private void ProcesNode(XmlNode node, string parentPath)
{
if (!node.HasChildNodes || ((node.ChildNodes.Count == 1) && (node.FirstChild is System.Xml.XmlText)))
{
if (node.Name == "Parameter")
{
//System.Diagnostics.Debug.WriteLine(parentPath + "/" + node.Name);
}
}
else
{
foreach (XmlNode child in node.ChildNodes)
{
ProcesNode(child, parentPath + "/" + node.Name);
}
}
}
}

more...

Thursday

Royalty Free Icons Clipart Stock Images

good- http://iconza.ru/
better: http://icons.mysitemyway.com/

event categorized:
http://icons.mysitemyway.com/magic-marker-icons-sports-hobbies/
http://icons.mysitemyway.com/amber-glossy-chrome-icons-sports-hobbies

another one - http://www.iconspedia.com/
for svg lovers: http://www.openclipart.org/"

free textures: http://www.texturelovers.com/
http://www.spiralgraphics.biz/packs/terrain_desert_barren/index.htm

to search for.ex.hourglass:
bad - http://browse.deviantart.com/?qh=&section=&q=hourglass"
better - http://www.iconspedia.com/search/hourglass/
best http://www.openclipart.org/search/?query=hourglass

Sunday

source code

you can find open-source and free projects (including asp.net/.net/mvc) here

There are others source code search engines and repositories:


codefetch{ - www.codefetch.com/
Snipplr - Code 2.0 - snipplr.com/
Google Code Search - www.google.com/codesearch
Codase - Source Code Search Engine - www.codase.com/
Home | byteMyCode - www.bytemycode.com/
DZone Snippets: Store, sort and share source code, with tag goodness - snippets.dzone.com/
Krugle - Find code. Find answers. - www.krugle.com/
Wiki Engines - c2.com/cgi/wiki?WikiEngines
merobase ? Software Component Finder - www.merobase.com/
Code Snippets - Source Code | DreamInCode.net - www.dreamincode.net/code/browse.php?cid=0
Open Source Code Search Engine - Koders - www.koders.com/
Code Search - O'Reilly Labs - labs.oreilly.com/code/

Thursday

H1B to COS B1/B2

Q


1. On H1B I797 & I-94 both valid till July 31,2009. Used 3 years of H1.
2. Last day on job May 22. Last pay I will get on 06/06/2009
3. Company said it will not file for H1 extension and will not revoke ( few weeks only).
My questions now-
1. Can I apply for COS to B1/B2 Efile now since I have car to sell and other stuff?
2. If I get a job before B1/B2 approval, how do I continue on H1 ?I assume my employer files for H1 extension.
3. If I get a job AFTER B1/B2 approval and also after expiry of H1 ( July 31), how do I get back onto H1?
4. If I go back to India,after expiry of my current H1, how can I revive this H1 with the current employer or New Employer?
5. If I apply for 2010 quota, can I be counted against old H1? or do I get new H1?( meaning 6 years?)

User's Location: Tampa, Florida, United States of America
Category: H1B Visa (Work Visa)
Posted on 27 May 2009

A.


1. Can I apply for COS to B1/B2 Efile now since I have car to sell and other stuff?

You can apply for a COS from H-1B to B-2 using the I-539. You will want to do so before your the date on your last pay stub. You will want to include proof of your financial ability to take care of yourself and a separate letter explaining the reason you need to take care of things.

2. If I get a job before B1/B2 approval, how do I continue on H1 ?I assume my employer files for H1 extension.

Your new employer would need to file for a new H-1B extension for you. You can include evidence of your pending B-2 COS with that new H-1B filing. You may want to consider requesting premium processing so the new H-1B could be approved before the chance that your COS to B-2 could be denied.

3. If I get a job AFTER B1/B2 approval and also after expiry of H1 ( July 31), how do I get back onto H1?

If you have H-1B time remaining, you simply file COS paperwork on I-129 for new H-1B and COS from B-2 to H-1B. You should be fine for an H-1B extension as long as you have H-1B time remaining and your COS should work so long as you have B-2 time remaining.

4. If I go back to India,after expiry of my current H1, how can I revive this H1 with the current employer or New Employer?

You would have to file new H-1B paperwork and recieve a new H-1B approval. This H-1B paperwork should not be counted against the H-1B cap.

5. If I apply for 2010 quota, can I be counted against old H1? or do I get new H1?( meaning 6 years?)

If you are outside of the U.S. for one year, you can either file for remaining H-1B time (3 years?) or file for new H-1B under new H-1B cap.


question:what all documents I should send to support my application?


Posted on 01 Jun 2009

A.

In order to file for a COS from H-1B to B-2, you should include:

(1) Copy of your H-1B approval notice;

(2) Copy of your H-1B visa and I-94;

(3) Copy of the face page of your passport;

(4) Copy of 3-4 most recent pay stubs;

(5) Copy of recent bank statement(s);

(6) Letter explaining reasons why you need to stay in the U.S. as a visitor (i.e. apt./home, car, financial issues to resolve, commitments etc.)

Tuesday

Running PowerShell script from C#



private void testRunToolStripMenuItem_Click(object sender, EventArgs e)
{
List<string> ls = new List<string>();
RunPowershellScript(@"c:\Program Files\Microsoft Transporter Tools\PassCh.ps1",ls);
//log("script complete");

}

private static void RunPowershellScript(string scriptFile, List<string> parameters)
{
// Validate parameters
if (string.IsNullOrEmpty(scriptFile)) { throw new ArgumentNullException("scriptFile"); }
if (parameters == null) { throw new ArgumentNullException("parameters"); }

RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
PSSnapInException ex;
runspaceConfiguration.AddPSSnapIn("Microsoft.Exchange.Transporter",out ex);

using (Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration))
{
runspace.Open();
RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
scriptInvoker.Invoke("Set-ExecutionPolicy Unrestricted");
Pipeline pipeline = runspace.CreatePipeline();
Command scriptCommand = new Command(scriptFile);
Collection<CommandParameter> commandParameters = new Collection<CommandParameter>();
foreach (string scriptParameter in parameters)
{
CommandParameter commandParm = new CommandParameter(null, scriptParameter);
commandParameters.Add(commandParm);
scriptCommand.Parameters.Add(commandParm);
}
pipeline.Commands.Add(scriptCommand);
Collection<PSObject> psObjects;
psObjects = pipeline.Invoke();
}
}

more...

Monday

vba code samples for outlook



Sub AssignCategoryAndMoveBasedOnSubject(Item As Outlook.MailItem)
If InStr(1, Item.Subject, "error") > 0 Then
Item.Categories = "Error"
Item.Subject = "Error:" + Item.Subject
Item.Save

Set myNameSpace = GetNamespace("MAPI")
Set myInBox = myNameSpace.GetDefaultFolder(olFolderInbox)
Set mydestFolder = FindOrCreateFolder(myInBox, "Text")
Item.Move mydestFolder
End If
End Sub


Function FindOrCreateFolder(inputFolder As Variant, folderName As String) As Outlook.MAPIFolder
Dim curFolder As Outlook.MAPIFolder
For Each curFolder In inputFolder.Folders
If folderName = curFolder.Name Then
Set FindOrCreateFolder = curFolder
Exit Function
End If
Next curFolder
Set FindOrCreateFolder = inputFolder.Folders.Add(folderName)
End Function

more...

vba code : access sql server from outlook



'Access SQL server from oputlook
Sub AccessSQLServer(Item As Outlook.MailItem)
Set con = CreateObject("ADODB.Connection")
con.Open "driver={SQL Server};Uid=sa;server=myserv;pwd=mypass;database=mydb;"
Set rs = CreateObject("ADODB.Recordset")
rs.ActiveConnection = con
rs.Open "SELECT * FROM MyTable"
Do While Not rs.EOF
MsgBox rs("id")
rs.MoveNext
Loop
End Sub


more...

Friday

C#(csharp) how to resize array (shrink) by Array.Copy

 

/// <summary>
/// Emails addresses creating.
/// </summary>
/// <param name="incom">The incoming array</param>
/// <returns></returns>
private EmailAddressType[] EmailAddressCreate(string[] incom) {
if (incom == null) return null;
EmailAddressType[] ret = new EmailAddressType[incom.Length];
EmailAddressType[] rt;
int i = 0;
foreach (string s in incom) {
if (!string.IsNullOrEmpty(s))
{
ret[i] = new EmailAddressType();
ret[i].EmailAddress = s;
i++;
}
}
// change size of array
if (i < incom.Length)
{
rt = new EmailAddressType[incom.Length];
Array.Copy(rt, ret, i);
}else
{
rt=ret;
}

return rt;
}

more...

Sunday

ASP.NET uploading files directly to a SQL database in C#

asp-page-source
 <form id="form1" runat="server">
Please upload file:<br />
<asp:Literal ID="lit_Status" runat="server" /><br />
<b>Name:</b>
<asp:TextBox ID="FileName" runat="server" />
<br />
<b>File:</b>
<asp:FileUpload ID="FileToUpload" runat="server" />
<br />
<asp:Button ID="btn_Upload" runat="server" Text="Upload" onclick="btn_Upload_Click" />
</form>


Code-behind source
 using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data.SqlClient;
using System.Configuration;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}

protected void btn_Upload_Click(object sender, EventArgs e)
{
if (FileToUpload.PostedFile == null || String.IsNullOrEmpty(FileToUpload.PostedFile.FileName) || FileToUpload.PostedFile.InputStream == null)
{
lit_Status.Text = "
Error - unable to upload file. Please try again.
";
}
else
{
using (SqlConnection Conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
try
{
const string SQL = "INSERT INTO [BinaryTable] ([FileName], [DateTimeUploaded], [MIME], [BinaryData]) VALUES (@FileName, @DateTimeUploaded, @MIME, @BinaryData)";
SqlCommand cmd = new SqlCommand(SQL, Conn);
cmd.Parameters.AddWithValue("@FileName", FileName.Text.Trim());
cmd.Parameters.AddWithValue("@MIME", FileToUpload.PostedFile.ContentType);

byte[] imageBytes = new byte[FileToUpload.PostedFile.InputStream.Length + 1];
FileToUpload.PostedFile.InputStream.Read(imageBytes, 0, imageBytes.Length);
cmd.Parameters.AddWithValue("@BinaryData", imageBytes);
cmd.Parameters.AddWithValue("@DateTimeUploaded", DateTime.Now);

Conn.Open();
cmd.ExecuteNonQuery();
lit_Status.Text = "
File successfully uploaded - thank you.
";
Conn.Close();
}
catch
{
Conn.Close();
}
}
}
}
}



more...

howto put file into varbinary (OPENROWSET,BULK,SINGLE_BLOB) on MS SQLServer


CREATE TABLE [cmp].[tblCMPEmailAttachements](
[AttachmentID] [int] IDENTITY(1,1) NOT NULL,
[EmailID] [int] NOT NULL,
[FileName] [nvarchar](50) NULL,
[CreatedDate] [datetime] NULL,
[FileBody] [varbinary](max) NULL
) ON [PRIMARY]



Declare @attID int
Insert into cmp.tblCMPEmailAttachements (EmailID,FileName,CreatedDate) values (1,'1.gif',GETDATE())
SET @attID = SCOPE_IDENTITY();
update cmp.tblCMPEmailAttachements set
[FileBody] = (SELECT * FROM OPENROWSET(BULK 'C:\1.gif', SINGLE_BLOB)AS [FileBody] ) WHERE AttachmentID=@attID

more...

Monday

android links

http://code.google.com/p/andro… - Android Scripting Environment brings scripting languages to Android.
http://developer.motorola.com/… - Motorola Developer Studio
http://eclipse.org/ - Eclipse, open development platform
http://developer.android.com/s… - Google Android SDK
http://androidforums.ru/ - русское сообщество ОС Android. Форум по Android
http://www.quattrowireless.com… и http://www.smaato.com/ - размещение рекламы на мобильных устройствах
http://slideme.org/ - альтернативный распространитель ПО

Вдогонку: http://sites.google.com/site/o… - пишем Hello World.

Thursday

Gvim editor new tips



da< - Delete the HTML tag the cursor is currently inside of the whole tag, regardless of just where the cursor is.
ci" -Change the content of a doublequote-delimited string.

da[ - Delete the [] region around your cursor
vi' - Visual select everything inside '' string
ya( - Yank all text from ( to )

See :help text-objects.

:e! - Reopen the current file, getting rid of any unsaved changes
gg=G - AMAZING If you're coding, gg will bring you to the top of the file, and =G will auto indent (=) everything to the bottom of the file (G)
gq - reset the entire selection to be wrapped correctly.
=% - Indents the block between two braces/#ifdefs
== - Indents current line
d% - delete till parrent - cursor can be not on opening tag
ft - move to the next occurrence of t and
tt - to move to the char before t

Macros are stored in registers, these are the same registers that can be used
for copy paste. So say you record a macro to register q you can paste it into a
document with "qp, edit it, then select it and cut it back into the register
with "qd.




more...

ГК стадии

стадии
0 - реклама. Для вас ничего не поменяется.
I - LC. Для вас ничего не меняется, кроме возможности продления H-1 за пределы 6 лет.
II - I-140 - Аналогично но начинаете указывать им намерения в анкете ну и по прежнему можете продлевать H-1. Если 140 аппрувлена но категория EB-3 (бакалавр) то продлевать можете сразу на 3 года за пределы 6-ти лет
III - I-485 (+ AP + EAD) - получаете нормальный документ для выезда (AP) и нормальный документ для внутренних нужд (EAD). Жена и дети получают возможность работать и иметь SSN.
III + 6 месяцев - можно менять работу.
ГК - не нужно больше суетиться и дети могут получать федеральную помошь на учебу и федеральные кредиты на учебу.

Если категория визы EB-2 или EB-1 то стадии II и III файлятся (все еще?) одновременно. Если EB-3 то между ними будет года 3 ожидания (все у того же работодателя и на визе).


Все правильно кроме, пожалуй, последнего. Время между непредсказуемо в случае Еб-3 - сейчас срок 7 лет исходя из бюллетеня, данные УСЦИС неполные и противоречивые, бэклог они посчитать не могут.


Дело в том, что начиная с 2006 года примерно поток EB-3 резко иссяк. И движение по оным годам будет очень нелинейным. Хотя... полный срок плавал от 2 до 5-ти лет, исходя из этого - срок по EB-3 вряд ли уедет за больше 6 - 7 лет (причем этот срок считается с подачи LC а не с подачи I-140, то есть если сейчас начнут, то и срок начнет отсчитываться), и вряд ли станет меньше 2 - 3 лет (сразу толпы набегут)...


Wednesday

Gvim editor tutorial: moving back trough changes


The changelist remembers the position of every change that can be undone.
You can move back and forwards through the changelist using the commands:
g;
g,


You can view the contents of the changelist by running the command:
:changes

Vim also maintains a jumplist,
remembering each position to which the cursor jumped, rather than scrolled.
You can move backwards and forwards through the jumplist with the commands:

ctrl-O
ctrl-I

You can view the contents of the jumplist by issuing the command:
:jumps

you can follow the keyword under the cursor with the command (ctags required):
ctrl-]

see also:
* :help changelist
* :help :changes
* :help jumplist
* :help :jumps
* :help jump-motions

more...

Friday

Visual Studio Mercurial,GIT,SVN links

Mercurial:
* free hosting : http://mercurial.selenic.com/wiki/MercurialHosting
* VisualHG: a plugin for Visual Studio: http://sharesource.org/project/visualhg/
* Windows Explorer client: http://tortoisehg.bitbucket.org/
GIT:

* Free hosting: http://git.wiki.kernel.org/index.php/GitHosting
* GitExtensions: a Visual Studio plugin http://code.google.com/p/gitextensions
* Windows Explorer client: http://code.google.com/p/tortoisegit/
SVN:

* VisualSVN server FREE installer: http://www.visualsvn.com/server/
* AnkhSVN plugin for Visual Studio: http://ankhsvn.open.collab.net/
* Windows Explorer client: http://tortoisesvn.tigris.org/

more...

Wednesday

How can I make yes/no questions is a batch file?


mplayer.exe -cache 1024 -speed 1.66 %1
SET /P ANSWER=Do you want to delete %1 file (Y/N)?
echo You chose: %ANSWER%
if /i {%ANSWER%}=={y} (goto :yes)
if /i {%ANSWER%}=={yes} (goto :yes)
goto :no
:yes
rm -f %1
exit /b 0
:no
echo file wasn't deleted
exit /b 1

more...

EventHandler event in usercontrol

First, we create a new, simple EventUserControl, with this code in it:
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="EventUserControl.ascx.cs" Inherits="EventUserControl" %>

Page title:
<asp:TextBox runat="server" ID="txtPageTitle" />
<asp:Button runat="server" ID="btnUpdatePageTitle" OnClick="btnUpdatePageTitle_Click" Text="Update" />


All just text and server controls that we know. In the CodeBehind, it looks a bit like this:
public partial class EventUserControl : System.Web.UI.UserControl
{
private string pageTitle;
public event EventHandler PageTitleUpdated;

protected void btnUpdatePageTitle_Click(object sender, EventArgs e)
{
this.pageTitle = txtPageTitle.Text;
if(PageTitleUpdated != null)
PageTitleUpdated(
this, EventArgs.Empty);
}

public string PageTitle
{
get { return pageTitle; }
}
}



We have defined a pageTitle container variable and a property for it. Then we have a new thing, an event. As you can see, it's defined much like any other kind of field, but it is a bit different. The theory about is explained in the C# tutorial, so we won't get into that here.
In the Click event of our button, we set the pageTitle field. Then we check if PageTitleUpdated, our event, is null. If it's not, it means that we have subscribed to this event somewhere, and in that case, we send a notification by calling the PageTitleUpdated as a method. As parameters, we send this (a reference to the UserControl it self) as the sender, and an empty EventArgs parameter. This will make sure that all subscribers are notified that the pageTitle has just been updated.

Now, in our page, I've declared our UserControl like this:
<%@ Register TagPrefix="My" TagName="EventUserControl" Src="~/EventUserControl.ascx" %>


And inserted it like this:
<My:EventUserControl runat="server" ID="MyEventUserControl" OnPageTitleUpdated="MyEventUserControl_PageTitleUpdated" />

As you can see, we have defined an event handler for the PageTitleUpdated event like if it was any other server control. In the CodeBehind of our page, we define the simple event handler for the UserControl event like this:
protected void MyEventUserControl_PageTitleUpdated(object sender, EventArgs e)
{
this.Title = MyEventUserControl.PageTitle;
}





more...

Tuesday

use editor to type text into firefox

there is Firefox add-on that allows to exit to type text in your favorite editor and then move to browser:
It's All Text!
more...

Friday

howto create and call json webservice in asp.net example

1.Add to webservice method this tag System.Web.Script.Services.ScriptService(),
so it will be looking like this:

Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.Web.Script.Services
Imports WebControlLibrary
Imports Ubill.Business
Imports System.ComponentModel

<System.Web.Services.WebService(Namespace:="http://tempuri.org/")> _
<System.Web.Services.WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<ToolboxItem(False)> <System.Web.Script.Services.ScriptService()> _
Public Class AtlasHub
Inherits System.Web.Services.WebService


<WebMethod(True)> _
Public Function AdvanceCustomerDelete(ByVal CustomerID As String) As String
Return cachefactory.AdvanceCustomerDelete(CustomerID)
End Function

End Class




2.On aspx page add this script manager binding :

<asp:ScriptManager runat="server" ID="scriptManagerId">
<Scripts>
<asp:ScriptReference Path="~/common/AtlasHub.js" />
</Scripts>
<Services>
<asp:ServiceReference Path="~/common/AtlasHub.asmx " />
</Services>
</asp:ScriptManager>



3.AtlasHub.js is javascript file those contains maintenance functions:


// Business functions
// // -------------------------------------------
function AdvanceCustomerDelete( customerID , onSuccessAdvanceCustomerDelete){
YouBillWeb.AtlasHub.AdvanceCustomerDelete(customerID,onSuccessAdvanceCustomerDelete,onTimeOut,onFailed);
}

// Maintenance functions
// -------------------------------------------
// This is the callback function invoked if the Web service
// succeeded.
// It accepts the result object, the user context, and the
// calling method name as parameters.
function OnSucceededWithContext(result, userContext, methodName)
{
var output;

// Page element to display feedback.
var RsltElem = document.getElementById("ResultId");

var readResult;
if (userContext == "XmlDocument")
{

if (document.all)
readResult =
result.documentElement.firstChild.text;
else
// Firefox
readResult =
result.documentElement.firstChild.textContent;

RsltElem.innerHTML = "XmlDocument content: " + readResult;
}

}

// This is the callback function invoked if the Web service
// succeeded.
// It accepts the result object as a parameter.
function onSuccess(result, eventArgs)
{
// Page element to display feedback.
var RsltElem = document.getElementById("ResultId");
RsltElem.innerHTML = result;
}

function OnSucceeded(result, eventArgs)
{
// Page element to display feedback.
var RsltElem = document.getElementById("ResultId");
RsltElem.innerHTML = result;
}


// This is the callback function invoked if the Web service
// failed.
// It accepts the error object as a parameter.
function onFailed(error)
{
// Display the error.
var RsltElem = document.getElementById("ResultId");
RsltElem.innerHTML =
"Service Error: " + error.get_message();
}

function onTimeOut(error)
{
// Display the error.
var RsltElem = document.getElementById("ResultId");
RsltElem.innerHTML =
"Service Error: " + error.get_message();
}

if (typeof(Sys) !== "undefined") Sys.Application.notifyScriptLoaded();

more...

Tuesday

no-ip script in python

change username/password/host in this script below

import urllib
import time
import sys
import string

f = urllib.urlopen('http://my-user-name:-mypass@dynupdate.no-ip.com/nic/update?hostname=myhost.no-ip.org')
sug = f.read()
f.close()
print sug

here are additional on no-ip API documentation:
request sample

protocol description

response codes

more...

Saturday

ssl certificate sec_error_untrusted_issuer

I had problem with the expired or not valid certificates in almost all application on my computer: Firefox, pidgin, Internet Explorer.
The cause was : date on my computer was set wrong and it thought I was years in the past!
Once I fixed the date and time, all of these problems vanished.

more...

Wednesday

how to show hide div in asp.net

1.add this javascript function:


<script type="text/javascript">
function showHideExcel(){
thisElement=document.getElementById('overlayExcel')
if (!thisElement) return;
if(thisElement.style.visibility == "visible"){
thisElement.style.visibility = "hidden";
}else {
thisElement.style.visibility = "visible";
}
}
</script>



2.add this div to asp.net code


<div id="overlayExcel" name="overlayExcel" style="visibility:hidden;position:absolute; top: 120px; left: 900px;background-color:white;display:block;">
<div style="padding: 3px; background-color: #CCCCCC; border: 1px solid #666666;">
<table border="0" border="0" cellspacing="0" cellpadding="0" >
<tr><td height="30">Start Date:&nbsp;</td> <td><asp:TextBox ID="txtExcelStartDate" runat="server" /></td></tr>
<tr><td height="30">End Date:&nbsp;</td> <td><asp:TextBox ID="txtExcelEndDate" runat="server" /><br></td></tr>
<tr><td height="30" colspan="2"><asp:Button ID="btnExcelMe" runat="server" Text="Open Excel Report" OnClick="OpenExcelReport" />
<input type=button value="Cancel" onclick="showHideExcel();"></td>
</tr>
</table>
</div>
</div>



that's it.
more...

Friday

very nice and free music for running or training on eclipse

I gave up on running for several times , recently discovered very good music for running.
Actually this music is free and keep me running all time.
It sorted by bits per secod,for.ex. 153BPM just right for me.

check this out http://djsteveboy.com/podrunner.html

more...

Tuesday

sql split string


DECLARE @t VARCHAR(50)
SET @t = '3333-4'
SELECT LEFT(@t, CHARINDEX('-', @t) - 1), RIGHT(@t, LEN(@t) - CHARINDEX('-', @t))

more...

how to configure VB6 works with TFS:

Read
download


more...

copy odbc from one computer to another


1.if this i user odbc run regedit.exe and export this folder into .reg file.
HKEY_CURRENT_USER\Software\ODBC
2.copy .reg file on target machine and double click on .reg file to add all keys to registry.

If they are System DSN odbc you have to do the same operations for
HKEY_LOCAL_MACHINE\SOFTWARE\ODBC
registry folder.

more...

Wednesday

Derive Collection class:Override Add,Insert,Remove methods

These methods are not overridable,
will be more correctly to override InsertItem,RemoveItem methods, they will be called from other methods Add,Insert,Remove , etc

using System.Collections.ObjectModel;
using System.Diagnostics;
using System;
namespace CollectionTest
{
class Program
{
static void Main(string[] args)
{
Debug.Write("MAIN");
LimitedCollection<String> col = new LimitedCollection<String>();
col.Add("hello");
col.Insert(0,"hello");

}
}
public class LimitedCollection<T> : Collection<T>
{
protected override void InsertItem(int index, T item)
{
base.InsertItem(index, item);
Debug.Write("InsertItem called");
}
}
}

more...

Tuesday

How to create Setup project for Windows Service

How to create a Setup project for a Windows Service in Visual Basic .NET or in Visual Basic 2005
Create a Setup project for a Windows Service
This section describes how to create a Windows Service project and how to use a compiled Setup project to install the Windows Service.
Create a Windows Service project

1. Click Start, point to Programs, point to Microsoft Visual Studio .NET or Microsoft Visual Studio 2005, and then click Microsoft Visual Studio .NET or Microsoft Visual Studio 2005.
2. On the File menu, point to New, and then click Project.
3. In the New Project dialog box, follow these steps:
1. Under Project Types, click Visual Basic Projects or click Windows under Visual Basic.
2. Under Templates, click Windows Service.
3. In the Name box, type LogWriterService.
4. In the Location box, type C:\, and then click OK.
4. In Solution Explorer, right-click Service1.vb, and then click View Code.
5. In the OnStart event handler, replace the comments with the following code.

EventLog.WriteEntry("My simple service started.")

6. In Solution Explorer, double-click Service1.vb.
7. In the Properties dialog box, click Add Installer.
8. In the Properties dialog box for ServiceInstaller1, change the ServiceName property to LogWriterService.
9. In Design view, click ServiceProcessInstaller1 in the Code Editor.
10. In the Properties dialog box, change the Account property to LocalSystem. The LocalService value and the NetworkService value are only available in Microsoft Windows XP and later operating systems.

Use a compiled Setup project to install the Windows Service
After you complete the steps in the "Create a Windows Service project" section to configure the Windows Service project, you can add a deployment project that packages the service application so that the service application can be installed. To do this, follow these steps:

1. Add a new project to your LogWriterService project.
1. In Solution Explorer, right-click Solution 'LogWriterService', point to Add, and then click New Project.
2. Under Project Types, click Setup and Deployment Projects or Setup and Deployment.
3. Under Templates, click Setup Project.
4. In the Name box, type ServiceSetup.
5. In the Location box, type C:\, and then click OK.
2. Tell the deployment project what the deployment project will package.
1. In Solution Explorer, right-click ServiceSetup, point to Add, and then click Project Output.
2. In the Add Project Output Group dialog box, click LogWriterService in the Project box.
3. Click Primary Output, and then click OK.
3. For correct installation, you have to add only primary output. To add the custom actions, follow these steps:
1. In Solution Explorer, right-click ServiceSetup, point to View, and then click Custom Actions.
2. Right-click Custom Actions, and then click Add Custom Action.
3. Click Application Folder, and then click OK.
4. Click Primary output from LogWriterService (Active), and then click OK. Notice that Primary output appears under Install, Commit, Rollback and Uninstall.
4. By default, Setup projects are not included in the build configuration. To build the solution, follow these steps:
1. Use one of the following methods:
* Right-click LogWriterService, and then click Build. Then, right-click ServiceSetup, and then click Build.
* To build the whole solution at the same time, click Configuration Manager on the Build menu, and then click to select the Build check box for ServiceSetup.
2. Press CTRL+SHIFT+B to build the whole solution. When the solution is built, you have a complete Setup package for the service.
5. To install the service, right-click ServiceSetup, and then click Install.
6. In the ServiceSetup dialog box, click Next three times. Notice that a progress bar appears while the Setup program is installing the service.
7. When the service is installed, click Close.


Thursday

tinyget call samples

Invoking the page for 4000 times.

tinyget -srv:localhost -uri:/BuggyBits/Links.aspx -loop:4000

Invoking the page on 30 threads, 50 times each.

tinyget -srv:localhost -uri:/BuggyBits/FeaturedProducts.aspx -threads:30 -loop:50

Wednesday

To try find out asp.net performance leak/locks or why my .net app is slow on multiple requests :) ?


1.take memory dump and load it in windbg with "sos" as described here.
Then you can load sos commands .cmdtree c:\debuggers\cmdtree.txt
3.Evaluate clr stacks for all threads by ~* e !clrstack
or by selecting Stacs/All managed Stacks from Sos Commands menu window.
as result you will see call stack lists,similar stacks like for memory dump.
4.Look for System.Threading.Monitor.Enter or System.Threading.Monitor.Exit in page load stacks , that might indicate that static object is using
that might cause slow performance for multiple requests.

5.to monitor sysncBlock use !syncblk commad
it will show who owns the lock and how many people waiting for it in "MonitorHeld" column.

"Info" column will - contains thread number [thr] that locking, use this commands:
~[thr]s
!clrstack
to display locking stack and which give you a chance to locate which procedure holding it.

also debugging and preview of dump files will be available in Visual studio 2010.

more...

How to find memory leak in .net application:


1.Create dump file of application process in windows , you can use this tool

DebugDiag (free tool from Microsoft)
Open it, go to "process" tab and select "create dump file"
2. Download and install
windbg
Start windbg and drag dump file there.
3.if it's dot.net you have to load sos extension , in windbg command line , type:
.loadby sos mscorwks
4.then !dumpheap -stat you will get list of all .Net objects in memory/dump
if you want to get specific instances , you can hit:
!dumpheap -mt [addr] - where [addr] is addr from left column in windbg
you will receive list of objects loaded into memory , by dump out do objects:
!do [addr] you will dump specific objects with it's properties.
when you do !do [addr] when [addr] of specific property you will get particular value of that property.
5.if you dumped web-application and see aspx pages this is not good.
you can get static objects by this command (it will show links on cache objects as well):
!gcroot [addr] where [addr] -- address of page in memory

As alternative you can use different analysis from [Analysis] tab in DebugDiag.
Memory Analysis gives a nice report.

Friday

micosoft sql server SHRINKFILE command:

first find file_name by:
select * from sys.database_files
then:
DBCC SHRINKFILE (mydb_log, 1000) WITH NO_INFOMSGS

Thursday

C#:ActiveDirectory : Check User cannot change password

in project add COM reference to "Active DS Type Library" COM library v1.0
usually located in C:\WINDOWS\system32\activeds.tlb.


using ActiveDs;
public void CheckUserCanChangePasswordsProperty()
{
DirectoryEntry de = GetDirectoryObject(UserName);
string PASSWORD_GUID = "{ab721a53-1e2f-11d0-9819-00aa0040529b}";
string[] trustees = { "NT AUTHORITY\\SELF", "EVERYONE" };


ActiveDs.IADsSecurityDescriptor sd =
(ActiveDs.IADsSecurityDescriptor)de.Properties["ntSecurityDescriptor"].Value;
ActiveDs.IADsAccessControlList acl = (ActiveDs.IADsAccessControlList)sd.DiscretionaryAcl;
ActiveDs.AccessControlEntry ace = new ActiveDs.AccessControlEntry();


double denied = (double)ActiveDs.ADS_ACETYPE_ENUM.ADS_ACETYPE_ACCESS_DENIED_OBJECT;
double objectType = (double)ActiveDs.ADS_FLAGTYPE_ENUM.ADS_FLAG_OBJECT_TYPE_PRESENT;
double dsControl = (double)ActiveDs.ADS_RIGHTS_ENUM.ADS_RIGHT_DS_CONTROL_ACCESS;

foreach (string trustee in trustees)
{
ace.Trustee = trustee;
ace.AceFlags = 0;
ace.AceType = Convert.ToInt32(Math.Floor(denied));
ace.Flags = Convert.ToInt32(Math.Floor(objectType));
ace.ObjectType = PASSWORD_GUID;
ace.AccessMask = Convert.ToInt32(Math.Floor(dsControl));

acl.AddAce(ace);
}
sd.DiscretionaryAcl = acl;
de.Properties["ntSecurityDescriptor"].Value = sd;

de.CommitChanges();
}

more...

C#:Active Directory:Uncheck User cannot change password


public void SetUserCanChangePasswordsPropertyUncheck()
{
DirectoryEntry de = GetDirectoryObject(UserName);
string PASSWORD_GUID = "{ab721a53-1e2f-11d0-9819-00aa0040529b}";
ActiveDs.IADsSecurityDescriptor sd =
(ActiveDs.IADsSecurityDescriptor)de.Properties["ntSecurityDescriptor"].Value;
ActiveDs.IADsAccessControlList acl = (ActiveDs.IADsAccessControlList)sd.DiscretionaryAcl;
//ActiveDs.AccessControlEntry ace = new ActiveDs.AccessControlEntry();
ActiveDs.ADS_ACETYPE_ENUM aceType;

//look for existing ace and get rid of
foreach (ActiveDs.AccessControlEntry ace in acl)
{
if (!(ace.ObjectType == null) && ace.ObjectType.ToLower() == PASSWORD_GUID)
{
if (ace.Trustee == "Everyone")
{
acl.RemoveAce(ace);
de.CommitChanges();
}
else if (ace.Trustee == "NT AUTHORITY\\SELF")
{
acl.RemoveAce(ace);
de.CommitChanges();
}
}
}

//now put in the one we want
sd.DiscretionaryAcl = acl;
de.Properties["ntSecurityDescriptor"].Value = sd;
de.CommitChanges();
}

more...

C#:Active Directory:Check/Uncheck Password never expires


public void SetPasswordNeverExpiresProperty(bool PasswordNeverExpires)
{
DirectoryEntry de = GetDirectoryObject(UserName);
if (PasswordNeverExpires)
{
ActiveDirectoryHelper.SetProperty(de, "userAccountControl",
(int)de.Properties["userAccountControl"].Value | 0x10000);
}
else
{
ActiveDirectoryHelper.SetProperty(de, "userAccountControl",
(int)de.Properties["userAccountControl"].Value ^ 0x10000);
}
de.CommitChanges();
}

more...

C#:Active Directory:Check/Uncheck User must change password at next logon



public void SetuserHasToChangePasswordsInTheNextLoginProperty(bool userHasToChangePasswordsInTheNextLogin)
{
DirectoryEntry de = GetDirectoryObject(UserName);
if (userHasToChangePasswordsInTheNextLogin)
{
ActiveDirectoryHelper.SetProperty(de, "pwdLastSet", 0);
}
else
{
ActiveDirectoryHelper.SetProperty(de, "pwdLastSet", -1);
}
de.CommitChanges();
}

more...

treeview .net control style



<table> <tr> <td style="border: solid 1px;">
<div style="overflow:scroll;height:200px">
<asp:TreeView PopulateNodesFromClient = "true" EnableClientScript = "true"
ID="WebTreeView1" runat="server" ShowCheckBoxes="Leaf" Width="100%"
NodeStyle-ForeColor="DarkBlue"
NodeStyle-Font-Names="Verdana"
NodeStyle-Font-Size="8pt"
NodeStyle-HorizontalPadding="5"
NodeStyle-VerticalPadding="0"
NodeStyle-BorderColor="#FFFFFF"
NodeStyle-BorderStyle="solid"
NodeStyle-BorderWidth="0px"
RootNodeStyle-Font-Bold="true"
SelectedNodeStyle-BackColor="#cccccc"
SelectedNodeStyle-BorderColor="#888888"
SelectedNodeStyle-BorderStyle="solid"
SelectedNodeStyle-BorderWidth="0px"
ShowLines="True"
NodeIndent="15"
ExpandDepth="1"
PathSeparator="|"
>
</asp:TreeView>
</div>
</td></tr></table>

more...

asp.net treeview load expanded and keep selection

 

TreeNode newNode = new TreeNode();
string title=string.Format("{0};{1};{2};{3}", row["Field1"], row["Field2"], row["Field3"], row["Field4"]);
newNode.Text=string.Format("<input type='hidden' value='{0}'><span title='{0}' onclick='return false;'>{1}</span>;",title,Bezeichnung);
string val=string.Format("{0}",row["NameGroupID"]);
newNode.Value =val;
newNode.Checked=stored.Contains(val);
newNode.Expand();
ProduktbereichNode.ChildNodes.Add(newNode);

more...

asp.net treeview javascript search

Backward search:
 

function SearchBack(tv_id,str)
{
var tree = document.getElementById(tv_id);
var treeLinks = tree.getElementsByTagName('A');
eval(' var sel_name = '+tv_id+'_Data.selectedNodeID.value;');
var elem;
var sel_passed=0;
for(var element in treeLinks )
{
var sub1=treeLinks[element].firstChild;

if (sel_name && treeLinks[element].id==sel_name) {
sel_passed =1;
if (!sel_name || sel_passed==1) break;
}
if (sub1 && (''+sub1.value).indexOf(str) >=0)
{
//log("found"+treeLinks[element].id);
elem=treeLinks[element];
}
}

if (elem) {
eval('TreeView_SelectNode('+tv_id+'_Data,elem,"'+elem.id+'");');
elem.focus();
}else{
alert('Not found');
}
}


Forward search:
 

function SearchForward(tv_id,str)
{
var tree = document.getElementById(tv_id);
var treeLinks = tree.getElementsByTagName('A');
eval(' var sel_name = '+tv_id+'_Data.selectedNodeID.value;');
var elem;
var sel_passed=0;
for(var element in treeLinks)
{
var sub1=treeLinks[element].firstChild;
if (sub1 && (''+sub1.value).indexOf(str) >=0)
{
//log("found"+treeLinks[element].id);
elem=treeLinks[element];
if (!sel_name || sel_passed==1) break;
}

if (sel_name && treeLinks[element].id==sel_name) {
sel_passed =1;
}
}
if (elem) {
eval('TreeView_SelectNode('+tv_id+'_Data,elem,"'+elem.id+'");');
elem.focus();
} else{
alert('Not found');
}


}

make ubuntu business casual

to make ubuntu business casual - make it black remove background: gsettings set org.gnome.desktop.background picture-options ...