Thursday, January 26, 2012

Using DataTable.select function for selecting from datatable

        DataTable dt = ((DataTable)ViewState["dtNewStudents"]);
        DataRow[] EditRows = dt.Select("Edit='1'");
        
        for(int i=0; i Less than EditRows.Count(); i++)
        {
            int index = dt.Rows.IndexOf(EditRows[i]);
            dt.Rows[index]["Edit"] = "0";
        }
        ViewState["dtNewStudents"] = dt;

Getting checkbox selected Gridview Rows in ASP.Net

Following is the line of code use to get the checked box selected rows of grid and getting the columns values from the gridview source DataTable.
DataTable dtGetStTable = (DataTable)ViewState["dtNewStudents"];

//Looping throgh Grid and deleting row after finding the checked row
for (int i = dtGetStTable.Rows.Count - 1; i > -1; i--)
{
    GridViewRow row = GridView1.Rows[i];
    bool isChecked = ((CheckBox)row.FindControl("CheckBox1")).Checked;

    if (isChecked)
    {
        try
        {
            string RollNo = dtGetStTable.Rows[i]["RollNo"].ToString();
            string Class = dtGetStTable.Rows[i]["Class"].ToString();
            string Division = dtGetStTable.Rows[i]["Division"].ToString();
            //Deleting the Reocrd from DataBase
            TotalRecordDeleted += objSRE.DeleteTheSelectedRecord(RollNo, Class, Division);

            dtGetStTable.Rows[i].Delete();
            dtGetStTable.AcceptChanges();
        }
        catch (Exception ex)
        {

            //throw;
        }
    }
}

Wednesday, January 25, 2012

Finding Duplicate Rows in DataTable using Linq

var duplicates = dt.AsEnumerable()
                .GroupBy(r => new { a = r[0], b = r[1] })
                .Where(gr => gr.Count() > 1);
lbMsg.Text = "Duplicate Record found for Rows: " + String.Join(", ", duplicates.Select(dupl => dupl.Key));


//End

Finding Duplicate Records on the basis of any Column in Datatable using Linq

Here is if your DatTable
DataTable dt = new DataTable();
dt.Columns.Add();
dt.Columns.Add();
dt.Columns.Add();
dt.Rows.Add(1, "Test1", "Sample1");
dt.Rows.Add(2, "Test2", "Sample2");
dt.Rows.Add(3, "Test3", "Sample3");
dt.Rows.Add(4, "Test4", "Sample4");
dt.Rows.Add(5, "Test5", "Sample5");

var duplicates = dt.AsEnumerable().GroupBy(r => r[0]).Where(gr => gr.Count() > 1).ToList();
Console.WriteLine("Duplicate found: {0}", duplicates.Any());

dt.Rows.Add(1, "Test6", "Sample6");  // Duplicate on 1
dt.Rows.Add(1, "Test6", "Sample6");  // Duplicate on 1
dt.Rows.Add(3, "Test6", "Sample6");  // Duplicate on 3
dt.Rows.Add(5, "Test6", "Sample6");  // Duplicate on 5

duplicates = dt.AsEnumerable().GroupBy(r => r[0]).Where(gr => gr.Count() > 1).ToList();
if (duplicates.Any())
    Console.WriteLine("Duplicate found for Classes: {0}", String.Join(", ", duplicates.Select(dupl => dupl.Key)));

Console.ReadLine();

Handling Button Click Event in ViewModel using MVVM structure of Silverlight

1. Write Xaml as follows
<Button Command="{Binding SearchCommand}" Content="Search" 
Height="20" HorizontalAlignment="Right" 
Margin="0,16,19,0" TabIndex="14" VerticalAlignment="Top" 
Width="75" Grid.Column="2" />
2. Write in viewModel as follows
//This is command against when search button will be pressed
 public RelayCommand SearchCommand
 {
    get
    {
      //GetDatais a method for your action on click event
      return new RelayCommand(GetData);
    }
 }
3. You Method for for on button click
protected void GetData()
{
     //Your work
     //
     //
}

Tuesday, January 24, 2012

Using Busy indicator of Master Page from the Child Page in MVVM structure of Silver light

You can call the busy indicator of silver light master page from the child form in the following way..

1. Register the Message in constructor of MasterPage View Model

public vmMasterPage()
{
   //Your other work
   Messenger.Default.Register(this, "GetBusy", getBusy);
}

2. Define the function in MasterPage view Model
public void getBusy(string msg)
        {
            //MainPageBusyIndicator is bool property to bind with busyindcator control on masterPage
            //
            if (msg == "Busy")
            {
                MainPageBusyIndicator = true;
            }
            else
            {
                MainPageBusyIndicator = false; 
            }
        }

3. Call This Message from your Child form as follows
Messenger.Default.Send("Busy", "GetBusy");



Thursday, January 19, 2012

Using Messanger for calling View method from ViewModel in MVVM structure of Silver light

Write in View Constructor

Messenger.Default.Register(this, "DoFocus", doFocus);

Write method in view that need to be call from view model
public void doFocus(string msg)
        {
            if (msg == "focus")
            {
                System.Windows.Browser.HtmlPage.Plugin.Focus();
                this.txtSalesOrderNo.Focus();
            }
        }

Now you can call the above method from viewmodel as below

Messenger.Default.Send("focus", "DoFocus");

How to set textbox focus in silverlight using MVVM

The question has been asked a couple of times, unfortunately the answers only apply to WPF. Anyone know how to accomplish this in silverlight? Basically I need to focus on a certain textbox from code.

Following class is required in view model

public class FocusBehavior : Behavior
    {

        protected override void OnAttached()
        {
            AssociatedObject.GotFocus += (sender, args) => IsFocused = true;
            AssociatedObject.LostFocus += (sender, a) => IsFocused = false;
            AssociatedObject.Loaded += (o, a) => { if (HasInitialFocus || IsFocused) AssociatedObject.Focus(); };

            base.OnAttached();
        }

        public static readonly DependencyProperty IsFocusedProperty =
            DependencyProperty.Register(
                "IsFocused",
                typeof(bool),
                typeof(FocusBehavior),
                new PropertyMetadata(false, (d, e) => { if ((bool)e.NewValue) ((FocusBehavior)d).AssociatedObject.Focus(); }));

        public bool IsFocused
        {
            get { return (bool)GetValue(IsFocusedProperty); }
            set { SetValue(IsFocusedProperty, value); }
        }

        public static readonly DependencyProperty HasInitialFocusProperty =
            DependencyProperty.Register(
                "HasInitialFocus",
                typeof(bool),
                typeof(FocusBehavior),
                new PropertyMetadata(false, null));

        public bool HasInitialFocus
        {
            get { return (bool)GetValue(HasInitialFocusProperty); }
            set { SetValue(HasInitialFocusProperty, value); }
        }
    }

Add name space reference in Xaml file like as
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" 

and give initial value and binding value like as below
 <TextBlock Height="20" HorizontalAlignment="Left" Margin="10,16,0,0" Text="Sales Order No" TextWrapping="Wrap" VerticalAlignment="Top" Width="91" />
        <TextBox Height="22"  HorizontalAlignment="Left" Margin="115,13,0,0" MaxLength="20" Name="txtSalesOrderNo" TabIndex="0"  TextWrapping="Wrap" VerticalAlignment="Top" Width="165" Text="{Binding Path=SaleOrderNo, Mode=TwoWay}" >
            <i:Interaction.Behaviors>
                <Local1:FocusBehavior HasInitialFocus="False" IsFocused="{Binding SaleOrderFocus, Mode=TwoWay}"/>
            </i:Interaction.Behaviors>


        </TextBox> 

How to set focus to a text box in silver light application

In Microsoft silver light you can set focus to the text in following way.

private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            if (App.Current.IsRunningOutOfBrowser)
            {
                txtSalesOrderNo.Focus(); 
            }
            else
            {
                System.Windows.Browser.HtmlPage.Plugin.Focus();
                txtSalesOrderNo.Focus(); 
            }

        }

Wednesday, January 18, 2012

How to use systax highlighter in your blog?


Introduction



I've been using Blogger as my blogging engine for a couple of weeks. I've been quite impressed at how easy it makes it to update your blogs look and feel and how free you are with the HTML and semantic layout of the pages.

One thing that seemed to be missing was allowing developers to copy and paste code into their blogs and allow other users to copy and paste the code from the blog into their own code.



Using SyntaxHighlighter Javascript Library

So in my search to find something better i came across this post which uses syntax highlighte


Adding Syntax Highlighter to Blogger Template



  • Copy the following code
<link href='http://alexgorbatchev.com/pub/sh/current/styles/shCore.css' rel='stylesheet' type='text/css'/>  
<link href='http://alexgorbatchev.com/pub/sh/current/styles/shThemeDefault.css' rel='stylesheet' type='text/css'/>  
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shCore.js' type='text/javascript'></script>  <script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushCpp.js' type='text/javascript'></script>  
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushCSharp.js' type='text/javascript'></script>  
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushCss.js' type='text/javascript'></script>  
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushJava.js' type='text/javascript'></script>  
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushJScript.js' type='text/javascript'></script>  
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPhp.js' type='text/javascript'></script>  
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPython.js' type='text/javascript'></script>  
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushRuby.js' type='text/javascript'></script>  
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushSql.js' type='text/javascript'></script>  
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushVb.js' type='text/javascript'></script> 
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushXml.js' type='text/javascript'></script>  
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPerl.js' type='text/javascript'></script>  
<script language='javascript'>  SyntaxHighlighter.config.bloggerMode = true; SyntaxHighlighter.config.clipboardSwf = 'http://alexgorbatchev.com/pub/sh/current/scripts/clipboard.swf'; SyntaxHighlighter.all(); </script>

  • paste it into your Blogger Template just above the </head> tag
  • Save the template
  • Then you can start creating code blocks in your existing or new Blog entries.
  • There are 2 ways to add a code block using syntaxhighlighter

<

Method 1: Using the script Tag

]]>



becomes:







Method 2: Using the pre Tag





becomes:



// Comment
public class Testing {
    public Testing() {
    }
 
    public void Method() {
        /* Another Comment
           on multiple lines */
        int x = 9;
    }
}


Code Containing Less that or Greater than

One person noticed that if you try and publish any code with < or > in it, you'll need to HTML Encode the code before adding it to the blog post using something like this. Then you'll be able to publish code with generic's such as the following:



static Dictionary<int, List<Delegate>> _delegate = new Dictionary<int, List<Delegate>>();


Conclusion

I have to say i'm pretty impressed. There are a couple of things you have to watch out for:

  • The java script uses the <code> Tag. So as lots of blogger templates have styles for this tag you have to remove any styles before it looks like the above.
  • If you paste in HTML or XML with <Tags>. You'll need to HTML encode them. Which is a bit of a shame, as i was hoping the CDATA would help get around that problem. Maybe in the next version.

How to set column alignment in silverlight Data Grid?

In Xaml write as below.
<sdk:DataGridTextColumn Binding="{Binding Path=PriceAmt}" CanUserReorder="True" CanUserResize="True" CanUserSort="True" Width="Auto" Header="Price Amount" IsReadOnly="True">
       <sdk:DataGridTextColumn.CellStyle>
         <Style TargetType="sdk:DataGridCell">
            <Style.Setters>
              <Setter Property="HorizontalAlignment" Value="Right"></Setter>
                 <Setter Property="FontWeight" Value="Bold" />
                     </Style.Setters>
                        </Style>
                        </sdk:DataGridTextColumn.CellStyle>
                        
</sdk:DataGridTextColumn>