Wednesday, October 28, 2009

How to increase sound level using C#

To increase sound level using C# first of all you should add line:

using System.Runtime.InteropServices;

to allow using COM Interop in your class.

Next we derlare two functions from an unmanaged DLL:


[DllImport("winmm.dll")]
public static extern int waveOutGetVolume(IntPtr hwo, out uint dwVolume);

[DllImport("winmm.dll")]
public static extern int waveOutSetVolume(IntPtr hwo, uint dwVolume);



Using these functions, we can increase or decrease the sound level of the sound card.
The following example shows how to mute the sound.


waveOutSetVolume(IntPtr.Zero, 0);


Check out калькулятор автокредита

Friday, October 23, 2009

Capture Sound and save into wav or mp3 file .NET C# example

It's surprising that there are no components for sound capturing in .NET Framework 3.5. Even designers of WPF and Silverlight 2.0 were focused on graphics so deeply, that they forgot about applications recording sound from user's microphone. It is said that the next version of Silverlight will provide such functionality.

However, what you often want to achieve is to store the recorded sound in MP3 file (or send it as MP3 stream). That's legally complicated due to MP3 patent constraints. And for the same legal reason, we can assume that we will not see MP3 functionality in Microsoft technologies soon (there is WMA instead).

This article uses a subset of C# MP3 Compressor libraries written by Idael Cardoso which in turn are partially based on A low level audio player in C# by Ianier Munoz. See this website for technical and copyright information regarding the LAME project.

In codeproject.com/KB/audio-video/Mp3SoundCapture.aspx you find an easy to use .NET 3.5 component, providing Sound Capturing functionality for a Windows application. It outputs data as raw PCM samples or a regular WAV file. Or you can just set one boolean property to use LAME DLL and perform MP3 compression on the fly.

Wednesday, July 29, 2009

How to get data from Firebird database using MS SQL Server stored procedure

In solving one of the tasks (рассчет автокредита) I needed an opportunity to perform stored procedure of SQL Server 2005, to receive data from the FireBird database.

Typically stored procedure in T-SQL can not do this, so I wrote a stored procedure in C#, which receives the necessary data to the DataTable(s), from where then method SqlContext.Pipe.SendResultsRow, passing a string SQL Server.
Here is the example:


public class SQLFIREBIRDCLR
{

[SqlProcedure()]
public static void ProcedureToFirebird(SqlString sServerName, SqlString sDatabaseName)
{

FbConnectionStringBuilder cs = new FbConnectionStringBuilder();
cs.DataSource = sServerName.ToString();
cs.Database = sDatabaseName.ToString();
cs.UserID = "SYSDBA";
cs.Password = "masterkey";
cs.Dialect = 3;
string ConnectionString = cs.ToString();

SqlDataRecord record = new SqlDataRecord(
new SqlMetaData("field1", SqlDbType.SmallInt),
new SqlMetaData("field2", SqlDbType.NVarChar, 30));


SqlContext.Pipe.SendResultsStart(record);
DataTable dt = new DataTable();
FbConnection conn = new FbConnection(ConnectionString);
using (conn)
{
string ssql = "select field1, field2 from table1";
FbCommand command = new FbCommand(ssql, conn);
FbDataAdapter adapt = new FbDataAdapter(command);
conn.Open();
adapt.Fill(dt);

}

foreach (DataRow dr in dt.Rows)
{
record.SetValue(0, dr["field1"]);
record.SetValue(1, dr["field2"]);
SqlContext.Pipe.SendResultsRow(record);
}
SqlContext.Pipe.SendResultsEnd();
}

}

Wednesday, May 6, 2009

How to connect to SQL Server 2008 using 2005

While supporting the website калькулятор на автокредит I encountered a problem when I use SQL Server Management Studio in SQL Server 2005 to connect to an instance of SQL Server 2008.
To solve this problem, I installed Microsoft SQL Server 2005 Service Pack 2. After that I also installed "Cumulative update package 12 for SQL Server 2005 Service Pack 2 (server and client)".
And, voila, it works!

Tuesday, April 28, 2009

How to sort the hierarchical recursive query in SQL Server 2005

In SQL Server 2005 was an innovation in the form of CTE (common table expressions), which enables the hierarchical recursive queries to the database. While designing the web site автокредит на автомобиль I have a challenge: to display the hierarchical structure of pages of the site. The query also have to sort sort the data on a field "pageorder" from the pages with the same level of hierarchy.

The structure of the table looks like this:


CREATE TABLE [dbo].[pages](
[id] [int] NULL,
[pid] [int] NULL,
[title] [nvarchar](max) NULL,
[pageorder] [int] NULL
) ON [PRIMARY]


The field "pid" points to id of the parent record. In addition, there have to exist a root(entry) record, whose pid = NULL.

Below is a sample request that selects and sorts the hierarchical data:


WITH CTE(pid, id, title, level, pageorder, pathstr) AS
(
SELECT pid, id, title, 0, 0, CAST ('/' AS VARCHAR(MAX))
FROM pages
WHERE pid IS NULL
UNION ALL
SELECT e.pid, e.id, e.title, level + 1, e.pageorder, d.pathstr + CAST(e.pageorder as VARCHAR) + '/'
FROM pages e
INNER JOIN CTE d
ON e.pid = d.id

)
SELECT pid, id, replicate('... ', level) + title as title, level, pageorder, pathstr
FROM CTE
ORDER BY pathstr


Here's what we get after execution the query:


pid id level pageorder pathstr title
----------- ----------- ----------- ----------- ----------- ---------------------------------
NULL 1 0 0 / Main
1 4 1 3 /3/ ... Products
4 5 2 3 /3/3/ ... ... cars
4 8 2 6 /3/6/ ... ... motorcycles
1 2 1 6 /6/ ... Services
2 6 2 3 /6/3/ ... ... Lease
2 3 2 6 /6/6/ ... ... Loans
1 7 1 9 /9/ ... about website

(8 row(s) affected)

Wednesday, March 25, 2009

How to disable passing of HTTP header "Expect: 100-continue" using HttpWebRequest in .NET Framework in C#?

How to disable passing of HTTP header "Expect: 100-continue" using HttpWebRequest in .NET Framework in C#?
По умолчанию, при выполнении веб-запроса, используя класс HttpWebRequest, .NET Framework добавляет HTTP заголовок (HTTP header) "Expect: 100-continue". Для того, чтобы запретить формирование этого заголовка нужно сделать следующее:

As default when You use HttpWebRequest class to execute web-requests it appends HTTP header "Expect: 100-continue" to it's headers collection. To disable passing of HTTP header "Expect: 100-continue" using HttpWebRequest You can do following:


HttpWebRequest myHttpWebRequest = (HttpWebRequest)HttpWebRequest.Create("http://a-kicker.blogspot.com");
myHttpWebRequest.ServicePoint.Expect100Continue = false;

How to place DateTimePicker onto ToolStrip control in Windows Forms .NET application?

To place DateTimePicker onto ToolStrip control in Windows Forms .NET application you had to do following:

DateTimePicker dateTimePcr = new DateTimePicker();
toolStrip1.Items.Add(new ToolStripControlHost(dateTimePcr));

Tuesday, March 3, 2009

How to enabling Gzip and Deflate HTTP Compression in ASP.NET pages

If your ASP.NET web application doesn't already contain a Global.asax file, create a new one using notepad. Then insert following code in it:


<%@ Application Language="C#" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.IO.Compression" %>

<script runat="server">
void Application_PreRequestHandlerExecute(object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication;
string acceptEncoding = app.Request.Headers["Accept-Encoding"];
Stream prevUncompressedStream = app.Response.Filter;

if (!(app.Context.CurrentHandler is Page) ||
app.Request["HTTP_X_MICROSOFTAJAX"] != null)
return;

if (acceptEncoding == null || acceptEncoding.Length == 0)
return;

acceptEncoding = acceptEncoding.ToLower();

if (acceptEncoding.Contains("deflate") || acceptEncoding == "*")
{
// defalte
app.Response.Filter = new DeflateStream(prevUncompressedStream,
CompressionMode.Compress);
app.Response.AppendHeader("Content-Encoding", "deflate");
} else if (acceptEncoding.Contains("gzip"))
{
// gzip
app.Response.Filter = new GZipStream(prevUncompressedStream,
CompressionMode.Compress);
app.Response.AppendHeader("Content-Encoding", "gzip");
}
}
</script>

Thursday, February 19, 2009

Dotnetnuke: how to force dotnetnuke to send welcome e-mail as HTML not plain text

To force dotnetnuke to send welcome e-mail as HTML, you just have to modify MAIL_USER_REGISTRATION_PUBLIC_BODY.Text or EMAIL_USER_REGISTRATION_PRIVATE_BODY.Text strings in language editor. DNN Framework check if the mailbody contains html code and send e-mail in corresponding mode.

Wednesday, February 18, 2009

How to show name of sender before the e-mail address using ASP.Net MailMessage object

How to show name of sender before the e-mail address using ASP.Net MailMessage object? It's very simple. Just look at following example:


System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
message.From = new System.Net.Mail.MailAddress("admin of TEST.COM <admin@test.com>");


That code was used in writing website Краш-тесты автомобилей

Thursday, February 5, 2009

How to change in code the title of web page in Dotnetnuke based website?

In the ordinal web page to change programmatically the title of the .aspx page is simple:


protected void Page_Load(object sender, EventArgs e)
{
this.Title = "The ordinal web page";
}


In dotnetnuke's module that code will not help. The title of the web page will be created by DNN's core.

But we can solve this problem. The code below shows how to achieve this:


protected void Page_Load(object sender, EventArgs e)
{
DotNetNuke.Framework.CDefault page = (DotNetNuke.Framework.CDefault)this.Page;
page.Title = "Веб-страница в Dotnetnuke";
}



You can see here how it works.

Tuesday, February 3, 2009

LINQ to SQL: How to get a Random Record from a Table inside the SQL Server Database

I wanted to get a random record from a particular table on the SQL Server database. For my case, I had a table containing quotes, and I wanted to randomly pick on to show on one corner of my web site. I am also using LINQ to SQL for this web site, so the solution here will be using LINQ, although the approach is pretty simple and flexible.

The idea centers on ordering the records by a random parameter an then getting the TOP n number of records. The NEWID() function from SQL Server makes a great candidate for getting a random parameter since this method generates a GUID.

In SQL Server, try out this query.


SELECT * FROM Quote ORDER by NEWID();


SELECT TOP 1 * FROM Quote ORDER by NEWID();


Now for our code, we need to duplicate this behavior on .NET. I needed to get an equivalent of NEWID() on my LINQ to SQL DBML. Note that we cannot use NEWID() directly on a stored procedure or function since SQL Server will complain with an “Invalid use of side-effecting or time-dependent operator in 'newid' within a function” error. The workaround is to create a view that uses the NEWID() and then a function that selects from the view.


CREATE VIEW [dbo].[RandomView]
AS
SELECT NEWID() As ID
GO
CREATE FUNCTION [dbo].[GetNewId]
(
)
RETURNS uniqueidentifier
AS
BEGIN
RETURN (SELECT ID FROM RandomView)
END
GO


On our DBML, we simple drag and drop the Quote table and the GetNewID function to our designer. The code below takes a random record from the Quotes table.


DataContext db = new QuoteDataContext();
var quote = db.Quote.OrderBy(q => db.GetNewId()).First();


Actually, once the objects are in place, we can use them to get x number of random records from any table.