how to send parameters to stored procedure using enterprise library - database

I have to log Exception in database, I've created pprocedure, configured Database Trace Listener, but I can't understand, how to send parameters to stored procedure in database, what esle should be configured?

/*
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.Common;
using System.Data.Odbc;
using System.Data.OleDb;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Data.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Data.Sql;
*/
public int DeleteSomething(System.Guid userUUID)
{
int rowsAffected = 0;
try
{
Database db = this.GetDatabase();
DbCommand dbc = db.GetStoredProcCommand("dbo.uspDeleteSomething");
dbc.CommandTimeout = 600;
db.AddInParameter(dbc, "#UserUUID", System.Data.DbType.Guid, userUUID );
rowsAffected = db.ExecuteNonQuery(dbc);
}
finally
{ }
return rowsAffected;
}
protected Microsoft.Practices.EnterpriseLibrary.Data.Database GetDatabase()
{
Database returnDb;
returnDb = Microsoft.Practices.EnterpriseLibrary.Data.DatabaseFactory.CreateDatabase();
return returnDb;
}

Related

Close/cancel open X509Certificate2UI certificate selection and pin dialog programmatically without further user interaction

I have a function that is executed in a C# Task object (part of a Winforms .NET 4.7.2 application) that asks the user to select a certificate from the windows certificate store using the X509Certificate2UI class.
There can be a situation where the corresponding selection dialog is open and waiting for user input when the task is canceled using the cancellation token. My expectation was that the selection dialog would then be automatically closed/canceled too, but it remains open.
The same problem applies to the dialog for entering the PIN securing the private key of a certificate.
Is there any clean way to cancel the dialog programmatically or to assure that it closes with the task?
The following code demonstrates the problem. One task opens the selection dialog. A second task simulates an event triggered after the dialog is opened. Once DoSomethingDifferent is done, the certificate is not required anymore and the selection dialog should therefore be closed. It however stays open until the program exits.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace CancelCertificateDialog
{
class Program
{
private static X509Certificate2 SelectCertificate()
{
// Selecte certificate from store
var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
X509Certificate2Collection collection = (X509Certificate2Collection)store.Certificates;
X509Certificate2Collection selectedCertificate = (X509Certificate2Collection)collection.Find(X509FindType.FindByKeyUsage, X509KeyUsageFlags.DigitalSignature, false);// (X509FindType.FindByKeyUsage, X509KeyUsageFlags.DigitalSignature, true);
selectedCertificate = X509Certificate2UI.SelectFromCollection(
store.Certificates,
"Certficates",
"Select a certificate for signing the document",
X509SelectionFlag.SingleSelection);
return selectedCertificate[0];
}
private static void DoSomethingDifferent()
{
Thread.Sleep(4000);
Console.WriteLine("I'm done");
}
static void Main(string[] args)
{
Console.WriteLine("Start");
CancellationTokenSource tokenSource = new CancellationTokenSource();
CancellationToken token = tokenSource.Token;
Task<X509Certificate2> t1 = new Task<X509Certificate2>(() => SelectCertificate(), token);
Task t2 = new Task(() => DoSomethingDifferent(), token);
t1.Start();
t2.Start();
try
{
Task.WaitAny(t1, t2);
}
catch (AggregateException e)
{
for (int j = 0; j < e.InnerExceptions.Count; j++)
{
Console.WriteLine(e.InnerExceptions[j]);
}
}
Console.WriteLine("The certificate is not required anymore. Get rid of the dialog");
tokenSource.Cancel();
Console.WriteLine("Press Key");
Console.ReadKey();
}
}
}

Hangfire: Azure SQL: Adding a new job is failing

Getting the below error
Inner Exception: "Object reference not set to an instance of an object."
Stack Trace:
at System.Transactions.Transaction.GetPromotedToken()
The error comes from the line connection.EnlistTransaction(Transaction.Current); in below code even if i set enlist=false in the connection string.
`internal T UseTransaction<T>([InstantHandle] Func<DbConnection, DbTransaction, T> func, IsolationLevel? isolationLevel)
{
#if NETFULL
using (var transaction = CreateTransaction(isolationLevel ?? _options.TransactionIsolationLevel))
{
var result = UseConnection(connection =>
{
connection.EnlistTransaction(Transaction.Current);
return func(connection, null);
});
transaction.Complete();
return result;
}
}`
when we set enlist=true, then we get error at the line connection.Open(); from the below code
internal DbConnection CreateAndOpenConnection()
{
if (_existingConnection != null)
{
return _existingConnection;
}
var connection = new SqlConnection(_connectionString);
connection.Open();
return connection;
}
both the methods are present under Hangfire.SqlServer.SqlServerStorage class
Same code works when connected to the local DB (SQL server 2014).
Landed on a discussion WCF Transaction against Azure SQL DB, not sure if it is relevant for this issue.
Edit:
HangFire Configuration
GlobalConfiguration.Configuration.UseSqlServerStorage(
Database.ConnectionString,
new SqlServerStorageOptions
{
QueuePollInterval = TimeSpan.FromSeconds(10),
PrepareSchemaIfNecessary = true
});
Job Enqueue
BackgroundJob.Enqueue(() => Update(connectionToken, intFileUniqueId));
Please help.
Thanks in advance.
Found the issue. call to method to queue job was inside transaction which was somehow leading to Distribution Transaction and Azure SQL doesn't support it.
Consider the code below:
public override void UpdateFile(int intUniqueId)
{
using (var scope = GetTransactionScope(...))
{
QueueJob<Updater>(x => x.Update(token, intUniqueId));
scope.Complete();
}
}
private static void QueueJob<T>(Expression<Action<T>> action)
{
BackgroundJob.Enqueue(action);
}
Removing the transaction scope in callee method works.
I'm checking the necessity of the transaction scope, if not required, I'll remove it.!!!

how to Ping ip address with parameter(-n,-t etc) in c#

I am developing a windows form application. I have a requirement, need ping the system ip address with parameters. like ping IP Address -n 1.
I am Unable to pass the parameter using ping.send function.
Any one can help me.
use Ping class. This provides a more organized approach
using System;
using System.Net;
using System.Net.NetworkInformation;
using System.Text;
namespace Examples.System.Net.NetworkInformation.PingTest
{
public class PingExample
{
// args[0] can be an IPaddress or host name.
public static void Main (string[] args)
{
Ping pingSender = new Ping ();
PingOptions options = new PingOptions ();
// Use the default Ttl value which is 128,
// but change the fragmentation behavior.
options.DontFragment = true;
// Create a buffer of 32 bytes of data to be transmitted.
string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
byte[] buffer = Encoding.ASCII.GetBytes (data);
int timeout = 120;
PingReply reply = pingSender.Send (args[0], timeout, buffer, options);
if (reply.Status == IPStatus.Success)
{
Console.WriteLine ("Address: {0}", reply.Address.ToString ());
Console.WriteLine ("RoundTrip time: {0}", reply.RoundtripTime);
Console.WriteLine ("Time to live: {0}", reply.Options.Ttl);
Console.WriteLine ("Don't fragment: {0}", reply.Options.DontFragment);
Console.WriteLine ("Buffer size: {0}", reply.Buffer.Length);
}
}
}
}
You can spam a cmd process and get its output.
ProcessStartInfo processInfo = new ProcessStartInfo("cmd");
processInfo.RedirectStandardInput = true;
processInfo.RedirectStandardOutput = true;
processInfo.UseShellExecute = false;
processInfo.CreateNoWindow = true;
Process process = Process.Start(processInfo);
process.StandardInput.WriteLine("ping 127.0.0.1 -n 1 -i 10");
process.StandardInput.Close();
string answer = process.StandardOutput.ReadToEnd();
process.WaitForExit();
process.Close()
Console.WriteLine(answer);

render pdf from memorystream

I have searched for entire day for a solution, but somehow I couldn't find it.
What I wanted is to get data from database (binary file such as PDF) into MemoryStream (which I succeeded to do so), but problem is when I wish to preview that file into WebBrowser control.
so the code goes:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.IO;
namespace MemoryStreamTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
MemoryStream memory = new MemoryStream();
//byte[] temp;
private void Form1_Load(object sender, EventArgs e)
{
memory = GetBlobFile();
}
private MemoryStream GetBlobFile()
{
MemoryStream ms = new MemoryStream();
string SQL = "SELECT [SnapshotPDF] FROM [DBtest].[dbo].[SamplePDF] WHERE id = " + 21;
SqlConnection conn = new SqlConnection("Data Source=database;Initial Catalog=DBtest; User ID=test; Password=test;");
SqlCommand comm = new SqlCommand(SQL, conn);
conn.Open();
byte [] result = (byte[])comm.ExecuteScalar();
conn.Close();
if (result != null)
{
ms.Write(result, 0, result.Length);
ms.Position = 0;
}
return ms;
}
private void button1_Click(object sender, EventArgs e)
{
//webBrowser1.DocumentText = "application/pdf";
webBrowser1.DocumentStream = memory;
}
}
}
Actually webBrowser really output content from memory, but obviously from picture above it's rendered as text...
How can I force to render as PDF?
If it is not possible to use webBrowser control, is there any other controls that I can use in WinForms that would preview/render PDF from memory.
You have to implement an async pluggable protocol, e.g. IClassFactory, IInternetProtocol... Then you use CoInternetGetSession to register your protocol. When IE calls your implementation, you can serve your image data from memory/provide mime type.
It's a bit tedious, but doable. Look at IInternetProtocol and pluggable protocols documentation on MSDN.
Done, I found one little bug which I correct it. this is entire code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.IO;
using Ghostscript.NET;
using Ghostscript.NET.Viewer;
namespace MemoryStreamTest
{
public partial class Form1 : Form
{
Stream stream;
byte[] result;
private GhostscriptViewer _viewer;
private GhostscriptVersionInfo _gsVersion = GhostscriptVersionInfo.GetLastInstalledVersion();
private Bitmap _pdfPage = null;
public Form1()
{
InitializeComponent();
pictureBox1.Width = 100;
pictureBox1.Height = 100;
_viewer = new GhostscriptViewer();
_viewer.DisplaySize += new GhostscriptViewerViewEventHandler(_viewer_DisplaySize);
_viewer.DisplayUpdate += new GhostscriptViewerViewEventHandler(_viewer_DisplayUpdate);
_viewer.DisplayPage += new GhostscriptViewerViewEventHandler(_viewer_DisplayPage);
}
private void Form1_Load(object sender, EventArgs e)
{
GetBlobFile();
}
private void GetBlobFile()
{
string SQL = "SELECT [SnapshotPDF] FROM [test].[dbo].[InvoiceAdded] WHERE id = " + 21;
SqlConnection conn = new SqlConnection("Data Source=test;Initial Catalog=test; User ID=test; Password=test;");
SqlCommand comm = new SqlCommand(SQL, conn);
conn.Open();
result = (byte[])comm.ExecuteScalar();
conn.Close();
stream = new MemoryStream(result);
}
private void button1_Click(object sender, EventArgs e)
{
ConvertToBitmap();
}
private void ConvertToBitmap()
{
_viewer.Open(stream, _gsVersion, true);
}
//DisplayPage
void _viewer_DisplayPage(object sender, GhostscriptViewerViewEventArgs e)
{
pictureBox1.Invalidate();
pictureBox1.Update();
}
//DisplaySize - dynamically
void _viewer_DisplaySize(object sender, GhostscriptViewerViewEventArgs e)
{
pictureBox1.Image = e.Image;
}
//DisplayUpdate - automatic update picture
void _viewer_DisplayUpdate(object sender, GhostscriptViewerViewEventArgs e)
{
pictureBox1.Invalidate();
pictureBox1.Update();
}
}
}
keep in mind that for this I needed to add .dll from Ghostscript.NET (a nice wrapper made by my patriot from Croatia), also I needed to install Ghostscript interpreter from GhostScript interpreter
And also many thanks to user: sm.abdullah
which actually point me to right direction.
Cheers

How to save an stringbuilder's content to text file using SaveFileDialog?

This is a winforms application.
In windows, I want the user to click and button, and then a popup should make the user select the path of where they want to save the file.
You want the WriteAllText function.
using (SaveFileDialog dialog = new SaveFileDialog()) {
if (dialog.ShowDialog(this) == DialogResult.OK) {
File.WriteAllText(dialog.FileName, yourStringBuilder.ToString());
}
}
Think no longer...
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication2 {
public partial class Form1 : Form {
StringBuilder sb = new StringBuilder();
public Form1() {
InitializeComponent();
sb.Append("This is going ");
sb.Append("to be saved to a text file");
}
private void button1_Click(object sender, EventArgs e) {
using (SaveFileDialog dlg = new SaveFileDialog()) {
if (dlg.ShowDialog() == DialogResult.OK) {
string fileName = dlg.FileName;
SaveToFile(fileName);
}
}
}
private void SaveToFile(string fileName) {
System.IO.TextWriter w = new System.IO.StreamWriter(fileName);
w.Write(sb.ToString());
w.Flush();
w.Close();
}
}
StringBuilder.ToString() will get you the string.
This link will show you how to write text to a file.
This link will show you how to call SaveFileDialog and pass a stream to it to save.
Hope that helps.
StringBuilder.ToString() can be passed to the TextStream.Write() method after creating the file.
Using the SaveFileDialog class, you can let the user select path and file name - in a standard way. Detailed examples in the doc.

Resources