Posts mit dem Label C# werden angezeigt. Alle Posts anzeigen
Posts mit dem Label C# werden angezeigt. Alle Posts anzeigen

Mittwoch, 9. Februar 2011

iKnow Release 1.2

iKnow is a small wiki engine based on -ASP.Net MVC 3.0 and a single-table MSSQL database. I've created it to serve as an intranet knowledge database wiki.


0. Try
http://iknow.codebrewery.ch/iKnow


1. Download
http://iknowwiki.codeplex.com/

2. Install
Make sure you have installed the newest MVC release (3.0) and WebMatrix. You can get them via the Web Platform Installer: http://www.microsoft.com/web/downloads/platform.aspx



To enable image uploads, follow the instructions below:




3. Use


(It's actually called Vulcan, sorry ;-))

4. Have a beer
Congratulations, you're done.

Samstag, 25. Dezember 2010

Collection was modified exception

I saw some pretty strange solutions for this problem, most of all, ones which involve a "helper" list to store the items to remove... this of course is overkill (memory and cpu wise - think of collections with a million items ...)

Here's how to do it:
for (int i = pageList.Count; i-- > 0; )
{
    if (itemsToRemoveList.Contains(mainList[i]))
        mainList.RemoveAt(i);
}

Montag, 19. Juli 2010

C# selective clone with a generic extension method

Hey guys, ever had to clone an object - but only duplicate the properties you actually needed. Or maybe you don't want to copy the id property... Something like that, well then take a look at this.

public static class ObjectExtensions
{
 public static T SelectiveClone(this Object obj, string[] properties)
  where T: new()
 {
  T temp = new T();
  PropertyInfo[] propertyInfos = typeof(T).GetProperties();
  foreach (PropertyInfo pi in propertyInfos)
  {
   if(properties.Contains(pi.Name))
    pi.SetValue(temp, pi.GetValue(obj, null), null);
  }

  return temp;
 }
}

Well you can then do something like the following.
/* 
 Product is a class with the properties
 "title", "titleAlias", "subTitle", "description", 
 "price", "stock" and "id"
 "original" is an existing object of the class Product
*/

// The following copies all properties except "id"
Product product = original.SelectiveClone(new string[] {
 "title", "titleAlias", "subTitle", "description", "price", "stock"
});

Freitag, 9. Juli 2010

Silverlight 4: Bye bye ControlParameter

If you've been using Silverlight 4 and some of its ria stuff, you may have noticed that the ControlParameter has gone missing. Actually it has gone for good - and that's a good thing.

ControlParameter was a misfit, why? Look at the following (old) code:
<riaData:ControlParameter ParameterName="title"
                             ControlName="filterTextBox"
                             PropertyName="Text" />

Now there's no databinding, and that most certainly isn't the (new) .NET way. Check out below how it should look now, with Silverlight 4. Here we doe some data filtering with DomainDataSource.FilterDescriptor.

<riaControls:DomainDataSource Name="ExampleSource" QueryName="GetExampleQuery" AutoLoad="True">
<riaControls:DomainDataSource.FilterDescriptors>
<riaControls:FilterDescriptor PropertyPath="title"
Operator="Contains" Value="{Binding Text, ElementName=filterTextBox}">
</riaControls:FilterDescriptor>
</riaControls:DomainDataSource.FilterDescriptors>
<riaControls:DomainDataSource.DomainContext>
<domain:ExampleDataContext />
</riaControls:DomainDataSource.DomainContext>
</riaControls:DomainDataSource>

See, everything is well now. :-)

Freitag, 2. Juli 2010

Silverlight 4: Drag and drop from desktop or image

Ok, Silverlight 4 is here and everyone's very happy and excited (well.. I think it's just more fun now to use Silverlight - especially with the nice toolkit, which can be found on codeplex). Yesterday I tried one of the new features and wow, it was pretty easy to implement drag and drop for Silverlight 4 applications.

So let's say you got a Listbox, like the following one
<ListBox x:Name="myListBox" />
Now you have to add e few things:
  • Allow Drop with AllowTrop="True"
  • An eventhandler for the Drop event
  • And finally if you want eventhandlers for DragEnter and DragLeave
The whole thing should look like the following
<ListBox Name="myListBox" 
         AllowDrop="True" 
         Drop="myListBox_Drop" 
         DragEnter="myListBox_DragEnter" 
         DragLeave="myListBox_DragLeave" />
Lets talk about the "Drop" event for a moment. Drop supplies the event handler with the arguments from DragEventArgs: Take a look at it on MSDN. Here's how I handle the event
private void myListBox_Drop(object sender, DragEventArgs e)
{
 FileInfo[] droppedFiles = e.Data.GetData(DataFormats.FileDrop) as FileInfo[];

 for (int i = 0; i < droppedFiles.Length; i++)
 {
  this.myListBox.Items.Add(droppedFiles[i].Name);
                /* you have to access the data in the listbox via droppedFiles[i].OpenRead()
                   things like File.OpenRead(droppedFiles[i].FullName) won't work because
                   of the Silverlight 4 security model */
 }

 e.Handled = true;
}
Additionally you can use the DragEnter and DragLeave event to alert the user, that dragged files can be dropped on the object - just change the background colour or something like that (a border is quite nice as well).

Dienstag, 15. Juni 2010

Drag and Drop files from WPF ListViews to the Desktop / Windows Explorer

Hey guys, this morning (yeah, beginning 7.00) I tried to implement what seemed to be quite an easy task: Dragging files out of my app onto the desktop or into an open explorer Window.

It’s not quite easy. So let’s start this small tutorial. First (of course) you create an ListView – let’s call it “FileView”.

<ListView x:Name="FileView" 
PreviewMouseLeftButtonDown="FileView_PreviewMouseLeftButtonDown"
MouseMove="FileView_MouseMove">
<ListView.View>
<GridView>
<!-- Put in here whatever you need -->
<GridViewColumn Header="Name" CellTemplate="{StaticResource file}" />
</GridView>
</ListView.View>
</ListView>


Now to the code behind the xaml. You might have noticed that I added two events to the ListView. The PreviewMouseLeftButtonDown (the dragging starts) and the MouseMove (the dragging is happening).



private Point start;

private void FileView_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
this.start = e.GetPosition(null);
}

private void FileView_MouseMove(object sender, MouseEventArgs e)
{
Point mpos = e.GetPosition(null);
Vector diff = this.start - mpos;

if (e.LeftButton == MouseButtonState.Pressed &&
Math.Abs(diff.X) > SystemParameters.MinimumHorizontalDragDistance &&
Math.Abs(diff.Y) > SystemParameters.MinimumVerticalDragDistance)
{
if (this.FileView.SelectedItems.Count == 0)
{
return;
}

// right about here you get the file urls of the selected items.
// should be quite easy, if not, ask.
//string[] files = ...;
string dataFormat = DataFormats.FileDrop;
DataObject dataObject = new DataObject(dataFormat, files);
DragDrop.DoDragDrop(this.FileView, dataObject, DragDropEffects.Copy);
}
}


Now that’s that, thanks for reading.

Donnerstag, 13. Mai 2010

Reading excel file with C#

Excel files can easily be read from C# using OleDbDataAdapter. You just need the correct connection string - and that's where it gets a little complicated. You have to specify the version of Excel in the connection string.

Now there are pretty many connection strings that look like this one floating around the Internet

string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
    "Data Source=" + fileName + ";" +
    "Extended Properties=Excel 8.0;";

Don't use this one, use this one instead:

string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" +
    "Data Source=" + fileName + ";" +
    "Extended Properties=Excel 12.0;";

The first connection string provides access only to older (Excel 97) Excel files - which nowadays isn't really of any use anymore. The second one uses THE ACE OLEDB Driver in version 12.0, which is able to handle the new Excel format (files with the extension .xlsx).

The other thing we need is an OleDbDataAdapter, which can be found in the following namespace

using System.Data.OleDb;

Now we got all this settled, let's take a look at the actual code

using System.Data.OleDb;

namespace Examples.Data
{

class ExcelAdapter
    {
        private OleDbDataAdapter dataAdapter;
        private DataSet dataSet;
        private DataTable dataTable;

        private String fileName;

        public ExcelAdapter(String fileName)
        {
            this.Load(fileName);
            this.fileName = fileName;
        }

        public void Reload()
        {
            this.Load(this.fileName);
        }

        private List Load(String fileName)
        {
            string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" +
                "Data Source=" + fileName + ";" +
                "Extended Properties=Excel 12.0;";

            this.dataAdapter = new OleDbDataAdapter("SELECT * FROM [Blonskij$]", connectionString);

            this.dataSet = new DataSet();

            this.dataAdapter.Fill(this.dataSet, "ExcelInfo");
            this.dataTable = this.dataSet.Tables["ExcelInfo"];
            foreach (DataRow row in this.dataTable.AsEnumerable())
            {
                
            }

            return new List();
        }
    }}

Now mind the following line

this.dataAdapter = new OleDbDataAdapter("SELECT * FROM [MySheet$]", connectionString);

Here you have to specify the Sheet in the chosen Excel file.

That's that. I hope it helps.

Socialize!