Customization on WPF ListView

June 5, 2013 2 comments

If  some one is planning to simply bind a list of datas to a listview in WPF its pretty easy and straight forward. But today i came through a case where i need a listbox that supports Sorting , Inline Editting and Save the chages to Db once i finish the inline edit .

I started one by one  1. Sorting and Inline Editting  > Using the logic or idea from this blog http://tech.pro/tutorial/857/wpf-tutorial-using-the-listview-part-3-in-place-edit

2. Saving the changes after finish the edit operation to Db – Add a new event to the textbox where you want to edit the data and do actions on that event

LostFocus=”textWordDescription_LostFocus” Tag=”{Binding}”

             string newtext = ((TextBox)sender).Text;
BindedObject selected = ((TextBox)sender).Tag as BindedObject;
updateDetails(selected.Id,selected);

Then next challenge is  want to sort my datas in ascending order . The following code solves that issue

  private void Sort(string sortBy, ListSortDirection direction)
{
ICollectionView dataView =
CollectionViewSource.GetDefaultView(wordBankListView.ItemsSource);
dataView.SortDescriptions.Clear();
SortDescription sd = new SortDescription(sortBy, direction);
dataView.SortDescriptions.Add(sd);
dataView.Refresh();
}

Next Challenge is with selection . By default i want to select an item in listbox (Its  pretty easy thing . just set selectedvalue ). But i need to handle the position of scrollviewer as well . If 100 items in listbox and i selected an item starts with letter z then thae item is in bottom of list , So using this code i make sure the scrollviewer position is closer to selected wordSystem.Windows.Controls.Primitives.Selector selector = wordBankListView;
(selector as ListBox).ScrollIntoView(selector.SelectedItem);

Categories: Prsnl References Tags: ,

MVC Models in LINQtoSQL way

December 21, 2012 Leave a comment

ASPNET_MVC_Tutorial_10_CS

A sample tutorial i found while learning LINQ2SQL in MVC3 . Dont remember the resource owner or source site, But is really a useful post

Categories: Prsnl References Tags: ,

Async. Download progress bar c#

December 4, 2012 Leave a comment

The code for creating an async. download progress bar , allows user to track how much data is downloaded

WebClient client = new WebClient();

client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);

client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);

//// Starts the download

string folder_path =”Location to save file”;

client.DownloadFileAsync(new Uri(downloadUrl), folder_path,””);

void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)

{

double bytesIn = double.Parse(e.BytesReceived.ToString());

double totalBytes = double.Parse(e.TotalBytesToReceive.ToString());

double percentage = bytesIn / totalBytes * 100;

 

downloadProgress.Text = int.Parse(Math.Truncate(percentage).ToString()).ToString()+” % finished”;

}

Categories: Prsnl References Tags: , , , ,

Uploading large files in ASP.Net

May 12, 2012 Leave a comment

I think below info is very useful for anyone using the HttpWebRequest class to send request data.

There are basically 3 ways to make an HTTP request that contains a payload:

  1. If the payload is amll, you can call [Begin]GetRequestStream and it will immediately return a memory-backed stream that buffers the request payload. Then, when you call [Begin]GetResponse, the HttpWebRequest object calculates the ContentLength header based on how much data was written to the stream and then it initiates the I/O.
  2. If the payload is large (2GB, for example), then you shouldn’t cache the whole payload in memory before sending it. In this case, you’d set the ContentLength property explicitly to the payload size. Then when you calll [Begin]GetRequestStream, it now performs all of the I/O up to the point of sending the payload. You now write your payload to the stream which now sends its directly to the network (it does not get sent to an in-memory stream). When you call [Begin]GetResponse, it checks that the amount of data sent matches what you specified for the ContentLength property and does no additional I/O in order to start receiving the response.
  3. If the payload is potentially large, generated at runtime, and you don’t know the its size ahead of time then you set HttpWebRequest’s SendChunked property to true (and do not set the ContentLength property). When you call [Begin]GetRequestStream, all of the I/O is performed up to the point of sending the payload data (including a “Trasnsfer-Encoding: Chunked” header). You now write to the stream in chunks and these writes go directly to the network. When you close the stream, a special terminating chunk is sent to notify the server that the payload is done. When you call [Begin]GetResponse, no I/O is performed and you can start receiving the response.
Categories: Prsnl References Tags:

Custom Bindings in WPF simple example

November 2, 2011 Leave a comment

A complete tutorial on this topic is found on http://simonhartcher.com/2009/12/12/image-caching-for-a-wpf-desktop-application/  and you can read  the formatted version of the same blog here

For  developing a WPF Desktop Application that fetches images from a web server. One of the shortfalls of WPF is that client side caching is not implemented, but you can do it yourself using custom bindings.

Consider the following code where the binding ImageAddress points to an image on some web server (www.someserver.com/image.jpg):

<Image Source="{Binding ImageAddress}"/>

Each time the Window in which this code resides is loaded the image will be fetched from the web server.

Every time you say?! Every time…

Considering the application we are working on will be displaying a lot of images, this is just not acceptable.

using the Binding.Converter attribute I could pass the value of the Source attribute to a Converter and then back again.the path of local file or cached file.

To create a converter you create a class that implements IValueConverter requires that you implement two methods:

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)

Convert will be used to convert the data you pass to it into the desired format to display on the form. ConvertBack is the reverse, where any changes the user makes to the data displayed on the form may need to be converted back to a format that you require for processing (eg. to send to a database). Here is an example as provided on msdn: > The following example shows the implementation of a date converter that converts the date value passed in so that it only shows the year, the month, and the day. When implementing the IValueConverter interface, it is a good practice to decorate the implementation with a ValueConversionAttribute to indicate to development tools the data types involved in the conversion, as in the following example:

[ValueConversion(typeof(DateTime), typeof(String))]
public class DateConverter : IValueConverter
{
  public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
  {
    DateTime date = (DateTime)value;
    return date.ToShortDateString();
  }

  public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  {
    string strValue = value as string;
    DateTime resultDateTime;
    if (DateTime.TryParse(strValue, out resultDateTime))
    {
      return resultDateTime;
    }
    return DependencyProperty.UnsetValue;
  }
}

As you can see, in Convert value is cast to a DateTime object and then returned as a string using ToShortDateString(). Then in ConvertBack (which will be passed a string from the form) the string is parsed into a date using DateTime.TryParse() and then returned if it completes successfully.

So, onto the specific problem of caching an image on the local machine. I start with an empty class called ImageCacher implementing stub methods from IValueConverter. As we are grabbing the web address from a database, we are not interested in sending the local address back to the database, so we can simply complete ConvertBack returning a null value.

//Not needed – return null
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
  return null;// or  throw new NotImplementedException("Two way conversion is not supported.");
}

We then add the ValueConversionAttribute to indicate to development tools the data types involved in the conversion. This is not compulsory, but I think it also makes understanding what the converter is doing easier in a single glance. Our goal is to grab the string from the Source attribute and then pass one back with the updated image location (after we save it locally). So in this case, we are converting from a string to a string.

[ValueConversion(typeof(string), typeof(string))]
class ImageCacher : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
	
//Cast the string into a Uri so we can access the image name without regex
var uri = new Uri((String)value);
var localFile="";/find path of local file using own logic
if (!File.Exists(localFile))
{
	var request = HttpWebRequest.Create(uri);
	var response = (HttpWebResponse)request.GetResponse();
//check the content type to assert that the file in the uri is an image
if (!response.ContentType.StartsWith(“image”))
{
	throw new FileFormatException(uri, String.Format(“Uri passed to ImageCacher does not return an image. Content is of type {0}.”, response.ContentType));
}
	//load the image from the stream
	var image = Image.FromStream(response.GetResponseStream());
	//save it
	image.Save(localFile);
}

Finally, return the path to the local file.

	return localFile;
}

Then in XAML, reference our converter using an xmlns tag and add our converter in the resources area.

<Window x:Class=”MyImageCacher.Window1″
	xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”
	xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”
	xmlns:mc=”http://schemas.openxmlformats.org/markup-compatibility/2006″
	xmlns:d=”http://schemas.microsoft.com/expression/blend/2008″
	xmlns:con=”clr-namespace:MyImageCacher.ImageCacher”>
<Window.Resources>
<con:ImageCacher x:Key=”imageCacher”/>

Then we add the Converter attribute to the Binding of our original Image control.

<Image Source=”{Binding ImageAddress, Converter={StaticResource imageCacher}}“/>

And its as simple as that. Each time an address is passed to the control, it will run it through the converter first. It will check to see if the image exists locally, and download it if it hasn’t been.

 A complete tutorial on this topic is found on http://simonhartcher.com/2009/12/12/image-caching-for-a-wpf-desktop-application/  and you can read  the formatted version of the same blog here
Categories: Prsnl References Tags: ,

Check The String is a valid Excel CellName or not using c#

April 3, 2011 Leave a comment

If you want to check the validity of name of cells you enterd
This function checks given string is a range addres or not
A1:A13- valid
A1:B12 valid
A1:A-not valid
A1:aa not valid
1A:b1 –not valid.

public bool checkcellRangeValidity(string inputrange)
{ bool valid = true;
string[] parts = inputrange.Split(':');
if (parts.Length == 2)
{
if (!((validcell(parts[0])) && (validcell(parts[1]))))
valid = false;
}
else //only one part or more parts on both sides of ':'
{
valid = false;
}
return valid;
}

Give string is a valid cell or not
A1: valid
A-not valid
1 not valid
1A not valid

public bool validcell(string inputcell)
{
bool valid = true;

int count = 0;
int digitscount = 0;
int lettercount = 0;

foreach (char c in inputcell)
{
if (char.IsDigit(c))
digitscount++;

if (char.IsLetter(c))
lettercount++;

if (!char.IsLetterOrDigit(c))
{
valid = false;
break;
}

if (count == 0) //means the very first char should be letter
{
count++;
if (!char.IsLetter(c))
{
valid = false;
break;
}

}
}

if (valid)
{ //chk only if the conditions are true till
if (!((digitscount >= 1) && (lettercount >= 1)))
{
// the cell is lagging either a no or a letter

valid = false;
}
}

return valid;
}

Categories: C# Programming Tips Tags:

Creating custom Excel Function wizard using VSTO Method2

April 3, 2011 Leave a comment

Word Document Of the tutorial-Introduction

Word Document Of the tutorial-Custom Function Wizard

Read Introduction Tutorial About VSTO

Read part1 Of the tutorial For First Aproach

Download FullCode From Here

In the steps discussed above the main logic was to write the formula on the selected cell.Instead of this we can do the same thing on this way
1. On click event of button in tab Shows the form.
2. Select the cell(Say A1)
3. Read value of the cell(say 5 , means value in the cell A1 is 5)
4. Calculate the factorial for this value (factorial of 5=1*2*3*4*5=120)
5. Write the result on the selected cell (120 instead of writing =fact(A1)).

Implementation Of Approach 2
Step1
Create a new form and design the form (similar to factorial form used on the first part of this tutorial)

Excel UDf using c# , FunctionWizard with Arguments Description, Excel Automation Addin c#, VSTo Excel Addin. Combine excel  Automation And Com Addin

Excel UDf using c# , FunctionWizard with Arguments Description, Excel Automation Addin c#, VSTo Excel Addin. Combine excel Automation And Com Addin


Add a new button on the ribbon and on the click event shows the newly designed form
Excel UDf using c# , FunctionWizard with Arguments Description, Excel Automation Addin c#, VSTo Excel Addin. Combine excel  Automation And Com Addin

Excel UDf using c# , FunctionWizard with Arguments Description, Excel Automation Addin c#, VSTo Excel Addin. Combine excel Automation And Com Addin



Step2

If we select some cells on excel we need to fill that cellname on the text box. But now we had the chance of opening either form1 or form2.
So the approach to overcome this isdeclare one static variable active formno on the ribbon class and assign it a unique no while showing each form.(say activeformno=1 for myfrm and activeformno=2 for myfrm2)


public static frmFact myfrm;
public static frmFactApproach2 myfrm2;
public static int activeformno;
And on the DoActions function check the active formno first and based on that we shows thecellname on the corresponding textbox

internal void DoActions(string cellValue)
{
try
{
if (activeformno == 1)
{
if (myfrm.ActiveControl.GetType() == typeof(System.Windows.Forms.TextBox))
myfrm.ActiveControl.Text = cellValue;
}
else if (activeformno == 2)
{
if (myfrm2.ActiveControl.GetType() == typeof(System.Windows.Forms.TextBox))
myfrm2.ActiveControl.Text = cellValue;
}
}
catch
{
}
}

Step3 read the value Of selected Cell
On the click event button on the form

string cellName = txtCellName.Text;

string value = readValueOfCell(cellName);

where the function to readvalue of selected cell is

private string readValueOfCell(string cellName)
{
string val = "";
Worksheet activeworksheet = Globals.TesstPAddin.GetActiveWorksheet();
Range FreqRange = activeworksheet.get_Range(cellName, Type.Missing);
val = Convert.ToString(FreqRange.Value);
return val;
}

Step4
Find the factorial based on this no

double factorial = getFactorial(Convert.ToDouble(value));

Step5
and display/write the value in selected cell

Worksheet currentSheet = Globals.TesstPAddin.GetActiveWorksheet();
currentSheet.Cells[Selectedrow, SelectedrCol] = factorial.ToString();
this.Close();

Disadvantage of this approach is if we are change the cell values the result willnot getting updated.But we need this kind of approach in some stages
Here we are discussing the way of reading only singe cell value .But there is a chance that user may selects a range of cells and we need to process this range of values.(

Excel UDf using c# , FunctionWizard with Arguments Description, Excel Automation Addin c#, VSTo Excel Addin. Combine excel  Automation And Com Addin

Excel UDf using c# , FunctionWizard with Arguments Description, Excel Automation Addin c#, VSTo Excel Addin. Combine excel Automation And Com Addin

In this case first we need to identify the cell address in text box is a single cell address(Then read the cell value)
Or a Range Of cell address like A1:A12 like in the last image.In this case we need to read the range of cells using the code.

Worksheet activeworksheet = Globals.TesstPAddin.GetActiveWorksheet();

Range FreqRange = activeworksheet.get_Range(cellnames, Type.Missing);
object[,] ExcelCellvalues = FreqRange.get_Value(System.Reflection.Missing.Value) as object[,];

The 2d array ExcelCellvalues contains all valuesin the selected range of cells.(Both null values,strings,doubles etc).So we process these values and store the needed values on to a List or another array like this

List NeededValues = new List();
if (ExcelCellvalues != null)
{
foreach (object obj in ExcelCellvalues)
{
if (obj != null)
{
/*Do the needed checks on data and store it if they are OK*/
NeededValues.Add(obj.ToString());

}

}
}

If you want to get the address of cell & value of selectd cells

Worksheet activeworksheet = Globals.TesstPAddin.GetActiveWorksheet();

Range FreqRange = activeworksheet.get_Range(cellnames, Type.Missing);

foreach (Range cell in FreqRange)
{

String cellAddress = cell.get_Address(false, false, Microsoft.Office.Interop.Excel.XlReferenceStyle.xlA1, false, false).ToString();
String value= cell.Value;

}

If you want to check the validity of name of cells you enterd
This function checks given string is a range addres or not
A1:A13- valid
A1:B12 valid
A1:A-not valid
A1:aa not valid
1A:b1 –not valid

Download FullCode From Here

Check A String is Valid Excel cell Name or not