Multi-level grouping using Linq

Referenced from Here
I have a list of records with the following structure: (Simplified example!)

class Rate
{
    string Code;
    double InterestFrom;
    double InterestTo;
    double IncomeFrom;
    double IncomeTo;
    double Value;
}

I have a List defined. I need to convert this list to the following simplified structure

class RateList
{
   List<Code> code;
}
class Code
{
    string code;
    List<Interest> interest;
}
class Interest
{
    double InterestFrom;
    double InterestTo;
    List<Income> income;
}
class Income
{
    double IncomeFrom;
    double IncomeTo;
    double Value;
}

And I would like to do this with a single LINQ query. I can work out other solutions but the challenge is to do it within one LINQ statement. Basically, the top-level group is grouped by code. The next level by the values InterestFrom and InterestTo and the lowest level is a list of IncomeFrom, IncomeTo and Value.

Solution:

var rateList = new RateList
               {
                   code = (from r in rates
                           group r by r.Code into g
                           select new Code
                           {
                               code = g.Key,
                               interest = (from i in g
                                           group i by new {i.InterestFrom, i.InterestTo} into g2
                                           select new Interest
                                           {
                                               InterestFrom = g2.Key.InterestFrom,
                                               InterestTo = g2.Key.InterestTo,
                                               income = (from inc in g2
                                                         select new Income
                                                         {
                                                             IncomeFrom = inc.IncomeFrom,
                                                             IncomeTo = inc.IncomeTo,
                                                             Value = inc.Value
                                                         }).ToList()
                                           }).ToList()
                           }).ToList()
               };

WPF or silverlight XAML element collision detection

WPF or silverlight XAML element collision detection.

private bool CheckCollision(FrameworkElement ctl1,FrameworkElement ctl2)
        {
            bool retval = false;
            Point ptTopLeft = new Point(Convert.ToDouble(ctl1.GetValue(Canvas.LeftProperty)), Convert.ToDouble(ctl1.GetValue(Canvas.TopProperty)));
            Point ptBottomRight = new Point(Convert.ToDouble(ctl1.GetValue(Canvas.LeftProperty)) + ctl1.Width, Convert.ToDouble(ctl1.GetValue(Canvas.TopProperty)) + ctl1.Height);
            Rect r1 = new Rect(ptTopLeft, ptBottomRight);

            //System.Diagnostics.Debug.WriteLine("+++x:" + ptTopLeft.X.ToString() + " Y " + ptTopLeft.Y.ToString() + " " + ptBottomRight.X.ToString() + " " + ptBottomRight.Y.ToString());

            Point ptTopLeft2 = new Point(Convert.ToDouble(ctl2.GetValue(Canvas.LeftProperty)), Convert.ToDouble(ctl2.GetValue(Canvas.TopProperty)));
            Point ptBottomRight2 = new Point(Convert.ToDouble(ctl2.GetValue(Canvas.LeftProperty)) + ctl2.Width, Convert.ToDouble(ctl2.GetValue(Canvas.TopProperty)) + ctl2.Height);
            Rect r2 = new Rect(ptTopLeft2, ptBottomRight2);

            r1.Intersect(r2);
            if (!r1.IsEmpty)
            {
                retval = true;
            }
            return retval;
        }

Creating Transaction by using System.Transactionscope

/* Using System.Transaction object */
            string cn = ConfigurationManager.ConnectionStrings["universityConnectionString1"].ToString();
            using (TransactionScope ts = new TransactionScope())
            {
                using (SqlConnection cns = new SqlConnection())
                {
                    cns.ConnectionString = cn;
                    cns.Open();
                    using (SqlCommand cmd = cns.CreateCommand())
                    {
                        try
                        {
                            cmd.CommandText = "Insert into creditAccount(Amount)values(" + int.Parse(txtcreditamt.Text) + ")";
                            cmd.ExecuteScalar();
                            int x = int.Parse(txtdebitamt.Text);
                            cmd.CommandText = "Insert into debitAccount(Amount)values(" + int.Parse(txtcreditamt.Text) + ")";
                            cmd.ExecuteScalar();
                            ts.Complete();
                            ts.Dispose();
                        }
                        catch (Exception)
                        {
                        }
                        
                    }
                }
            }

Creating a transaction by using ADO.NET dbTransaction object

using (SqlConnection cn = new SqlConnection())
            {

                cn.ConnectionString = ConfigurationManager.ConnectionStrings["universityConnectionString1"].ToString();

                cn.Open();

                using (SqlTransaction tran = cn.BeginTransaction())
                {
                    try
                    {
                        using (SqlCommand cmd = cn.CreateCommand())
                        {
                            cmd.Transaction = tran;
                            cmd.CommandText = "Insert into creditAccount(Amount)values(" + int.Parse(txtcreditamt.Text) + ")";
                            cmd.ExecuteScalar();
                            int x = int.Parse(txtdebitamt.Text);
                            cmd.CommandText = "Insert into debitAccount(Amount)values(" + int.Parse(txtcreditamt.Text) + ")";
                            cmd.ExecuteScalar();
                        }
                        tran.Commit();
                    }
                    catch (Exception)
                    {
                        tran.Rollback();
                    }
                }
            }

C# datetime Find Second Monday and Find Fourth Monday

Suppose you have some scheduled job which must not run on Second Monday and Fourth Monday of the month, the following code spinet will be helpful to identify the date-


private int GetDateForWeekDay(DayOfWeek DesiredDay, int Occurrence, int Month, int Year)
{

DateTime dtSat = new DateTime(Year, Month, 1);
int j = 0;
if (Convert.ToInt32(DesiredDay) - Convert.ToInt32(dtSat.DayOfWeek) >= 0)
j = Convert.ToInt32(DesiredDay) - Convert.ToInt32(dtSat.DayOfWeek) + 1;
else
j = (7 - Convert.ToInt32(dtSat.DayOfWeek)) + (Convert.ToInt32(DesiredDay) + 1);

return j + (Occurrence - 1) * 7;

}

Access (Web Service Enhancements 3.0 ) secure web service using C# ASP.NET

Access (Web Service Enhancements 3.0 ) secure web service using C# ASP.NET

You might get following errors if you try to use wsewsdl3.exe to generate proxy class for a secure web service.

  • “Unable to import biniding ‘xxxxx’ from namespace…”
  • “unable to import Operations:GetWeather”
  • “Found more than one parameter on method “GetWeather” while multiple parameters are not supported.”

What you need to do is following –

  • Install WSE 3
  • Reference your secure web service in Visual Studio.
  • Add a reference to Microsoft.Web.Services3 dll into your client project.
  • Open References.cs ( under web reference) and add following using statement at top.
  • using Microsoft.Web.Services3;
  • After  that inherit your web service proxy partial class from Microsoft.Web.Services3.WebServicesClientProtocol

Amazservice.WeatherWS pws = new Amazservice.WeatherWS();
Microsoft.Web.Services3.Security.Tokens.UsernameToken token = new Microsoft.Web.Services3.Security.Tokens.UsernameToken("username", "password", Microsoft.Web.Services3.Security.Tokens.PasswordOption.SendPlainText);
SoapContext reqContext = pws.RequestSoapContext
reqContext.Security.Tokens.Add(token);
reqContext.Security.Timestamp.TtlInSeconds = 60;
string s = pws.GetWeatherForZip("382019");

C#/Javascript – Shareponit 2010 List Update using Web Service

C# – Shareponit 2010 List Update using Web Service

public static void LockDailyEntry(int rowID)
 {
 spws.Lists oSplistWs = new spws.Lists();
 /*Authenticate the current user by passing their default
 credentials to the Web service from the system credential cache.*/
 oSplistWs.Credentials = System.Net.CredentialCache.DefaultCredentials;

 /*Get Name attribute values (GUIDs) for list and view. */
 System.Xml.XmlNode ndListView = oSplistWs.GetListAndView("UnlockDailyEntry", "");
 string strListID = ndListView.ChildNodes[0].Attributes["Name"].Value;
 string strViewID = ndListView.ChildNodes[1].Attributes["Name"].Value;

 /*Create an XmlDocument object and construct a Batch element and its
 attributes. Note that an empty ViewName parameter causes the method to use the default view. */
 System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
 System.Xml.XmlElement batchElement = doc.CreateElement("Batch");
 batchElement.SetAttribute("OnError", "Continue");
 batchElement.SetAttribute("ListVersion", "1");
 batchElement.SetAttribute("ViewName", strViewID);

 /*Specify methods for the batch post using CAML. To update or delete,
 specify the ID of the item, and to update or add, specify
 the value to place in the specified column.*/
 batchElement.InnerXml = "<Method ID='1' Cmd='Update'>" +
 "<Field Name='ID'>" + rowID + "</Field>" +
 "<Field Name='Status'>Lock</Field>" +
 "</Method>";

 /*Update list items. This example uses the list GUID, which is recommended,
 but the list display name will also work.*/
 oSplistWs.UpdateListItems(strListID, batchElement);
 }

Javascript – Shareponit 2010 List Update using Web Service

function SaveListItem() {
 var soapRequest = '<?xml version="1.0" encoding="utf-8"?>' +
 '<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">' +
 ' <soap12:Body>' +
 ' <UpdateListItems xmlns="http://schemas.microsoft.com/sharepoint/soap/">' +
 ' <listName>UnlockDailyEntry</listName>' +
 ' <updates>' +
 '<Batch OnError="Continue">' +
 ' <Method ID="1" Cmd="Insert">' +
 ' <Field Name="Status">Lock</Field>' +
 ' </Method>' +
 '</Batch>' +
 ' </updates>' +
 ' </UpdateListItems>' +
 ' </soap12:Body>' +
 '</soap12:Envelope>';

 xmlHttp = new XMLHttpRequest();
 xmlHttp.open('post', 'http://spserver:18000/_vti_bin/lists.asmx', true);
 xmlHttp.setRequestHeader('Content-Type', 'application/soap+xml; charset=utf-8');

 xmlHttp.send(soapRequest);
 }

Linq to SQL – table join with multiple where clause


public IQueryable<CustomerActivity> GetCustomerActivityResult(string sUser,DateTime ReportDate)
 {
 CustomerDataClassesDataContext db = new CustomerDataClassesDataContext();

 var customeractivity = from ca in db.CustomerActivities
 join acts in db.ActivitySummaries
 on ca.ActivitySummaryID equals acts.ActivitySummaryID
 where acts.Name == sUser && acts.Date == ReportDate
 select ca;
 return customeractivity;
 }

List all dates between start and end date

The following code returns List<string> of dates between 2 dates.

public List<SearchResult> GetSearchResult(string sUser,DateTime dtStartDate, DateTime dtEndDate)
        {
            List<SearchResult> searchresult = new List<SearchResult>();
            
            while (dtStartDate.AddDays(1) <= dtEndDate)
            {
                dtStartDate = dtStartDate.AddDays(1);
                searchresult.Add(new SearchResult { Date = String.Format("{0:dd-MMM-yy}", dtStartDate) , Status = "New" });
            }

            return searchresult;
        }