Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Tuesday, July 1, 2014

linq max count of list


                var max = data.Max(p => p.SubList.Count);
                var maxData = data.FirstOrDefault(p => p.SubList.Count == max);

Friday, November 8, 2013

c# Get Executing Method Name

String method = String.Format("{0}.{1}", 
                MethodBase.GetCurrentMethod().DeclaringType.FullName, 
                MethodBase.GetCurrentMethod().Name); 

Monday, October 28, 2013

C# Create DbGeography Point in Entity Framework

public DbGeography GeoPoint(Double latitude, Double longitude)
{
//Assembly Microsoft.SqlServer.Types.dll, v11.0.0.0
       SqlGeography sqlGeo = SqlGeography.Point(latitude, longitude, 4326);

       //Assembly System.Data.Entity.dll, v4.0.0.0
       DbGeography dbGeom = DbGeography.FromText(sqlGeo.ToString(), 4326);

       return dbGeom;

}

Sunday, October 27, 2013

c# Type from String

Type type = Type.GetType("Namespace.MyClass, MyAssembly");

Sunday, September 22, 2013

Cross-thread operation not valid: Control '' accessed from a thread other than the thread it was created on.

delegate void SetMaximumProgressCallbackDelegate(Int32 max);
        public void SetMaximumProgressCallback(Int32 max)
        {
            if (this.progressBar1.InvokeRequired)
            {
                SetMaximumProgressCallbackDelegate d = new SetMaximumProgressCallbackDelegate(SetMaximumProgressCallback);
                this.Invoke(d, new Object[] { max });
            }
            else
            {
                this.progressBar1.Maximum = max;
            }
        }

Thursday, September 19, 2013

Microsoft Dynamics CRM 2011 Create Reports via Fetch XML by BIDS

Great Post
http://blog.rahulsharma.in/2011/04/microsoft-dynamics-crm-2011-fetch-xml.html

Below Text copied from Above address.

Microsoft Dynamics CRM 2011 comes in two flavors, online and on-premises. Fetch-Xml method of report development can be used to create custom SSRS reports for both the types of CRM deployments. 

To get started with the development, make sure you have installed the below two pieces of software: 

- SQL Server 2008 R2 Business Intelligence Development Studio (BIDS). Installing BIDS will also install Visual Studio 2008 cut down version to develop SSRS reports.

- Microsoft Dynamics CRM 2011 Fetch Authoring Extension for BIDS. This will give you ability to add Microsoft Dynamics CRM Fetch data source in your SSRS report. To configure this data source for your report you need to provide CRM Server URL, Organisation Unique Name and Windows Live Credentials or Domain\LoginId.

By installing and configuring the Fetch XML data source, creating a report is as simple as creating a normal SSRS report except rather than choosing Microsoft SQL Server as your data source you chose Microsoft Dynamics CRM Fetch as your report data source. 

These CRM reports are regular RDLs with Fetch XML as the data query language and the data provider is MSCRMFETCH. 

There are two ways to create custom CRM reports:

     First option is you create a basic report through CRM Report Wizard and then download RDL to modify it in BIDS. The Report wizard creates fetch-xml based reports and this can be a good starting point to learn or start developing your fetch-xml based reports.

     Second, you can create fetch-xml report from scratch in BIDS.

In this article, we will see how to create fetch-xml based reports from the scratch in BIDS.

Create Fetch-XML Report:

  • Launch Business Intelligence Development Studio.
  • Create a new Report Server Project.

  • In Solution Explorer, right-click Reports folder, and click ‘Add New Report’. A Report Wizard will open up. Click next on the first introduction page.

  • Note: To edit exiting custom report created through CRM Report Wizard, select "Add > Existing Item..." above instead of "Add New Report". You can download your custom report from CRM, by selecting your report then Edit > Download Report.

  • Select the Data Source. Choose a name for your data source, on the Type drop down, select Microsoft Dynamics CRM Fetch as your data provider and provide the connection string of your CRM instance.

    Connection string should be in the following format:
    CRM Server URL;[Org Unique Name];[Home Realm URL]

    If Organization Name is not provided and user belongs to multiple orgs, then the first org returned by CRM is used. To get Org Name, go to CRM > Settings > Customizations > Developer Resources.


    Home Realm URL is needed when we use Federation for identity management, and url is the identity provider's url.

    Also provide report credentials. If creating report for CRM online then provide Windows Live ID or if on-premises then provide domain\LoginID
    Click next.
  • Design the Query. Define fetch-xml query that will retrieve the data for your report. Simple and fast way to create fetch-xml is by using CRM itself.
    • Navigate to CRM Advanced Find, and specify a query.
    • You can pick the individual columns to be displayed on your report by selecting ‘Edit Columns’.
    • After you are satisfied with your query, click ‘Download Fetch XML’.
    • Save the fetch-xml to your local drive.

     In the Query string textbox, copy and paste the content of the fetch-xml you saved above. You can also preview your data on the query designer.

    Click next, select other reporting options on other pages of the wizard and you are done. :)

  • Now, upload your RDL on the CRM server in the appropriate categories and your report is ready to be displayed in CRM.
So, we have just created a custom fetch-xml report.

Overview of Fetch-XML syntax:
Let's have a quick look how you can define and use fetch-xml as your report query.
<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="true">
    <entity name="invoice">
        <all-attributes/>
    </entity>
</fetch>

In the above xml, <entity> tag defines CRM entity you want to query and <all-attributes> tag defines that you want to fetch all columns. In case you want to fetch selected columns use below...
<entity name="invoice">
    <attribute name="name" alias="InvoiceName" />
    <attribute name="customerid" />
    <attribute name="totalamount" />
    <attribute name="invoiceid" />
</entity>

"alias" attribute is to define a different column name.

Define sort order: Use <order> tag.
<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="true">
  <entity name="invoice">
    <attribute name="name" />
    <attribute name="customerid" />
    <attribute name="totalamount" />
    <attribute name="invoiceid" />
    <order attribute="name" descending="false" />
  </entity>
</fetch>

Define conditions or filters: Use <filter> tag.
<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="true">
  <entity name="invoice">
    <attribute name="name" />
    <attribute name="customerid" />
    <attribute name="totalamount" />
    <attribute name="invoiceid" />
    <order attribute="name" descending="false" />
    <filter type="and">
      <condition attribute="invoicenumber" operator="eq" value="SomeValue" />
    </filter>
  </entity>
</fetch>

Another example could be,
<filter type="and">
     <condition attribute="invoicenumber" operator="in">
       <value>SomeValue</value>
       <value>AnotherValue</value>
     </condition>
</filter>

Define entity relationships: Use <link-entity> tag.
<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="true">
  <entity name="invoice">
    <attribute name="name" />
    <attribute name="customerid" />
    <attribute name="totalamount" />
    <attribute name="invoiceid" />
    <order attribute="name" descending="false" />
    <filter type="and">
      <condition attribute="invoicenumber" operator="eq" value="SomeValue" />
    </filter>
    <link-entity name="psa_project" from="psa_projectid" to="psa_project" alias="Project">
        <attribute name="psa_account" />
        <attribute name="psa_accountaddress" />
        <attribute name="psa_principalcontact" />
    </link-entity>
  </entity>
</fetch>

Define parameters: You can also define parameters on the fetch-xml query to take user input.
<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="true">
  <entity name="invoice">
    <attribute name="name" />
    <attribute name="customerid" />
    <attribute name="totalamount" />
    <attribute name="invoiceid" />
    <order attribute="name" descending="false" />
    <filter type="and">
      <condition attribute="invoicenumber" operator="eq" value="@pInvoiceId" />
    </filter>
  </entity>
</fetch>

Above xml will create a query parameter, pInvoiceId. Parameter names need to start with @ sign. Also adding the parameter in the fetch query also adds the QueryParameter and ReportParameter nodes in the RDL automatically.


Define Pre-Filtering: This is a way to filter your report data using CRM Advance Find Functionality. Pre-Filtering actually makes your report context sensitive.

To get it working, you need to add two attributes to the <entity> tag in your fetch-xml.
<entity name="invoice" enableprefiltering="true" prefilterparametername="InvoiceFilter">

"enableprefiltering", will make the particular entity context sensitive and "prefilterparametername" is optional attribute to provide a name to your pre-filtering parameter. Pre-Filtering adds a Query &  Report Parameter to your report, if "prefilterparametername" not provided then the parameter name would be CRM_<EntityName>.

Wednesday, September 11, 2013

VSTO - Get OleObject and Set PrintObject as False

ws is ActiveSheet
Shape picture = ws.Shapes.Item("Picture 1");
picture.Select(Type.Missing);
picture.OLEFormat.Object.PrintObject = false;

Sunday, September 8, 2013

Copy Transparent Bitmap to Clipboard with C#

delegate void CopyClipboardCallbackDelegate(Bitmap image);
        public void CopyClipboardCallback(Bitmap image)
        {
            if (this.InvokeRequired)
            {
                CopyClipboardCallbackDelegate d = new CopyClipboardCallbackDelegate(CopyClipboardCallback);
                this.Invoke(d, image);
            }
            else
            {
                using (MemoryStream stream = new MemoryStream())
                {
                    image.Save(stream, ImageFormat.Png);
                    var data = new DataObject("PNG", stream);
                    Clipboard.Clear();
                    Clipboard.SetDataObject(data, true);
                }
            }
        }

Tuesday, February 26, 2013

C# bitwise Operations with enum


public enum UserTypes: int
    {
        Admin = 1,
        Moderator = 2,
        Member = 4,
        None = 8
    }

    class Program
    {
        static void Main(string[] args)
        {
            var userRoles = UserTypes.Admin | UserTypes.Member | UserTypes.Moderator;

            Console.WriteLine("value:" + (Int32)userRoles);
            if(userRoles.HasFlag(UserTypes.Member))
                Console.WriteLine("member");
            if (userRoles.HasFlag(UserTypes.Admin))
                Console.WriteLine("admin");
            if (userRoles.HasFlag(UserTypes.Moderator))
                Console.WriteLine("moderator");
            if (userRoles.HasFlag(UserTypes.None))
                Console.WriteLine("none");

            Console.Read();

        }
    }

Thursday, February 7, 2013

Enable-Migrations Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.


  1. if you are using Code First
  2. if your DBContext class is in another library and it still references the older v4.1 DLL, you will get the the error. Just check to make sure everything references the same version. Check your all dll's that reference the same entityframework.dll 5.0.0

Wednesday, January 16, 2013

An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.


You must execute the query before detach it.

//this gets error

public IEnumerable<USER_CONTACT> SelectAll(Guid userId)
        {
            //create query
            var query = from q in unitOfWork.UserContacts
                        select q;

            foreach (var item in query)
            {
                unitOfWork.UserContacts.Detach(item);
            }
            return query;
        }


//no problem
public IEnumerable<USER_CONTACT> SelectAll(Guid userId)
        {
            //create query
            var query = from q in unitOfWork.UserContacts
                        select q;

            var result = query.ToList();
            foreach (var item in result)
            {
                unitOfWork.UserContacts.Detach(item);
            }

            return result;
        }

Monday, November 12, 2012

VSTO - Performance - Set 1000000 value within 2 seconds



        public void RunTest(String columnName)
        {
            var start = DateTime.Now;

            var sheet = Globals.ThisWorkbook.Sheets.getByName("Sheet3");

            //set data area
            Excel.Range dataArea = sheet.Range(String.Format("{0}1:{0}1000000", columnName));
            //prepare dummy data
            Object[,] data = new Object[1000000,1];
            for (int i = 0; i < 1000000; i++)
            {
                data[i, 0] = i;
            }
            Debug.WriteLine("Data ready!!!");
            // set data
            dataArea.Value = data;

            var duration = (DateTime.Now - start).TotalMilliseconds;
            Debug.WriteLine(duration.ToString());
            MessageBox.Show(duration.ToString());
        }

telerik grid masked column not working


this is the dummy solution.



RadMaskedTextBox dummyTextBox = new RadMaskedTextBox(); 
protected void ClientRadGrid_ItemDataBound(object sender, GridItemEventArgs e) 
{ 
   if (e.Item is GridDataItem) 
   { 
        GridDataItem item = (GridDataItem)e.Item; 
        dummyTextBox.Mask="+## (###) ### ## ##"; 
        dummyTextBox.Text = item["Phone"].Text; 
        item["Phone"].Text = dummyTextBox.TextWithPromptAndLiterals; 
    } 
}

Monday, August 27, 2012

subdomain HttpContext.Current.Server.MapPath Problem

const String folderName = "App_Data/Database"; not works 
const String folderName = "~/App_Data/Database"; works

Monday, August 13, 2012

unitycontainer LoadConfiguration not found




Assembly Microsoft.Practices.Unity.Configuration.dll, v2.0.50727

using Microsoft.Practices.Unity.Configuration;

var unityContainer = new UnityContainer();
unityContainer.LoadConfiguration();

LoadConfiguration is a extension method. you have to use using directive

Saturday, August 11, 2012

Create Image Thumb Name


if file name contains in path, no problem.


 String CreateThumbName(String fullPath)

        {
            //get file name
            var onlyFilename = System.IO.Path.GetFileNameWithoutExtension(fullPath);
            //name with extension
            var nameWithExt = System.IO.Path.GetFileName(fullPath);
            //just extension
            var ext = System.IO.Path.GetExtension(fullPath);
            //create thumb name
            var thumbName = String.Format("{0}_thumb{1}", onlyFilename, ext);
            //replace file name with thumb name
            var result = fullPath.Replace(nameWithExt, thumbName);
           
            //return result
            return result;
        }


Sample

var fullPath = "c:\windows\MyFolder\my.jpg"
var result = CreateThumbName(fullPath);

Console.WriteLine(result);

Output

c:\windows\MyFolder\my_thumb.jpg



Asp.net Convert AbsolutePath to RelativePath


I wrote step by step to be clear. use this method as extension could be nice.
 String ToRelative(String absolute)
        {
            //getting root portion
            var root = HttpContext.Current.Server.MapPath("/");
            //removing root portion
            var result = absolute.Replace(root, "");
            //replace backslash-spash
            result = result.Replace("\\", "/");
            //finalize the path adding first char as slash
            result = String.Format("/{0}", result);
            //good to go
            return result;
        }

Friday, August 10, 2012

linq select in query


ToSearchList extension creates list of strings, permutation of given text
Ex:  var list = "tuğbay".ToSearchList();
list contains tuğbay, tüğbay, tugbay, tügbay


if (!String.IsNullOrEmpty(searchText))
            {
                var searchList = searchText.ToSearchList();
                query = from p in query
                             from sl in searchList
                        where p.User.name.ToLower().Contains(sl)
                              || p.User.surname.ToLower().Contains(sl)
                              || p.User.email.ToLower().Contains(sl)
                        select p;
            }

Sunday, July 22, 2012

linq group by count


public IEnumerable DrillCountInTrainings()
        {
            var query = from t in context.TRAININGS
                        join td in context.TRAINING_DRILLS on t.training_id equals td.training_id
                        join d in context.DRILLS on td.drill_id equals d.drill_id
                        group t by new { t.name, t.date, t.training_id } into grp
                        orderby grp.Key.date descending
                        select new SuccessReportResultDTO
                        {
                            Name = grp.Key.name,
                            Value = grp.Count(),
                            IdealValue = 0,
                            MeanValue = 0
                        };

            return query;
        }

Wednesday, July 18, 2012

AutoMapper Convert Classes Sample


public Team ToDomain(TEAM team)
        {
            if (team == null) return new MissingTeam();

            Mapper.CreateMap()
                .ForMember(p => p.CountryId, o => o.MapFrom(p => p.country_id))
                .ForMember(p => p.CreateDate, o => o.MapFrom(p => p.create_date))
                .ForMember(p => p.CreateUserId, o => o.MapFrom(p => p.create_user_id))
                .ForMember(p => p.CurrentLeagueId, o => o.MapFrom(p => p.current_league_id))
                .ForMember(p => p.FoundDate, o => o.MapFrom(p => p.found_date))
                .ForMember(p => p.Name, o => o.MapFrom(p => p.name))
                .ForMember(p => p.TeamId, o => o.MapFrom(p => p.team_id))
                .AfterMap((p, k) =>
                              {
                                  if (k.CreateUser == null)
                                  {
                                      k.CreateUser = new MissingUser();
                                  }
                              })
                .AfterMap((p, k) =>
                              {
                                  if (k.CurrentLeague == null)
                                  {
                                      k.CurrentLeague = new MissingLeague();
                                  }
                              })
                .AfterMap((p, k) =>
                              {
                                  if (k.Country == null)
                                  {
                                      k.Country = new MissingCountry();
                                  }
                              });

            Team temp = Mapper.Map(team);
            return temp;
        }