Feedjit

Articles for you

Showing posts with label C#. Show all posts
Showing posts with label C#. 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 29, 2013

Software with Source Code to convert RGB to CMYK Converter in C# Image Resizer and Without Using Color Profile

using Photoshop;
using System.IO;
namespace Image_Converter

{
    public partial class Form1 : Form
    {
Photoshop.Application appRef = default(Photoshop.Application);
        Photoshop.Document currentDoc = default(Photoshop.Document);
public Form1()
        {
            InitializeComponent();
         
        }
private void convert_Click(object sender, EventArgs e)
        {
            long originalWidth;
            long originalHeight;
         
            if (txtFrom.Text != "" && txtTo.Text!= "")
            {
                Thread th_1 = new Thread(new ThreadStart(show));
                try
                {
                 
                 
                    th_1.Start();
                    appRef = new Photoshop.Application();
                    appRef.Visible = false;
                    appRef.DisplayDialogs = PsDialogModes.psDisplayNoDialogs;

                    String[] files = Directory.GetFiles(txtFrom.Text);
                    foreach (string fl in files)
                    {
                        if (fl.EndsWith(".jpg") || fl.EndsWith(".jpeg"))
                        {
                            currentDoc = appRef.Open(fl);
                            currentDoc.ChangeMode(PsChangeMode.psConvertToCMYK);
                            appRef.Preferences.RulerUnits = Photoshop.PsUnits.psPixels;
                            originalHeight = (long)currentDoc.Height;
                            originalWidth = (long)currentDoc.Width;
                            int targetHeight = (int)(originalHeight);
                            int targetWidth = (int)(originalWidth);
                            Photoshop.JPEGSaveOptions jpeg = new Photoshop.JPEGSaveOptions();
                            jpeg.Quality = 8;
                            currentDoc.ResizeImage(targetWidth, targetHeight, 300, PsResampleMethod.psBicubic);
                            string temp = txtTo.Text + Path.GetFileName(fl);
                            currentDoc.SaveAs(txtTo.Text + "\\" + Path.GetFileName(fl), jpeg);
                            currentDoc.Close(PsSaveOptions.psDoNotSaveChanges);

                        }
                    }

                }

                catch (Exception ex) {
                    MessageBox.Show(ex.ToString());
                    label3.Hide();
                }

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

Vacuum Cleaner Artificially Intelligent Implementation A.I based with Auto Manual System in C#



                           VACUUM_CLEANER
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Dru_Cleaner      //Main Form
{
    public partial class Main_Form : Form
    {
        public Main_Form()
        {
            InitializeComponent();}

    private void button2_Click(object sender, EventArgs e)
        {this.Close();}

    private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                int choice = int.Parse(textBox1.Text);
                if (choice == 1)
                {
                    Manual_Form obj = new Manual_Form(); obj.Show();this.Hide();}
                else if (choice == 2)
                {
                Automatic_Form obj = new Automatic_Form();obj.Show();this.Hide(); }
                else if (choice == 3)
                {
               Choice_Random obj = new Choice_Random();obj.Show();this.Hide(); }
                textBox1.Text = null;}
            catch (Exception ex) { MessageBox.Show(ex.Message); }}}}
/////////////////////////////////////      Manual Form
namespace Dru_Cleaner{
    public partial class Manual_Form : Form
    {
        public Manual_Form()
        {
            InitializeComponent();}
      
public string[,] lookup = new string[5,3];
private void button1_Click(object sender, EventArgs e)
        {
         string location, status = null;location = textBox1.Text.ToUpper();
         status =   textBox2.Text.ToUpper();int bound0 = lookup.GetUpperBound(0);
        int bound1 = lookup.GetUpperBound(1);
            for (int j = 0; j < bound0; j++)
            {
 for (int k = 0; k < bound1; k++){
 
if (location == lookup[j, k])
  {
     if (status == lookup[j, ++k]){ MessageBox.Show(lookup[j, ++k]); }}}}
      textBox1.Text = null;textBox2.Text = null;
        }
private void Form1_Load(object sender, EventArgs e){
            lookup[0, 0] = "A"; lookup[0, 1] = "DIRTY"; lookup[0, 2] = "CLEAN";
            lookup[1, 0] = "A"; lookup[1, 1] = "CLEAN"; lookup[1, 2] = "MOVE RIGHT";
            lookup[2, 0] = "B"; lookup[2, 1] = "DIRTY"; lookup[2, 2] = "CLEAN";
            lookup[3, 0] = "B"; lookup[3, 1] = "CLEAN"; lookup[3, 2] = "MOVE LEFT";}
private void button2_Click(object sender, EventArgs e){
            this.Close();
            Application.OpenForms[0].Show();}}}
/////////////////////////////////////////
namespace Dru_Cleaner
{
    public partial class Automatic_Form : Form
    {
        public Automatic_Form()
        {
            InitializeComponent();}
public string[,] lookup = new string[5, 3];
private void button2_Click(object sender, EventArgs e)
{
  this.Close();Application.OpenForms[0].Show();}

private void button1_Click(object sender, EventArgs e)
{
   textBox1.Text = null;button1.Enabled = false;
   int bound0 = lookup.GetUpperBound(0);int bound1 = lookup.GetUpperBound(1);
 for (int j = 0; j <= bound0; j++)
            {
                for (int k = 0; k <= bound1; k++)
             
 textBox1.Text += "   ";textBox1.Text += lookup[j, k];textBox1.Text += "                    ";
 Stopwatch delayWatch = new Stopwatch();
 while (delayWatch.ElapsedMilliseconds < 1200)
                    {
                        delayWatch.Start();
                        Application.DoEvents();
                        delayWatch.Stop();} } textBox1.Text += Environment.NewLine}}
     textBox1.Text += "STOP...! The whole area is now cleaned up";
            button1.Enabled = true;}
        private void Automatic_Form_Load(object sender, EventArgs e)
        {
            lookup[0, 0] = "A"; lookup[0, 1] = "DIRTY"; lookup[0, 2] = "CLEAN";
            lookup[1, 0] = "A"; lookup[1, 1] = "CLEAN"; lookup[1, 2] = "MOVE RIGHT";
            lookup[2, 0] = "B"; lookup[2, 1] = "DIRTY"; lookup[2, 2] = "CLEAN";
            lookup[3, 0] = "B"; lookup[3, 1] = "CLEAN"; lookup[3, 2] = "MOVE LEFT";
            lookup[4, 0] = "A"; lookup[4, 1] = "CLEAN"; lookup[4, 2] = "MOVE RIGHT";
        }}}
////////////////////////////   //Random Choic Form
namespace Dru_Cleaner
{
    public partial class Random_Form : Form
    {
        public Random_Form()
        {
            InitializeComponent();
        }
        public string[,] lookup = new string[5, 3];
 private void Random_Form_Load(object sender, EventArgs e)
        {
            lookup[0, 0] = "A"; lookup[0, 1] = "DIRTY"; lookup[0, 2] = "CLEAN";
            lookup[1, 0] = "A"; lookup[1, 1] = "CLEAN"; lookup[1, 2] = "MOVE RIGHT";
            lookup[2, 0] = "B"; lookup[2, 1] = "DIRTY"; lookup[2, 2] = "CLEAN";
            lookup[3, 0] = "B"; lookup[3, 1] = "CLEAN"; lookup[3, 2] = "MOVE LEFT";
        }

 private void button1_Click(object sender, EventArgs e)
        {
    if (textBox1.Enabled==false)
            {
                Random RandNum = new Random();
                int MyRandomNumber = RandNum.Next(4);
                string location, action = null;
                location = lookup[MyRandomNumber, 0];
                action = textBox2.Text.ToUpper();
                int bound0 = lookup.GetUpperBound(0);
                int bound1 = lookup.GetUpperBound(1);
                for (int j = 0; j < bound0; j++)
                {
                    for (int k = 0; k < bound1; k++)
                    {
                        if (location == lookup[j, k])
                        {
                            k++;
                            if (action == lookup[j, ++k])
        { MessageBox.Show("Location:  " + location + "\n" + "State:    " + lookup[j, --k]); }
                        }}}
            }
            else if (textBox2.Enabled == false)
            {
                Random rd = new Random();
                int rnum = rd.Next(4);
                string location, action = null;
                location = textBox1.Text.ToUpper();
                action = lookup[rnum, 2];
                int bound0 = lookup.GetUpperBound(0);
                int bound1 = lookup.GetUpperBound(1);
                for (int j = 0; j < bound0; j++)
                {
                    for (int k = 0; k < bound1; k++)
                    {
                        if (location == lookup[j, k])
                        {
                            k++;
                            if (action == lookup[j, ++k])
        { MessageBox.Show("State:  " + lookup[j, --k] + "\n" + "Action:  " + action); }
                        }
                    }
                }

            }
         textBox1.Text = null;
         textBox2.Text = null;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.Close();
            Application.OpenForms[1].Show();
        }
    }
}

Read More

Articles for you