Archive

Archive for the ‘C#’ Category

Prevent system from entering sleep or turn off the display in .NET

April 22nd, 2013 No comments
Categories: C#, DOTNET

Custom Attributes in C# – code snippet

March 24th, 2013 No comments

Not a new topic as custom attributes but just a refresher. Below simple code snippets tells you how to create custom attributes and how to access the values using reflection.

    [TestAttribute("this is my name")]
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        private void Form1_Load(object sender, EventArgs e)
        {
            System.Reflection.MemberInfo info = typeof(Form1);
            foreach (var item in info.GetCustomAttributes(true))
            {
                if (item is TestAttribute)
                {
                    TestAttribute att = (TestAttribute)item;
                    Text = att.Name;
                }
 
            }
        }
 
    }
 
    [AttributeUsage(AttributeTargets.All)]
    public class TestAttribute : Attribute
    {
        public readonly string Name;
 
        public TestAttribute(string name)
        {
            Name = name;     
        }
 
    }
VN:F [1.9.18_1163]
Rating: 0.0/5 (0 votes cast)
Categories: C#

Read from Excel sheet (2007+) using OpenXML

January 19th, 2013 No comments

Below code snippet explains how to read data from an excel cell from .NET, here I use C# via OpenXml. Cell Format information like font style, datatype etc. I am not considering here.

Make sure you add reference to WindowsBase and DocumentFormat.OpenXml from OpenXML 2.x SDK.

using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml;

Here is the code snippet:

string filename = @"C:\path-to-excel\test1.xlsx";
string sheetname = "Sheet1"; // Sheet name
string colname = "A";int rownum = 1; // Eg: Cell "A1"
 
SpreadsheetDocument doc = SpreadsheetDocument.Open(filename,true);
WorkbookPart part = doc.WorkbookPart;
 
Sheet sheet = part.Workbook.Descendants<sheet>()
	.Where(x => x.Name == sheetname).FirstOrDefault();
Worksheet ws = ((WorksheetPart)(part.GetPartById(sheet.Id))).Worksheet;
 
Row row = ws.GetFirstChild<sheetdata>().
  Elements<row>().Where(r => r.RowIndex == rownum).First();
 
Cell cell = row.Elements<cell>().Where(c => string.Compare
       (c.CellReference.Value, colname +
       rownum, true) == 0).First();
Text = cell.StyleIndex.ToString();
 
SharedStringItem ssi = part.SharedStringTablePart.SharedStringTable
	.Elements<sharedstringitem>().ElementAt(int.Parse(cell.CellValue.Text));
 
Text = ssi.InnerText;
VN:F [1.9.18_1163]
Rating: 0.0/5 (0 votes cast)
Categories: C#, Code Snippets

SSRS Subscription : Get Scheduling information

January 15th, 2013 No comments
string report = @"/Report Project1/Report1";
 
ssrs1.ReportingService2005 rs = new ssrs1.ReportingService2005();
 
foreach(Subscription s in rs.ListSubscriptions(report,null)) {
	ExtensionSettings extsettings;
        string descr,status,eventtype, matchdata;
        ActiveState act;
        ParameterValue[] parameters;
        rs.GetSubscriptionProperties(s.SubscriptionID,
        	out extsettings,
                out descr,
                out act,
                out status,
                out eventtype,
                out matchdata,
                out parameters);
                textBox1.Text = matchdata;
}
return;
VN:F [1.9.18_1163]
Rating: 5.0/5 (1 vote cast)
Categories: C#, Code Snippets, SQL

SSRS: Create a Subscription programmatically

January 11th, 2013 No comments

This code snippet explains how to create a subscription programmatically in .NET. The type of subscription I used here is Report Server FileShare. You have to add extension parameters to make this working for email or what ever other subscription types you want to implement.

I found conflicting extension parameter information on internet mainly because of different versions of ssrs services available. My strategy was create one sample subscription in server and fetch it from a sample project and see what all parameters used. Yep, kind of reverse engineering :)

I used:

Here is the code snippet.

using System;
using System.Windows.Forms;
using System.Net;
using rpt_subscription.ssrs1;
 
namespace rpt_subscription
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        private void Form1_Load(object sender, EventArgs e)
        {
            string report = @"/Report Project1/Report1"; 
 
            ssrs1.ReportingService2010 rs 
			= new ssrs1.ReportingService2010();
            rs.Credentials 
			= new NetworkCredential("praveenn", "test");
 
            string desc = "Praveen test";
            string eventType = "TimedSubscription";
 
            string scheduleXml =
           @"<ScheduleDefinition>" +
            "   <StartDateTime>2013-01-10T09:00:00-08:00" +
            "   </StartDateTime>" +
            "   <WeeklyRecurrence>" +
            "      <WeeksInterval>1</WeeksInterval>" +
            "      <DaysOfWeek>" +
            "         <Monday>True</Monday>" +
            "      </DaysOfWeek>" +
            "   </WeeklyRecurrence>" +
            "</ScheduleDefinition>";
 
            ParameterValue[] extensionParams 
			= new ParameterValue[7];
 
            extensionParams[0] = new ParameterValue();
            extensionParams[0].Name = "RENDER_FORMAT";
            extensionParams[0].Value = "EXCEL";
 
            extensionParams[1] = new ParameterValue();
            extensionParams[1].Name = "FILENAME";
            extensionParams[1].Value = "test";
 
            extensionParams[2] = new ParameterValue();
            extensionParams[2].Name = "FILEEXTN";
            extensionParams[2].Value = "True";
 
            extensionParams[3] = new ParameterValue();
            extensionParams[3].Name = "PATH";
            extensionParams[3].Value = @"\\praveenvn\shared";
 
            extensionParams[4] = new ParameterValue();
            extensionParams[4].Name = "WRITEMODE";
            extensionParams[4].Value = "Overwrite";
 
            extensionParams[5] = new ParameterValue();
            extensionParams[5].Name = "USERNAME";
            extensionParams[5].Value = "praveenn";
 
            extensionParams[6] = new ParameterValue();
            extensionParams[6].Name = "PASSWORD";
            extensionParams[6].Value = "test";
 
            string matchData = scheduleXml;
            ExtensionSettings extSettings = new ExtensionSettings();
            extSettings.ParameterValues = extensionParams;
            extSettings.Extension = "Report Server FileShare";
 
            rs.CreateSubscription(report, extSettings,desc, 
			eventType, matchData, null);
        }
    }
}
VN:F [1.9.18_1163]
Rating: 5.0/5 (1 vote cast)
Categories: C#, Code Snippets, SQL

edmx: Entity Framework – how to insert & retrieve data in C#

December 24th, 2012 No comments

Retrieve using LINQ:

TrainingCentralModel.TrainingCentralEntities context 
	= new TrainingCentralModel.TrainingCentralEntities();
var cert = from d in context.CertMatrices select d;
CertificationList.DataSource = cert;
CertificationList.DataBind();

Insert/Save a record:

TrainingCentralModel.TrainingCentralEntities context 
	= new TrainingCentralModel.TrainingCentralEntities();
 
TrainingCentralModel.CertMatrix cert 
	= new TrainingCentralModel.CertMatrix();
cert.sponsor = "Microsoft";
cert.examcode = "070-480";
cert.examcode = "Programming in HTML5 with JavaScript and CSS3";
cert.examdate = DateTime.Now;
 
context.CertMatrices.AddObject(cert);
context.SaveChanges();
VN:F [1.9.18_1163]
Rating: 5.0/5 (1 vote cast)
Categories: C#

C# Razor Syntax Quick Reference

November 25th, 2012 No comments

Click here.

VN:F [1.9.18_1163]
Rating: 5.0/5 (1 vote cast)
Categories: ASP.NET, C#

Adding a watermark via windows explorer context menu in C#

August 26th, 2012 No comments

This post explains below things:

  • Adding a windows explorer context menu item
  • Adding a signature / watermark to a photo

STEP 1

static void Main(string[] args)
{
        if (args.Length &gt; 0)
        {
        // Do validations for file formats - 
        // because you will get exception if a non-image type is selected
        string filename = args[0]; 
 
        // Here goes your watermark file. Use a transparent PNG for effects
	string signature = @&quot;C:\Users\user\Desktop
				\watermark\watermark\signature.png&quot;;
 
	Image img = Image.FromFile(filename,true);
 
        Image imgsig = Image.FromFile(signature);
        // Do a size check. Exception will be thrown if a 
        // small size image than the watermark file is selected
 
	Graphics g = Graphics.FromImage(img);
        g.SmoothingMode = SmoothingMode.HighQuality;
        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
        g.PixelOffsetMode = PixelOffsetMode.HighQuality;
        g.DrawImage(imgsig, (img.Width - imgsig.Width) - 10, imgsig.Height);
 
        img.Save(filename.Replace(&quot;.&quot;, &quot;_01.&quot;));
        // Added _01 so that you wont loose the 
	// original file when experimenting this code :)
}

STEP 2

  1. Take registry editor. You can do this by typing “regedit” in command prompt
  2. Go to HKEY_CLASSES_ROOT\*\shell
  3. Add a key “Add Watermark” or a menu title of your choice
  4. Under this menu key, add another key called “Command”
  5. Make the default value of this key to the “<path to your EXE file>” “%1”. Eg: "C:\Users\user\Desktop\watermark\watermark\bin\Debug\watermark.exe" "%1"

Now, try right clicking on any image file. You should see the “Add Watermark” menu item.

image

Note: I wrote this code just to demonstrate, so no validations and coding standards followed.

VN:F [1.9.18_1163]
Rating: 4.7/5 (3 votes cast)
Categories: C#

Saving image using Imagetools in Silverlight

August 15th, 2012 1 comment

I wrote this script for the purpose of answering in a forum. Thought to post in the blog too.

Query: How to crop in oval shape an image in Silverlight and save it. My quick approach to save it was using Imagetools-for-silverlight.

You can download that library from codeplex – http://imagetools.codeplex.com/

This is how the output image looks like:

test

Below is the XAML to crop the image in Image element:

<Grid x:Name="LayoutRoot" Background="White">
<Image x:Name="Image1" Source="/SilverlightApplication1;component/Images/sample_image.jpg"
    Stretch="None" Margin="31,37,42,23">
            <Image.Clip>
                <EllipseGeometry x:Name="Ellipse" RadiusX="75" RadiusY="50"
            Center="150,120"/>
            </Image.Clip>
        </Image>
        <Button Content="Save" Height="23" HorizontalAlignment="Left" Margin="46,55,0,0" 
Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
    </Grid>

Below is the code for saving:

using ImageTools;
using ImageTools.IO.Png;
 
...
 
private void button1_Click(object sender, RoutedEventArgs e)	
{
	var dlg = new SaveFileDialog() {Filter = "*.png | *.png", 
	DefaultExt = ".png"};
 
	if ((bool) dlg.ShowDialog())	
	{
	var img = Image1.ToImage();
	var encoder = new PngEncoder();
	var stream = dlg.OpenFile();
	encoder.Encode(img, stream);
	stream.Close();
	}
}
VN:F [1.9.18_1163]
Rating: 4.5/5 (2 votes cast)
Categories: C#, Code Snippets, WPF-WCF-WF

Microsoft “Roslyn” CTP

July 20th, 2012 No comments

The Microsoft “Roslyn” June 2012 CTP installs as an extension to Visual Studio 2012 RC and Visual Studio 2010 SP1. “Roslyn” is a long lead project which we are considering for the post-Visual Studio 2012 timeframe. The CTP includes an early preview of the APIs exposed by the C# and Visual Basic compilers, and the C# Interactive window experience.

Download from here.

VN:F [1.9.18_1163]
Rating: 0.0/5 (0 votes cast)
Categories: C#, DOTNET, VB.NET