Feedjit

Articles for you

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

Sunday, June 15, 2014

Log4net Implementation in CRM 2011, log4net in CRM Plugins, WebServices and Custom aspx Pages.

This post is about log4net logger implementation in CRM 2011. I will provide details about log4net in CRM Plugins. It is as the same with Web-services and Custom aspx Pages.


1. First we will have a Config file for log4net so that, its configuration/settings can be read and applied to logger.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
  </configSections>
  <log4net>
    <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="D:\Logger\Log4net\logs\log.txt" />
      <appendToFile value="false" />
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="5" />
      <maximumFileSize value="1GB" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
      </layout>
    </appender>
    <appender name="MemoryAppender" type="log4net.Appender.MemoryAppender">
    </appender>
    <root>
      <level value="Info" />
      <appender-ref ref="RollingLogFileAppender" />
      <appender-ref ref="MemoryAppender" />
    </root>
  </log4net>
</configuration
Copy all this into a file named "log4net.config" and place it in D:\Logger\Log4net\Config\

2. Add log4net.dll to your Plugin.

3.
using log4net;
using log4net.Config;
public class MyPlugin: IPlugin
    {
    protected static readonly ILog Logger = LogManager.GetLogger(typeof(PublishToGRID));
    static MyPlugin()
    {
      XmlConfigurator.Configure(new System.IO.FileInfo(@"D:\Logger\Log4net\Config\log4net.config"));
    }
try
{
if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
{
  Logger.Info("Plugin Executed");
}
}
catch (Exception ex)
{
  string ErrorMessage = "Exception Occured in CRM";
  Logger.Error(ErrorMessage,ex);              
}


After your plugin executed: you will se the log file generated in D drive.
containing the following text:

Logger.info: 6/15/2014  7:11 p.m
Plugin Excuted







Wednesday, May 28, 2014

Bridge Inspection and Management system in Asp Dot Net (.NET C#) with Source Code and Database in MS Sql Server 2008


I have developed Bridge Inspection System using Visual Studio Web-Site Project in Asp.net with C#, using my own CSS styling.
Database: in Microsoft SQL server 2008 R2.
Above is the Main Screen, Default Page.
Following are features in this Bridge Inspection System:



  • Admin who can add more admins,Collectors,Inspectors and Bridges to be inspected in  System
    Delete Collectors, Inspectors and Bridges from the System.
  • Bridge Inspector who can Inspect the Bridges that are currently added and make a report
  • Bridge Collector who can View the final Reports added by BI.
  • Reports Generation from Inspected Bridge Data and Export Reports in PDF format to be ready for download and printing.
  • Profile Management.
  • and more ..........................
  • Sql Server 2008 Database, Normalized and Complete Relationships.
Following are some screen-shots of the system.




Admin Login:





Admin Page:





 Add Bridge Profile:





Profile Managment:








 Bridge Profile View:
If anyone need Source Code along with the Database file, please ask in Comments I will provide links:
Thanks,
Saqib Khan. (Dynamics CRM developer).


Tuesday, December 24, 2013

How to Create a new Guid CRM 2011 C# xRM Empty Guid or Null Guid

 How to Create/Generate a New GUID using Vb.Net, C# and Vb.Script

 Suppose i have got a guid in Query String like


http://localhost:3214/Default.aspx?id=9D2B0228-4D0D-4C23-8B49-01A698857709


or

like this

// Without Dashes
http://localhost:3214/Default.aspx?id=9D2B02284D0D4C238B4901A698857709










if (Request.QueryString["id"] != null)

string Id = Request.QueryString["id"];

Guid guid = new Guid(Id);

if(guid!= Guid.Empty)
{
  //Use id here to retreive the record.
}








Sunday, September 15, 2013

Simplest and Fastest File Searcher in C#. How to Copy Zip Files from Source to Destination Using C#, .NET

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;

namespace Utillity_1
{
    public partial class Form1 : Form
    {
        public string source_path = "E:\\Received files";
        public string destination_path = "D:\\Saqib\\Approved";
        public Form1()
        {
            InitializeComponent();
        }

     

     
        private void btn_Browse_Click(object sender, EventArgs e)
        {
            openFileDialog1.Title = "Open CSV/TSV File";
            openFileDialog1.Filter = "CSV(*.csv)|*.csv";//|TSV(*.tsv)|*.tsv";
            openFileDialog1.Multiselect = false;
           // openFileDialog1.ShowDialog();
            try
            {
                string[] filePaths = Directory.GetFiles(source_path,"*.zip");
         
                if (openFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    StreamReader csv_reader = new StreamReader(openFileDialog1.FileName);
                    //string temp = csv_reader.ReadToEnd();
                    string temp=null;
                    while (!csv_reader.EndOfStream)
                    {
                        string line = csv_reader.ReadLine();
                        if (!(string.IsNullOrEmpty(line)))
                        {
                            string[] values = line.Split(',');

                           // temp += values[0];
                           // temp += Environment.NewLine;
                            foreach (string file in filePaths)
                            {
                                //Console.WriteLine(file);
                                if (file.EndsWith(".zip"))
                                {
                                  string path = Path.GetFileName(file);
                                  string[] to_get_filename = path.Split('.');
                                  string filename = to_get_filename[0];
                                  if (filename.Equals(values[1]))
                                  {
                                      // MessageBox.Show(file);
                                     // source_path +="\\"+ filename+".zip";
                                      destination_path = Path.Combine(destination_path, path);
                                     // File.Move(file, destination_path);
                                      File.Copy(file, destination_path, true);
                                   
                                  }
                                }
                            }
                        }
                    }
                    MessageBox.Show(temp);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
        private void btn_Close_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Really Close?", "Confirm close", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                this.Close();
            }
         
        }

    }
}

Tuesday, August 20, 2013

How to Get All Uparas from the XML using XPATH and C#. XSL XSLT XPATH XML Using Regular Expression REGEX

using System.IO;
using System.Collections;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Xsl;
namespace XML_Parser
{
    class Program
    {
        public static Hashtable hash_table = new Hashtable();
        static void Main(string[] args)
        {
            string path = @"C:\Documents and Settings\saqib\My Documents\OMessenger\Received files\KOKODA-With Index.xml";
            string pattern = @"[a-z][a-z]+\.[a-z]+";
            XslCompiledTransform myxsl = new XslCompiledTransform();
            myxsl.Load("XSLTFile1.xslt");
            myxsl.Transform(path, "To_Table.html");
          //  var xDocument = XDocument.Load(path);
          //  string xmll = xDocument.ToString();
            XmlDocument xml =new XmlDocument();
            xml.Load(path);

XmlNodeList xnList = xml.SelectNodes("//upara");
//Console.WriteLine(xnList.Count);
foreach (XmlNode xn in xnList)

{
    //Console.WriteLine(xn.InnerText);
    string upara = xn.InnerText;
 
    MatchCollection matches = Regex.Matches(upara, pattern);
    foreach (Match match in matches)
    {
        foreach (Capture capture in match.Captures)
        {
            Console.WriteLine("Index={0}, Value={1}", capture.Index, capture.Value);
            hash_table.Add(capture.Index, capture.Value);
        }
    }

}
Console.ReadKey();
        }          
                    }
                }
         
        

Saturday, June 22, 2013

WPF Client for Console Server Signalr Server. ASP.NET, Signalr, WPF Client

Main Window.Xaml
////////////////////////////
<Window x:Class="Virtual_Trainer_Client.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Button x:Name="Button1" Content="Send" HorizontalAlignment="Left" Margin="268,35,0,0" VerticalAlignment="Top" Width="75" Click="Button1_Click"/>
        <Button x:Name="Button2" Content="Connect" HorizontalAlignment="Left" Margin="385,35,0,0" VerticalAlignment="Top" Width="75" RenderTransformOrigin="0.5,0.5" Click="Button2_Click"/>
        <ListBox x:Name="listBox1" HorizontalAlignment="Left" Height="100" Margin="183,107,0,0" VerticalAlignment="Top" Width="258" RenderTransformOrigin="0.231,0.401"/>
        <TextBox x:Name="textBox1" HorizontalAlignment="Left" Height="39" Margin="87,63,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="127"/>
        <TextBox x:Name="textbox2" HorizontalAlignment="Left" Height="80" Margin="29,107,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="149"/>
        <Label x:Name="label_welcome" Content="" HorizontalAlignment="Left" Margin="19,10,0,0" VerticalAlignment="Top" Height="26" Width="149"/>

    </Grid>
</Window>
///////////////////////////////////////////////////////////////////
Main Window.xaml.cs
///////////////////////////////////
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Client;
using Microsoft.AspNet.SignalR.Client.Hubs;
//using System.Windows.Threading.Dispatcher;


namespace Virtual_Trainer_Client
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        IHubProxy proxy;
        HubConnection connection;
        public MainWindow()
        {
            InitializeComponent();
         
       
        }
        private void Button2_Click(object sender, RoutedEventArgs e)
        {
            connection = new HubConnection(@"http://localhost:8081/");
            proxy = connection.CreateHubProxy("commHub");
           
          
            proxy.On("broadCastToClients", message =>function(message));
            proxy.On("joined",mess=>this.Dispatcher.Invoke((Action)(()=>label_welcome.Content="Wellcome from Server")));
          
            connection.Error += connection_Error;
            connection.Start().Wait();
        }
        void connection_Error(Exception obj)
        {
            MessageBox.Show(obj.Message);
        }

        void function(string mess)
        {
            this.Dispatcher.Invoke((Action)(() => { textbox2.Text += mess+'\n'; }));
        }
      

        private void Button1_Click(object sender, RoutedEventArgs e)
        {
      
          
            proxy.Invoke("send", textBox1.Text);
            textBox1.Text = null;
       
        }
        private  void UpdateApplicationDataUI(string msg)
        {
            //txtStatus.Text = "test";
            textbox2.Text = msg;
        }
   
       
    }
    public static class ControlExtensions
    {
        public static void Invoke(this Control Control, Action Action)
        {
            Control.Invoke(Action);
        }
    }
}
/////////////////////////////////////////////////////
Run Server
then Client
Click on connect a welcome message will be sent from server to client.
Then any message sent by the client will be received back from the server.

Thursday, June 6, 2013

Assignment # 03 Artificial Intelligence, Fall 2012 8 Queens Problem. GenetiC Algorithm



Assignment # 03
Artificial Intelligence, Fall 2012
Department of Computer Science & Software Engineering, IIUI
Submission Deadline: Monday 04:30 PM, December 10, 2012






The above diagram illustrates the working of Genetic Algorithm. For example the number 24748552 depict the position of the queens. The below diagram explain all.


1
2
3
4
5
6
7
8
1








2
Q






Q
3








4

Q

Q




5





Q
Q

6








7


Q





8




Q





A pair of queen is attacking pair directly or indirectly if both are in same row or same column or in same diagonal.

You are required to perform following task
  1. Take four states of the Queen table as Initial population. You are required to use to rand function to produce the position of each queen in each column in all four states.
  2. Find the number of non-attacking pairs (fitness) for each state.
  3. Perform selection step. The selection should be random in which one state can come either zero time or more than one times.
  4. The cut for cross over should be decided randomly on each pair.
  5. In mutation, mute only single element of each state.
  6. Calculate the fitness again. If the fitness of even single state is better than all states in initial population then stop and display that state, otherwise repeat step 3 to 6
 //////////////////////////////////////////////////////

                           GENETIC ALGORITHM
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
using System.Threading;

namespace Genetic_Algo
{
    class Program
    {
        public int selected1,selected2,selected3,selected4;
        int[] arr1, arr2, arr3, arr4 = new int[9];
        public static int[] Original = new int[5];
        public static int[] Calculated = new int[5];
        public int[] array1=new int[9];
        public int[] array2=new int[9];
        public int[] array3=new int[9] ;
        public int[] array4=new int[9];
        public static Random random_num = new Random();
        static int collision_pairs=0;
       
///////////////////////////////////////////////////////////////////
public void Initial_Population()  // Generate Four States of the Queen initial population
        {
            double percentage = 0;
                for (int j = 1; j < 9; j++)
                {
                    array1[j]=random_num.Next(1,9);
                    array2[j] = random_num.Next(1, 9);
                    array3[j] = random_num.Next(1, 9);
                    array4[j] = random_num.Next(1, 9);}
// Initial Fitness Values Stored in Original array
                EvaluateCollision(array1);
                Original[1] = 28 - collision_pairs;
                EvaluateCollision(array2);
                Original[2] = 28 - collision_pairs;
                EvaluateCollision(array3);
                Original[3] = 28 - collision_pairs;
                EvaluateCollision(array4);
                Original[4] = 28 - collision_pairs;
////////////////////////////////////Calculate the Original Values Percentages
percentage = (double)Original[1]/(Original[1]+Original[2]+Original[3]+Original[4]);
percentage = percentage * 100; percentage = Math.Round(percentage);
Original[1] = (int)percentage;

percentage = (double)Original[2] / (Original[1] + Original[2] + Original[3] + Original[4]);
percentage = percentage * 100; percentage = Math.Round(percentage);
Original[2] = (int)percentage;

percentage = (double)Original[3] / (Original[1] + Original[2] + Original[3] + Original[4]);
percentage = percentage * 100; percentage = Math.Round(percentage);
Original[3] = (int)percentage;

percentage = (double)Original[4] / (Original[1] + Original[2] + Original[3] + Original[4]);
                percentage = percentage * 100; percentage = Math.Round(percentage);
                Original[4] = (int)percentage;
  /////////////////////////////// Write Initial Population on Screen
Console.WriteLine("Initial Population:" + "   " + "Non-Attacking Queens Pairs %"); Console.WriteLine("-------------------   -----------------------------");
                for (int w = 1; w < 9; w++) { Console.Write(array1[w]); } Console.WriteLine("                       "+Original[1]);
                for (int w = 1; w < 9; w++) { Console.Write(array2[w]); } Console.WriteLine("                       "+Original[2]);
                for (int w = 1; w < 9; w++) { Console.Write(array3[w]); } Console.WriteLine("                       "+Original[3]);
                for (int w = 1; w < 9; w++) { Console.Write(array4[w]); } Console.WriteLine("                       "+Original[4]); }
///////////////////////////////////////////////////////////////////
 public void EvaluateCollision(int[] array)  //Function to count attacking queens
{
    collision_pairs = 0;

    for (int i = 1; i <= 8; i++)
        for (int j = i + 1; j <= 8; j++)
            if (Math.Abs(i - j) == Math.Abs(array[i] - array[j]))
              
                collision_pairs++;
        for (int j = 1; j < 8; j++)
        {
            for (int k = j + 1; k < 9; k++)
            {
                if (array[j] == array[k])
                {
                    collision_pairs++;
                }}}}
//////////////////////////////////////////////////////////////////
public void Fitness_Function()    //Calculate the Fitness again and again
 {
     Console.ForegroundColor = ConsoleColor.DarkCyan;
     Console.Write("Performing Fitness Step");
     for (int i = 1; i <= 6; i++)
     {
         Console.Write(".");
         Thread.Sleep(50);
     } Console.WriteLine();
    double percentage = 0;
    EvaluateCollision(arr1);
    Calculated[1] = 28 - collision_pairs;
    EvaluateCollision(arr2);
    Calculated[2] = 28 - collision_pairs;
    EvaluateCollision(arr3);
    Calculated[3] = 28 - collision_pairs;
    EvaluateCollision(arr4);
    Calculated[4] = 28 - collision_pairs;
////////////////////////////////////////  //Calculate Percentages
percentage=(double)Calculated[1]/(Calculated[1] + Calculated[2] + Calculated[3] + Calculated[4]);
percentage = percentage * 100; percentage = Math.Round(percentage);
Calculated[1] = (int)percentage;
percentage = (double)Calculated[2] / (Calculated[1] + Calculated[2] + Calculated[3] + Calculated[4]);
percentage = percentage * 100; percentage = Math.Round(percentage);
Calculated[2] = (int)percentage;
percentage = (double)Calculated[3] / (Calculated[1] + Calculated[2] + Calculated[3] + Calculated[4]);
percentage = percentage * 100; percentage = Math.Round(percentage);
    Calculated[3] = (int)percentage;

    percentage = (double)Calculated[4] / (Calculated[1] + Calculated[2] + Calculated[3] + Calculated[4]);
    percentage = percentage * 100; percentage = Math.Round(percentage);
    Calculated[4] = (int)percentage;}
   
//////////////////////////////////////////////////////////////////
public void Selection()        //Make Random Selection of States
{
    Console.ForegroundColor = ConsoleColor.Green;
    Console.Write("Performing Selection Step");
    for (int i = 1; i <= 6; i++)
    { Console.Write(".");
    Thread.Sleep(50);
    } Console.WriteLine();
    selected1 = random_num.Next(1,5);
    selected2 = random_num.Next(1,5);
    selected3 = random_num.Next(1,5);
    selected4 = random_num.Next(1,5);
    if (selected1 == 1) { arr1 = array1; }; if (selected1 == 2) { arr1 = array2; }; if (selected1 == 3) { arr1 = array3; };
    if (selected1 == 4) { arr1 = array4; }

    if (selected2 == 1) { arr2 = array1; }; if (selected2 == 2) { arr2 = array2; }; if (selected2 == 3) { arr2 = array3; };
    if (selected2 == 4) { arr2 = array4; }
   
    if (selected3 == 1) { arr3 = array1; }; if (selected3 == 2) { arr3 = array2; }; if (selected3 == 3) { arr3 = array3; };
    if (selected3 == 4) { arr3 = array4; }
   
    if (selected4 == 1) { arr4 = array1; }; if (selected4 == 2) { arr4 = array2; }; if (selected4 == 3) { arr4 = array3; };
    if (selected4 == 4) { arr4 = array4; }
}
//////////////////////////////////////////////////////////////////
public void Cross_Over()   //Mark Cut Randomly in States
{
    Console.ForegroundColor = ConsoleColor.DarkYellow;
    Console.Write("Performing Cross-Over Step");
    for (int i = 1; i < 6; i++)
    {
        Console.Write(".");
        Thread.Sleep(50);
    } Console.WriteLine();
   
    int[] temp = new int[9];
    int cut1, cut2;
    cut1 = random_num.Next(1,9);
    cut2 = random_num.Next(1,9);
    for (int loop1 = cut1 + 1; loop1 < 9; loop1++)
    { temp[loop1] = arr1[loop1];
      arr1[loop1] = arr2[loop1];
      arr2[loop1] = temp[loop1]; 
    }
    for (int loop2 = cut2 + 1; loop2 < 9;loop2++ )
    {
        temp[loop2] = arr3[loop2];
        arr3[loop2] = arr4[loop2];
        arr4[loop2] = temp[loop2];
    }}
//////////////////////////////////////////////////////////////////
public void Mutation()        //Change a number at random position by a random number
{
    Console.ForegroundColor = ConsoleColor.Yellow;
    Console.Write("Performing Mutation  Step");
    for (int i = 1; i <= 6; i++)
    {
        Console.Write(".");
        Thread.Sleep(50);
    } Console.WriteLine();
   
    arr1[random_num.Next(1, 9)] = random_num.Next(1, 9);
    arr2[random_num.Next(1, 9)] = random_num.Next(1, 9);
    arr3[random_num.Next(1, 9)] = random_num.Next(1, 9);
    arr4[random_num.Next(1, 9)] = random_num.Next(1, 9);
}
//////////////////////////////////////////////////////////////////
public static void Main(string[] args)
{
    bool flag = false;
    Program obj = new Program();
    Console.ForegroundColor = ConsoleColor.Red;
    obj.Initial_Population();
    Console.WriteLine("---------------------------------------------------");
    obj.Selection();
    obj.Cross_Over();
    obj.Mutation();
    while (true)
    {
        int[] State_Solution = new int[9];
        obj.Fitness_Function();
        for (int a = 1; a < 5; a++)
        {
            int curr = Calculated[a];
            if (curr > Original[1] && curr > Original[2] && curr > Original[3] && curr > Original[4])
            {
                Console.ForegroundColor = ConsoleColor.Magenta;
                Console.WriteLine("-------------------------------");
   Console.Write("Resultant State:       "); Console.WriteLine("Non-Attacking Queens %");
   if (a == 1) { State_Solution = obj.arr1; } if (a == 2) { State_Solution = obj.arr2; }
   if (a == 3) { State_Solution = obj.arr3; } if (a == 4) { State_Solution = obj.arr4; }
   for (int write = 1; write < 9; write++)
                {
                    Console.Write(State_Solution[write]);}
               
                obj.EvaluateCollision(State_Solution);
                Console.WriteLine("                         "+Calculated[a]);
                flag = true;
                break;
            } }
        if(flag==false)
        {
            obj.Selection();
            obj.Cross_Over();
            obj.Mutation();
        }
   
        if (flag == true)
        {
            Console.ReadLine();
            break; }    }}}}
 

Read More

Articles for you