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

Saturday, October 12, 2019

Send Push Notification using C#

Here is the way by which we can send push notification to mobile device. Below are some steps to perform before sending notification to device.

(1) Google Firebase provides way by which we can send push notification through that. In this case we have valid google account 
(2) From your Firebase account, create project for the android/ios application
(3) Once your application is installed on your device it will register your device for that project to receive notification
(4) When your device is ready with application created on firebase and device id is registered then it is ready to receive push notifications for that application
(5) In step - (4), when your device is registered with device id, this device id to be shared or stored at some repository so that whenever we want to send notification we can pull that device id and send notification with below c# code

var result = "-1";
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://fcm.googleapis.com/fcm/send");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Headers.Add(string.Format("Authorization: key={0}", "server key"));
httpWebRequest.Headers.Add(string.Format("Sender: id={0}", "Test Sender"));
httpWebRequest.Method = "POST";

var payload = new
{
to = "device token",
priority = "high",
        content_available = true,
notification = new
        {
        body = "body of notification",
        title = "notification title"
        },
};

using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = JsonConvert.SerializeObject(payload);
        streamWriter.Write(json);
        streamWriter.Flush();
}

var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}

Tuesday, February 5, 2019

Excel Operations Using Excel Interop Assembly

Here is code to read excel file which will read file and converts its cell to specific format like date format or number format or so and then save new version of file to take effect of the new file converted with provided format and leave original file as it is.

For the excel file to read, it is 2010pia which is installed to read excel file and in reference there will be version with 15.0 for excel is used to read excel file. The link to download is below

Download Microsoft Office 2010: Primary Interop Assemblies Redistributable

Below code to read excel file using office interop excel assembly and perform changes in cell and save that file
Microsoft.Office.Interop.Excel.Application objexcel = new Microsoft.Office.Interop.Excel.Application();

objexcel.DisplayAlerts = false;

Microsoft.Office.Interop.Excel.Workbook workbook = objexcel.Workbooks.Open("your file path", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

Microsoft.Office.Interop.Excel.Worksheet sheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Sheets.get_Item(1);

rangeoutput = sheet.UsedRange;

int lastRow = sheet.Cells.SpecialCells(Microsoft.Office.Interop.Excel.XlCellType.xlCellTypeLastCell, Type.Missing).Row;

int lastColumn = sheet.Cells.SpecialCells(Microsoft.Office.Interop.Excel.XlCellType.xlCellTypeLastCell, Type.Missing).Column;

Microsoft.Office.Interop.Excel.Range oRange = (Microsoft.Office.Interop.Excel.Range)sheet.get_Range((Microsoft.Office.Interop.Excel.Range)sheet.Cells[1, 1], (Microsoft.Office.Interop.Excel.Range)sheet.Cells[lastRow, lastColumn]);

oRange.EntireColumn.AutoFit();

for (int i = 0; i < oRange.Columns.Count; i++)
{
    dt.Columns.Add("a" + i.ToString());
}

object[,] cellValues = (object[,])oRange.Value2;

object[] values = new object[lastColumn];

//Loop through the all rows of the excel file and operate to change the type of the cell
for (int i = 1; i <= lastRow; i++)
{
    //Loop through the columns and get the each cell value from rows
    for (int j = 0; j < dt.Columns.Count; j++)
    {
        //This implementation for selecting columns names from excel file
        if (i == 1)
        {
    //If you know the column name then from here set for the entire column format
            sheet.get_Range("B1").EntireColumn.NumberFormat = "dd/MM/yyyy";
        }
        else
        {
    //if entire column format is not get set then go with this else part where if you know the cell index then go with it
            if (j == 13)
            {
//for me it was date operation to perform and i checked statically with 13 which when comes picks the value for cell and convert it
                string str = Convert.ToString(cellValues[i, j + 2]);
                DateFormat numFormat = strColumns.Where(x => x.ColumnIndex == j + 2).FirstOrDefault();
                if (!string.IsNullOrWhiteSpace(str))
                {
                    double dblResult = 0;
                    bool blnIsDbl = double.TryParse(str, out dblResult);
                    if (blnIsDbl)
                    {
(rangeoutput.Cells[i, j + 2] as Microsoft.Office.Interop.Excel.Range).NumberFormat = numFormat.ColumnFormat;
                        double d = double.Parse(str);
                        DateTime conv = DateTime.FromOADate(d);
                        values[j] = conv.ToShortDateString();// cellValues[i, j + 1];
                        string strNewValue = conv.ToString(numFormat.ColumnFormat);
                        (rangeoutput.Cells[i, j + 2] as Microsoft.Office.Interop.Excel.Range).Value = strNewValue;
                        (rangeoutput.Cells[i, j + 2] as Microsoft.Office.Interop.Excel.Range).Value2 = strNewValue;
                    }
                    else
                    {
                        //if cell value are correct then fine but if it is wrong then here in else part checking its value then if it is wrong then keep it as it is
                        try
                        {
                            DateTime dt1;
                            bool IsValidDate = DateTime.TryParseExact(str, numFormat.ColumnFormat, null, DateTimeStyles.None, out dt1);
                            if (IsValidDate)
                            {
                                string strNewValue = dt1.ToString(numFormat.ColumnFormat);
                                (rangeoutput.Cells[i, j + 2] as Microsoft.Office.Interop.Excel.Range).Value = strNewValue;
                                (rangeoutput.Cells[i, j + 2] as Microsoft.Office.Interop.Excel.Range).Value2 = strNewValue;
                            }
                            else
                            {
                                (rangeoutput.Cells[i, j + 2] as Microsoft.Office.Interop.Excel.Range).Value = str;
                                (rangeoutput.Cells[i, j + 2] as Microsoft.Office.Interop.Excel.Range).Value2 = str;
                                intInvalidRows.Add(i);
                            }
                        }
                        catch (Exception Exc)
                        {
                            Exc.Message.ToString();
                            (rangeoutput.Cells[i, j + 2] as Microsoft.Office.Interop.Excel.Range).Value = str;
                            (rangeoutput.Cells[i, j + 2] as Microsoft.Office.Interop.Excel.Range).Value2 = str;
                        }
                    }
                }
            }
        }
    }
}

//Saves the changed excel file and then closes the file along with current workbook
objexcel.DisplayAlerts = false;

objexcel.ActiveWorkbook.SaveAs(Filename: "file path to save", FileFormat: Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault, CreateBackup: false);

objexcel.ActiveWorkbook.Close(SaveChanges: false);

objexcel.DisplayAlerts = true;

objexcel.Quit();

There are multiple operations has been performed here like opening file/changing file content/assigning cell format/save file using Excel Interop Assembly.

Thursday, January 31, 2019

Error: Retrieving the COM class factory for component with CLSID {00024500-0000-0000-C000-000000000046} failed due to the following error: 80070005 Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)).

While working with Excel Interop Assembly for reading an excel file, I come up with error "Error: Retrieving the COM class factory for component with CLSID {00024500-0000-0000-C000-000000000046} failed due to the following error: 80070005 Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))". Found below error resolution for the error and performing steps in below links resolve my problem.

(1) System.UnauthorizedAccessException: Retrieving the COM class factory for Word Interop fails with error 80070005

(2) Access Denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)) - Powered by Kayako Help Desk Software

Performing steps provided in above links resolve my problem. 

Step to reproduce this error: While reading an excel file using Interop assembly, on below line of code

Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();

It throws above error right from this line of code.

Monday, November 27, 2017

Working with Microsoft Cognitive Services - Emotions

Here is the way by which we can get Emotions of image which contains face and by consuming service of Microsoft Cognitive Service we can detect face along with its emotions.

- All you need for this service to consume is 1) api url 2) Subscription Key
- For this example use image having faces and make sure you pass image convert into byte stream and pass it to service call which will return faces in it and emotions of that faces

Below is the code for this

var client = new HttpClient();

var queryString = HttpUtility.ParseQueryString(string.Empty);
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", Your Subscription Key);

var uri = uri + queryString;

HttpResponseMessage response;
Emotion[] emotionResult = null;

// Request body
byte[] byteData = image stream in bytes;

using (var content = new ByteArrayContent(byteData))
{
content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
response = await client.PostAsync(uri, content);
return response;
}

For this, please find below links to explore more
(1) Emotion API in C# Tutorial

(2) Emotion API

Thursday, August 11, 2016

Working with Authorize.net using Sandbox Account

Here is the way by which we can work with authorize.net. You can also work with Create New Sandbox and then Login to Sandbox Account. The steps provided here are worked for me and for code implementation, I used "Authorize Credit Card" which worked for me to my Sandbox Account.

Few things that you need to have to work with this is
(1) API Login ID
You will find login id from your account under Login to Sandbox --> Account Menu --> Security Settings --> General Security Settings --> Click on "API Credentials & Keys" link

(2) Transaction Key
You will find this transaction key from your account under Login to Sandbox --> Account Menu --> Security Settings General Security Settings --> Click on "Manage Public Client Key" link

From the same menu Login to Sandbox --> Account Menu --> Security Settings General Security Settings, you can also set
(3) MD5-Hash

(4) Test Mode - While your account is in Test Mode there will be only processing occurred not exact operation will be performed, but to work with live account after testing to charge/authorize your payment it should be in live mode.

Alternatively, you can also set few more things like
(1) Receipt Page :- Used to send payment information with all required information like API Login Id/Transaction Key/Payment information etc.

(2) Response/Receipt URLs :- Used when operation has been completed from Step-(1) and it sends response of the transaction indicating whether it is success/failure of the transaction.


by navigating to Login to Sandbox --> Account Menu --> Transaction Format Settings --> Transaction Response Settings

Set all this stuff to your sandbox account, You will get C# Sample Code as well. In that set required information to the code and set method of payment which you want to do like you can Charge Credit Card, Authorize Credit Card and so on.

Once this configuration and code with your account configuration execute with code provided based on the method(Charge Credit Card, Authorize Credit Card) selected you will find that thing under Login to Sandbox --> Search Menu --> Unsettled Transactions on success of your transaction.

Once you will are success with Sandbox account, for your live account you can check same thing under "Test Mode" account and to check with your actual transaction make it "Live" from "Test" mode.

That's it for the authorize.net implementation.

Monday, August 18, 2014

Working with AngularJS with Get/Post calls

Here is some code which will show how can we use get/post calls when working with AngularJS. For these code i assume that you are aware of some basic knowledge of AngularJS code and syntaxes. Also, for this examples i used WCF service as data source which returns expected results as i want for my use so you can change code or source of service as per your need.

(1) Get With Single Value : This function returns single string value.
HTML :  





AngularJS : 

var sample = function ($scope, $http) {
        $http({
            url: '/MyService.svc/DoWorkWithString'
        }).success(function (data) {
            $scope.stringResult = data.DoWorkWithStringResult;
        });
    };

(2) Get With List of values : This function returns list of Name & Count which are processed at UI and displayed to view.
HTML : 







AngularJS : 
var ListController = function($scope, $http) {
        var resultPromise = $http.get("MyService.svc/ListItems");
        resultPromise.success(function(data) {
            $scope.ListItems = data.ListItemsResult;
        });
    };

For the post operation, both function simply returns string value which could be any success/error message that we can pass to UI after completion of any
operation on posting.
(3) Post with single parameter : posts one valueHTML : 




Angular JS :
function FrmController($scope, $http) {
$scope.errors = [];
$scope.msgs = [];
$scope.Click = function () {
$scope.errors.splice(0, $scope.errors.length); // remove all error messages
$scope.msgs.splice(0, $scope.msgs.length);
$http({ method: 'POST', url: 'MyService.svc/ListTest', data: JSON.stringify($scope.idTest) }).success(function (data) {
                if (data != '') {
                    $scope.msgs.push(data);
                } else {
                    $scope.errors.push(data);
                }
            });
};

(4) Post with two parameter
HTML : 

Angular JS :
function FrmController($scope, $http) {
$scope.errors = [];
$scope.msgs = [];
$scope.Click = function () {
$scope.errors.splice(0, $scope.errors.length); // remove all error messages
$scope.msgs.splice(0, $scope.msgs.length);
$http({ method: 'POST', url: 'MyService.svc/ListTestTwo', data: JSON.stringify({"param1":"value1","param2":"value2"}) }).success (function (data) {
                if (data != '') {
                    $scope.msgs.push(data);
                } else {
                    $scope.errors.push(data);
                }
            });
};

So, That's it for AngularJS with Get/Post calls.

Thursday, August 14, 2014

Error : Operation 'Operation' of contract 'Contract' specifies multiple request body parameters to be serialized without any wrapper elements.

During working with WCF Service, multiple scenarios were there for me. I completed POST scenario with one argument which works fine for me. But, POST scenario with more than one argument leads me to following error 


"Operation 'Operation' of contract 'Contract'
specifies multiple request body parameters to be serialized without any wrapper
elements. 
At most one body parameter can be serialized without wrapper elements. Either remove the extra body parameters or set the BodyStyle property on the WebGetAttribute/WebInvokeAttribute to Wrapped."

after some googling i got to know, "WCF doesn't support more than one parameter with bare body, if you need pass several parameters in one post method operation, then we need set the BodyStyle to Wrapped."

I added BodyStyle attribute to my contract to Wrapped help me out to working condition for my method.
Following are some links which i find useful for me for this error.
(1) Why cant I use two arguments in a WCF REST POST method?

(2) WCF Service Proxy throws exception when more than one parameter is used in [OperationContract] method

(3) WebInvokeAttribute.BodyStyle Property

(4) WebMessageBodyStyle Enumeration

Tuesday, August 12, 2014

Error : Cannot have two operations in the same contract with the same name.

Working with WCF Service implementation i came across error "Cannot have two operations in the same contract with the same name.". Following is some links that will demonstrate what is the reason behind this.

(1) Function Overloading in WCF

(2) Cannot have two operations in the same contract with the same name

(3) 2 methods with the same name

Friday, August 8, 2014

Simple WCF Application Call From Client End

Today, i am going to create simple WCF Web Service and consume same web service from client side.
(A) Steps to create new WCF Service
(1) Right Click on your solution --> Add --> New Project --> Select ASP.NET Web Application --> Give appropriate name like "REST"
(2) Above step will create new Web Application, you can remove master page and other pages included from newly created project
(3) Right Click on newly created project --> Add --> New Item --> Select "WCF Service" --> Give appropriate name like "MyService"
(4) Above step will add an interface named "IMyService" already implemented and one service with extension "MyService.svc"
(5) Remove existing code implemented in interface as well as in service.
(6) Add following line of code in interface
[OperationContract]
[WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json)]
string DoWorkWithString();
- This is simple method we have declare which will return string on execute.
- WebInvoke requires "System.ServiceModel.Web" name space to be added as reference in your project
(7) Implement above method with following code in MyService.cs
public string DoWorkWithString()
{
    return "This is one test";
}

(8) After completion of above code, create virtual directory named "REST" and bind it with above project.

(9) To run with existing code from client end, you need to change serviceModel tag with following line of code in your Web.Config file. To do that, replace following line of code of serviceModel with your Web.Config tag.



(B) Steps to call WCF Service from client end
Now, you are done with your simple service implementation, you can now call above service from client end using following line of code to your html and it will prompt "This is one test".
$.ajax({
    url: 'http://localhost/REST/MyService.svc/DoWorkWithString',
    dataType: 'json',
    cache: false,
    type: 'GET',
    contentType: 'application/json; charset=utf-8',
    data: {},
    error: function (XMLHttpRequest, textStatus, errorThrown) {
     alert('Error occurred during operation');
    },
    success: function (data1) {
        alert(data1.DoWorkWithStringResult);
    }
});

(C) You can also following navigate to following links to do same.


(1) An Introduction to WCF

(2) Four Steps to Create First WCF Service For Beginners

(3) Consuming WCF / ASMX / REST service using JQuery
       

Friday, July 11, 2014

Error : The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine.

Here i found another error generated over working with importing excel file. So, my idea behind importing an excel file is simple shown below.

Code to import excel file is shown below.
excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileLocation + ";Extended Properties='Excel 12.0;HDR=YES';";
DataTable dt = new DataTable();
OleDbConnection excelConnection1 = new OleDbConnection(excelConnectionString);
string query = string.Format("Select * from [{0}]", excelSheets[0]);
using (OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, excelConnection1))
{
        dataAdapter.Fill(ds);
}

but, doing this stuff i found error "The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine."


Googling around this error help me out by two cases. For the solution, i found following two links useful.
(1) 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine.

(2) 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine error


So, that's it for this error.

Friday, August 23, 2013

Working with Code Snippet

If you are working with Visual Studio IDE for c#/vb then you came across a situation where you need to write down a same line of code at many place.

Here is the way how you can save your time from writing same line of code again and again.


(1) Write it down on "General" Tab of your Toolbox
- if you are aware of toolbox then you probably knowing tabs under this toolbox. In Toolbox, for HTML view you will find different controls available in tree view style and tabs are like "Standard", "Data", etc.. are available (below screenshot).

- You will find one more tab that is "General". In general tab you can save your frequent line of code so that whenever you require them you can easily search from this Toolbox and get those line of code you require (Keyboard shortcut for Toolbox is Ctrl + Alt + X).To do this, just copy line of code you require frequently and paste that under "General" Tab of "Toolbox" and Once you paste, it will appear under your "General" Tab (below screenshot).



You can rename its title so that it will be easily searchable code for your reference. Once you paste this line of code, you will be able to see this at both "HTML" and "Code Behind" Toolbox view and use this line of code at both places.

(2) Use Code Snippet
Visual Studio provides code snippets in built so that you can use some code samples and you are not need to write that line of code.

To use Code Snippet just write down short name used for that snippet. So, let say you are about to create new property then write "prop" and hit "Tab" key and it will automatically insert line of code for property.


You will find some links from my previous post for Code Snippet in Visual Studio.

Monday, August 5, 2013

Working with Macro Parameter In Umbraco CMS

In your Partial View, if we are passing parameters then to fetch/pass value to parameters we can use following way.

code
:var data = Model.MacroParameters;

description: This will fetch the Macro Parameter associated with our partial view. This line of code are placed in your partial view.

Now, to fetch value of your paremeter value use following line of code
string Name = data.FirstOrDefault(c => c.Key == "ParameterName").Value.ToString(); 

"ParameterName" is the name of your parameter/property which is defined in partial view.

This will fetch value passed to parameter in your partial view and you can use this value to your internal function.                  



Monday, July 29, 2013

Working with Media Items in Umbraco CMS

Different ways of  fetching media items in Umbraco CMS
Following are some different ways of fetching Media items in Umbraco CMS.

(1) To get media by id user following line of code
code : var varMedia = new umbraco.cms.businesslogic.media.Media(1);
description: This will fetch details of the media item by its id, in above code item 1 is some media item and based on this id we can find details of this media file.
-- to get file value use following line of code, in this code "umbracoFile" is the name of the property which contains name of the file
var file = varMedia.getProperty("umbracoFile");
further, you can get value by following line item
string filename = (string)file.Value


(2) To get file placed at root location on Media
code: var media = Services.MediaService.GetRootMedia().FirstOrDefault(c => c.Name == "filename");
description: This line of code will get specified file in rootmedia
-- to get file value user following line of code
string filename = media.Properties["umbracoFile"].Value.ToString()

(3) To get all files of a folder in Media
-- First, fetch id of the media folder using following line of code
var media = Services.MediaService.GetRootMedia().Where(c => c.Name == "foldername").FirstOrDefault();
- You can also check here that the item that we found is file or folder using following line of code
media.ContentType.Alias == "Folder"
-- Get if of the folder
int ID = media.Id;
-- following line of code will get all childrens/subfiles of the specified folder id. 
IEnumerable mediaChildList = Services.MediaService.GetChildren(ID);
You can loop through the child items of folder and can get specific file details

(4) To get file name using umbraco namespace on Partial View.
This line of code coulde be written on partial view.

code: var rootNode = new Node(-1).Children;
var Mainlist = ((Node)(rootNode[0])).ChildrenAsList.FirstOrDefault(c => c.Name == "foldername");

description: above line of code will get root node with given folder name
-- to get a file from above line of code
var DetailList = Mainlist.ChildrenAsList.FirstOrDefault(c => c.Name == "filename");
-- using following line of code we can get url of the file name

var src = Umbraco.Media(Convert.ToInt32(@DetailList.GetProperty("thumbnail").Value)).umbracoFile;

(5) To get file name using umbraco namespace on Partial View with other way. 
code: var rootNode = new Node(-1).ChildrenAsList.FirstOrDefault(c => c.Name == "foldername");
description: above line of code will fetch folder with name specified
-- to get child items of the folder use following line of code
var list = rootNode.ChildrenAsList;
-- to get url of the file in above folder loop through the all items in list and if file name matches, use following line of code

@node.NiceUrl

We can also get first node of the Media using following line of code code:rootNode = new Node(-1).Children;
List list = rootNode[0].ChildrenAsList;
description: above line of code will get files from first node and fetches child items from this node.       

       


WCF Application - Optimizing Performance

Monday, July 4, 2011

Working with CheckBoxList

Here is some links about checkboxlist in VisualStudio.
CheckBoxList Control
(1) CheckBoxList Class

(2) ASP.NET : The checkbox and checkboxlist control

(3) CheckBoxList Control in ASP.NET

(4) Generic Way to Bind Enum With Different ASP.NET List Controls

(5) ASP.NET 4.0 New Feature- RepeatLayout property for CheckBoxList and RadioButtonList Controls.

(6) How to retrieve checkboxes values in jQuery

(7) Jquery to Get selected items from CheckBoxList

(8) JQuery to determine if all checkboxlists (in div) have been checked

(9) How to check if checkbox is checked using jQuery

CheckBoxList validation
(1) Creating a CheckBoxList validation control in C#

(2) CheckBoxList client side validation using JQuery

(3) Creating a Custom Validation Control in ASP.NET

CheckBoxList with LINQ
(1) ASP.Net CheckBoxList, Linq, and jQuery

(2) LINQ: Get all selected values of a CheckBoxList using a Lambda expression

(3) Get all values from CheckBoxList in C#

CheckBoxList with JQuery
(1) ASP.NET Checkboxlist get values in client side [JQuery]

(2) Toggle items in a CheckBoxList using jQuery

(3) How to select checkboxes in an ASP.NET CheckBoxList using jQuery

(4) Jquery and CheckboxList