content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the workspaces-2015-04-08.normal.json service model.
*/
using System;
using System.IO;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Amazon.WorkSpaces;
using Amazon.WorkSpaces.Model;
using Amazon.WorkSpaces.Model.Internal.MarshallTransformations;
using Amazon.Runtime.Internal.Transform;
using ServiceClientGenerator;
using AWSSDK_DotNet35.UnitTests.TestTools;
namespace AWSSDK_DotNet35.UnitTests.Marshalling
{
[TestClass]
public class WorkSpacesMarshallingTests
{
static readonly ServiceModel service_model = Utils.LoadServiceModel("workspaces");
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("WorkSpaces")]
public void AssociateIpGroupsMarshallTest()
{
var request = InstantiateClassGenerator.Execute<AssociateIpGroupsRequest>();
var marshaller = new AssociateIpGroupsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<AssociateIpGroupsRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("AssociateIpGroups").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = AssociateIpGroupsResponseUnmarshaller.Instance.Unmarshall(context)
as AssociateIpGroupsResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("WorkSpaces")]
public void AuthorizeIpRulesMarshallTest()
{
var request = InstantiateClassGenerator.Execute<AuthorizeIpRulesRequest>();
var marshaller = new AuthorizeIpRulesRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<AuthorizeIpRulesRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("AuthorizeIpRules").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = AuthorizeIpRulesResponseUnmarshaller.Instance.Unmarshall(context)
as AuthorizeIpRulesResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("WorkSpaces")]
public void CopyWorkspaceImageMarshallTest()
{
var request = InstantiateClassGenerator.Execute<CopyWorkspaceImageRequest>();
var marshaller = new CopyWorkspaceImageRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<CopyWorkspaceImageRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("CopyWorkspaceImage").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = CopyWorkspaceImageResponseUnmarshaller.Instance.Unmarshall(context)
as CopyWorkspaceImageResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("WorkSpaces")]
public void CreateIpGroupMarshallTest()
{
var request = InstantiateClassGenerator.Execute<CreateIpGroupRequest>();
var marshaller = new CreateIpGroupRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<CreateIpGroupRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("CreateIpGroup").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = CreateIpGroupResponseUnmarshaller.Instance.Unmarshall(context)
as CreateIpGroupResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("WorkSpaces")]
public void CreateTagsMarshallTest()
{
var request = InstantiateClassGenerator.Execute<CreateTagsRequest>();
var marshaller = new CreateTagsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<CreateTagsRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("CreateTags").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = CreateTagsResponseUnmarshaller.Instance.Unmarshall(context)
as CreateTagsResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("WorkSpaces")]
public void CreateWorkspacesMarshallTest()
{
var request = InstantiateClassGenerator.Execute<CreateWorkspacesRequest>();
var marshaller = new CreateWorkspacesRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<CreateWorkspacesRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("CreateWorkspaces").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = CreateWorkspacesResponseUnmarshaller.Instance.Unmarshall(context)
as CreateWorkspacesResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("WorkSpaces")]
public void DeleteIpGroupMarshallTest()
{
var request = InstantiateClassGenerator.Execute<DeleteIpGroupRequest>();
var marshaller = new DeleteIpGroupRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<DeleteIpGroupRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DeleteIpGroup").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = DeleteIpGroupResponseUnmarshaller.Instance.Unmarshall(context)
as DeleteIpGroupResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("WorkSpaces")]
public void DeleteTagsMarshallTest()
{
var request = InstantiateClassGenerator.Execute<DeleteTagsRequest>();
var marshaller = new DeleteTagsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<DeleteTagsRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DeleteTags").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = DeleteTagsResponseUnmarshaller.Instance.Unmarshall(context)
as DeleteTagsResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("WorkSpaces")]
public void DeleteWorkspaceImageMarshallTest()
{
var request = InstantiateClassGenerator.Execute<DeleteWorkspaceImageRequest>();
var marshaller = new DeleteWorkspaceImageRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<DeleteWorkspaceImageRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DeleteWorkspaceImage").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = DeleteWorkspaceImageResponseUnmarshaller.Instance.Unmarshall(context)
as DeleteWorkspaceImageResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("WorkSpaces")]
public void DeregisterWorkspaceDirectoryMarshallTest()
{
var request = InstantiateClassGenerator.Execute<DeregisterWorkspaceDirectoryRequest>();
var marshaller = new DeregisterWorkspaceDirectoryRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<DeregisterWorkspaceDirectoryRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DeregisterWorkspaceDirectory").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = DeregisterWorkspaceDirectoryResponseUnmarshaller.Instance.Unmarshall(context)
as DeregisterWorkspaceDirectoryResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("WorkSpaces")]
public void DescribeAccountMarshallTest()
{
var request = InstantiateClassGenerator.Execute<DescribeAccountRequest>();
var marshaller = new DescribeAccountRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<DescribeAccountRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DescribeAccount").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = DescribeAccountResponseUnmarshaller.Instance.Unmarshall(context)
as DescribeAccountResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("WorkSpaces")]
public void DescribeAccountModificationsMarshallTest()
{
var request = InstantiateClassGenerator.Execute<DescribeAccountModificationsRequest>();
var marshaller = new DescribeAccountModificationsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<DescribeAccountModificationsRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DescribeAccountModifications").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = DescribeAccountModificationsResponseUnmarshaller.Instance.Unmarshall(context)
as DescribeAccountModificationsResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("WorkSpaces")]
public void DescribeClientPropertiesMarshallTest()
{
var request = InstantiateClassGenerator.Execute<DescribeClientPropertiesRequest>();
var marshaller = new DescribeClientPropertiesRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<DescribeClientPropertiesRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DescribeClientProperties").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = DescribeClientPropertiesResponseUnmarshaller.Instance.Unmarshall(context)
as DescribeClientPropertiesResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("WorkSpaces")]
public void DescribeIpGroupsMarshallTest()
{
var request = InstantiateClassGenerator.Execute<DescribeIpGroupsRequest>();
var marshaller = new DescribeIpGroupsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<DescribeIpGroupsRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DescribeIpGroups").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = DescribeIpGroupsResponseUnmarshaller.Instance.Unmarshall(context)
as DescribeIpGroupsResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("WorkSpaces")]
public void DescribeTagsMarshallTest()
{
var request = InstantiateClassGenerator.Execute<DescribeTagsRequest>();
var marshaller = new DescribeTagsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<DescribeTagsRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DescribeTags").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = DescribeTagsResponseUnmarshaller.Instance.Unmarshall(context)
as DescribeTagsResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("WorkSpaces")]
public void DescribeWorkspaceBundlesMarshallTest()
{
var request = InstantiateClassGenerator.Execute<DescribeWorkspaceBundlesRequest>();
var marshaller = new DescribeWorkspaceBundlesRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<DescribeWorkspaceBundlesRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DescribeWorkspaceBundles").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = DescribeWorkspaceBundlesResponseUnmarshaller.Instance.Unmarshall(context)
as DescribeWorkspaceBundlesResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("WorkSpaces")]
public void DescribeWorkspaceDirectoriesMarshallTest()
{
var request = InstantiateClassGenerator.Execute<DescribeWorkspaceDirectoriesRequest>();
var marshaller = new DescribeWorkspaceDirectoriesRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<DescribeWorkspaceDirectoriesRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DescribeWorkspaceDirectories").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = DescribeWorkspaceDirectoriesResponseUnmarshaller.Instance.Unmarshall(context)
as DescribeWorkspaceDirectoriesResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("WorkSpaces")]
public void DescribeWorkspaceImagesMarshallTest()
{
var request = InstantiateClassGenerator.Execute<DescribeWorkspaceImagesRequest>();
var marshaller = new DescribeWorkspaceImagesRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<DescribeWorkspaceImagesRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DescribeWorkspaceImages").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = DescribeWorkspaceImagesResponseUnmarshaller.Instance.Unmarshall(context)
as DescribeWorkspaceImagesResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("WorkSpaces")]
public void DescribeWorkspacesMarshallTest()
{
var request = InstantiateClassGenerator.Execute<DescribeWorkspacesRequest>();
var marshaller = new DescribeWorkspacesRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<DescribeWorkspacesRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DescribeWorkspaces").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = DescribeWorkspacesResponseUnmarshaller.Instance.Unmarshall(context)
as DescribeWorkspacesResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("WorkSpaces")]
public void DescribeWorkspacesConnectionStatusMarshallTest()
{
var request = InstantiateClassGenerator.Execute<DescribeWorkspacesConnectionStatusRequest>();
var marshaller = new DescribeWorkspacesConnectionStatusRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<DescribeWorkspacesConnectionStatusRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DescribeWorkspacesConnectionStatus").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = DescribeWorkspacesConnectionStatusResponseUnmarshaller.Instance.Unmarshall(context)
as DescribeWorkspacesConnectionStatusResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("WorkSpaces")]
public void DescribeWorkspaceSnapshotsMarshallTest()
{
var request = InstantiateClassGenerator.Execute<DescribeWorkspaceSnapshotsRequest>();
var marshaller = new DescribeWorkspaceSnapshotsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<DescribeWorkspaceSnapshotsRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DescribeWorkspaceSnapshots").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = DescribeWorkspaceSnapshotsResponseUnmarshaller.Instance.Unmarshall(context)
as DescribeWorkspaceSnapshotsResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("WorkSpaces")]
public void DisassociateIpGroupsMarshallTest()
{
var request = InstantiateClassGenerator.Execute<DisassociateIpGroupsRequest>();
var marshaller = new DisassociateIpGroupsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<DisassociateIpGroupsRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DisassociateIpGroups").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = DisassociateIpGroupsResponseUnmarshaller.Instance.Unmarshall(context)
as DisassociateIpGroupsResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("WorkSpaces")]
public void ImportWorkspaceImageMarshallTest()
{
var request = InstantiateClassGenerator.Execute<ImportWorkspaceImageRequest>();
var marshaller = new ImportWorkspaceImageRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<ImportWorkspaceImageRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("ImportWorkspaceImage").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = ImportWorkspaceImageResponseUnmarshaller.Instance.Unmarshall(context)
as ImportWorkspaceImageResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("WorkSpaces")]
public void ListAvailableManagementCidrRangesMarshallTest()
{
var request = InstantiateClassGenerator.Execute<ListAvailableManagementCidrRangesRequest>();
var marshaller = new ListAvailableManagementCidrRangesRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<ListAvailableManagementCidrRangesRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("ListAvailableManagementCidrRanges").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = ListAvailableManagementCidrRangesResponseUnmarshaller.Instance.Unmarshall(context)
as ListAvailableManagementCidrRangesResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("WorkSpaces")]
public void MigrateWorkspaceMarshallTest()
{
var request = InstantiateClassGenerator.Execute<MigrateWorkspaceRequest>();
var marshaller = new MigrateWorkspaceRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<MigrateWorkspaceRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("MigrateWorkspace").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = MigrateWorkspaceResponseUnmarshaller.Instance.Unmarshall(context)
as MigrateWorkspaceResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("WorkSpaces")]
public void ModifyAccountMarshallTest()
{
var request = InstantiateClassGenerator.Execute<ModifyAccountRequest>();
var marshaller = new ModifyAccountRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<ModifyAccountRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("ModifyAccount").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = ModifyAccountResponseUnmarshaller.Instance.Unmarshall(context)
as ModifyAccountResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("WorkSpaces")]
public void ModifyClientPropertiesMarshallTest()
{
var request = InstantiateClassGenerator.Execute<ModifyClientPropertiesRequest>();
var marshaller = new ModifyClientPropertiesRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<ModifyClientPropertiesRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("ModifyClientProperties").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = ModifyClientPropertiesResponseUnmarshaller.Instance.Unmarshall(context)
as ModifyClientPropertiesResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("WorkSpaces")]
public void ModifySelfservicePermissionsMarshallTest()
{
var request = InstantiateClassGenerator.Execute<ModifySelfservicePermissionsRequest>();
var marshaller = new ModifySelfservicePermissionsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<ModifySelfservicePermissionsRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("ModifySelfservicePermissions").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = ModifySelfservicePermissionsResponseUnmarshaller.Instance.Unmarshall(context)
as ModifySelfservicePermissionsResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("WorkSpaces")]
public void ModifyWorkspaceAccessPropertiesMarshallTest()
{
var request = InstantiateClassGenerator.Execute<ModifyWorkspaceAccessPropertiesRequest>();
var marshaller = new ModifyWorkspaceAccessPropertiesRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<ModifyWorkspaceAccessPropertiesRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("ModifyWorkspaceAccessProperties").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = ModifyWorkspaceAccessPropertiesResponseUnmarshaller.Instance.Unmarshall(context)
as ModifyWorkspaceAccessPropertiesResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("WorkSpaces")]
public void ModifyWorkspaceCreationPropertiesMarshallTest()
{
var request = InstantiateClassGenerator.Execute<ModifyWorkspaceCreationPropertiesRequest>();
var marshaller = new ModifyWorkspaceCreationPropertiesRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<ModifyWorkspaceCreationPropertiesRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("ModifyWorkspaceCreationProperties").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = ModifyWorkspaceCreationPropertiesResponseUnmarshaller.Instance.Unmarshall(context)
as ModifyWorkspaceCreationPropertiesResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("WorkSpaces")]
public void ModifyWorkspacePropertiesMarshallTest()
{
var request = InstantiateClassGenerator.Execute<ModifyWorkspacePropertiesRequest>();
var marshaller = new ModifyWorkspacePropertiesRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<ModifyWorkspacePropertiesRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("ModifyWorkspaceProperties").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = ModifyWorkspacePropertiesResponseUnmarshaller.Instance.Unmarshall(context)
as ModifyWorkspacePropertiesResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("WorkSpaces")]
public void ModifyWorkspaceStateMarshallTest()
{
var request = InstantiateClassGenerator.Execute<ModifyWorkspaceStateRequest>();
var marshaller = new ModifyWorkspaceStateRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<ModifyWorkspaceStateRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("ModifyWorkspaceState").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = ModifyWorkspaceStateResponseUnmarshaller.Instance.Unmarshall(context)
as ModifyWorkspaceStateResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("WorkSpaces")]
public void RebootWorkspacesMarshallTest()
{
var request = InstantiateClassGenerator.Execute<RebootWorkspacesRequest>();
var marshaller = new RebootWorkspacesRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<RebootWorkspacesRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("RebootWorkspaces").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = RebootWorkspacesResponseUnmarshaller.Instance.Unmarshall(context)
as RebootWorkspacesResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("WorkSpaces")]
public void RebuildWorkspacesMarshallTest()
{
var request = InstantiateClassGenerator.Execute<RebuildWorkspacesRequest>();
var marshaller = new RebuildWorkspacesRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<RebuildWorkspacesRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("RebuildWorkspaces").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = RebuildWorkspacesResponseUnmarshaller.Instance.Unmarshall(context)
as RebuildWorkspacesResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("WorkSpaces")]
public void RegisterWorkspaceDirectoryMarshallTest()
{
var request = InstantiateClassGenerator.Execute<RegisterWorkspaceDirectoryRequest>();
var marshaller = new RegisterWorkspaceDirectoryRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<RegisterWorkspaceDirectoryRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("RegisterWorkspaceDirectory").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = RegisterWorkspaceDirectoryResponseUnmarshaller.Instance.Unmarshall(context)
as RegisterWorkspaceDirectoryResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("WorkSpaces")]
public void RestoreWorkspaceMarshallTest()
{
var request = InstantiateClassGenerator.Execute<RestoreWorkspaceRequest>();
var marshaller = new RestoreWorkspaceRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<RestoreWorkspaceRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("RestoreWorkspace").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = RestoreWorkspaceResponseUnmarshaller.Instance.Unmarshall(context)
as RestoreWorkspaceResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("WorkSpaces")]
public void RevokeIpRulesMarshallTest()
{
var request = InstantiateClassGenerator.Execute<RevokeIpRulesRequest>();
var marshaller = new RevokeIpRulesRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<RevokeIpRulesRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("RevokeIpRules").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = RevokeIpRulesResponseUnmarshaller.Instance.Unmarshall(context)
as RevokeIpRulesResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("WorkSpaces")]
public void StartWorkspacesMarshallTest()
{
var request = InstantiateClassGenerator.Execute<StartWorkspacesRequest>();
var marshaller = new StartWorkspacesRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<StartWorkspacesRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("StartWorkspaces").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = StartWorkspacesResponseUnmarshaller.Instance.Unmarshall(context)
as StartWorkspacesResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("WorkSpaces")]
public void StopWorkspacesMarshallTest()
{
var request = InstantiateClassGenerator.Execute<StopWorkspacesRequest>();
var marshaller = new StopWorkspacesRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<StopWorkspacesRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("StopWorkspaces").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = StopWorkspacesResponseUnmarshaller.Instance.Unmarshall(context)
as StopWorkspacesResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("WorkSpaces")]
public void TerminateWorkspacesMarshallTest()
{
var request = InstantiateClassGenerator.Execute<TerminateWorkspacesRequest>();
var marshaller = new TerminateWorkspacesRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<TerminateWorkspacesRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("TerminateWorkspaces").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = TerminateWorkspacesResponseUnmarshaller.Instance.Unmarshall(context)
as TerminateWorkspacesResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("WorkSpaces")]
public void UpdateRulesOfIpGroupMarshallTest()
{
var request = InstantiateClassGenerator.Execute<UpdateRulesOfIpGroupRequest>();
var marshaller = new UpdateRulesOfIpGroupRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<UpdateRulesOfIpGroupRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("UpdateRulesOfIpGroup").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = UpdateRulesOfIpGroupResponseUnmarshaller.Instance.Unmarshall(context)
as UpdateRulesOfIpGroupResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
}
} | 51.157595 | 165 | 0.64813 | [
"Apache-2.0"
] | NGL321/aws-sdk-net | sdk/test/Services/WorkSpaces/UnitTests/Generated/Marshalling/WorkSpacesMarshallingTests.cs | 62,975 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using Entidades;
namespace Testeos
{
[TestClass]
public class Test_TP4
{
[TestMethod]
public void ContarPalabras_CuandoRecibeDosPalabras_DeberiaRetornarNumeroDos()
{
//Arrange
string texto = "Hola Mundo";
int expected = 2;
//Act
int actual = texto.ContarPalabras();
//Assert
Assert.AreEqual(expected, actual);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void ContarPalabras_RecibeUnStringVacio_DeberiaLanzarArgumentException()
{
//Arrange
string str = string.Empty;
//Act
int actual = str.ContarPalabras();
}
[TestMethod]
public void ContarPalabras_CuandoRecibePalabrasSeparadasPorGuion_DeberiaRetornarDos()
{
//Arrange
string texto = "Hola-Mundo";
int expected = 2;
//Act
int actual = texto.ContarPalabras();
//Assert
Assert.AreEqual(expected, actual);
}
}
}
| 24.875 | 93 | 0.567839 | [
"MIT"
] | tomasfriz/TPs-DE-LABORATORIO-2 | TP 4/Proyecto/Testeos/Test_TP4.cs | 1,196 | C# |
using BorderControl.Interfaces;
using System;
using System.Collections.Generic;
using System.Text;
namespace BorderControl
{
public class Citizen : IIdentifiable, IBirthtable, IAgeable, INameable, IBuyer
{
public Citizen(string name, string age, string id, string birthdate)
{
this.Name = name;
this.Age = age;
this.Id = id;
this.Birthdate = birthdate;
this.Food = 0;
}
public string Name { get; private set; }
public string Id { get; private set; }
public string Birthdate { get; private set; }
public string Age { get; private set; }
public int Food { get; private set; }
public void BuyFood()
{
this.Food += 10;
}
}
}
| 22.885714 | 82 | 0.570537 | [
"MIT"
] | BorislavVladimirov/C-Software-University | C# OOP June 2019/InterfacesAndAbstractionEx/BorderControl/Models/Citizen.cs | 803 | C# |
using QAToolKit.Core.Helpers;
using QAToolKit.Core.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace QAToolKit.Core.HttpRequestTools
{
/// <summary>
/// Http Url generator
/// </summary>
public class HttpRequestUrlGenerator
{
private readonly HttpRequest _httpRequest;
private readonly DataReplacementOptions _dataReplacerOptions;
/// <summary>
/// Http Url generator
/// </summary>
/// <param name="httpRequest"></param>
/// <param name="dataReplacerOptions"></param>
public HttpRequestUrlGenerator(HttpRequest httpRequest, Action<DataReplacementOptions> dataReplacerOptions = null)
{
_httpRequest = httpRequest ?? throw new ArgumentNullException(nameof(httpRequest));
_dataReplacerOptions = new DataReplacementOptions();
dataReplacerOptions?.Invoke(_dataReplacerOptions);
}
/// <summary>
/// Get url with parameters
/// </summary>
/// <returns></returns>
public string GetUrl()
{
var url = new StringBuilder();
if (!_httpRequest.BasePath.EndsWith("/"))
{
url.Append($"{_httpRequest.BasePath}/");
}
else
{
url.Append(_httpRequest.BasePath);
}
string rawPath = GetPath();
url.Append(rawPath);
var rawQuery = GetQuery();
url.Append(rawQuery);
return $"{url}";
}
/// <summary>
/// Get query parameters
/// </summary>
/// <returns></returns>
private string GetQuery()
{
var queryParts = new List<string>();
foreach (var parameter in _httpRequest.Parameters.Where(kind => kind.Location == Location.Query))
{
if (parameter.Value != null && !HasReplaceValue(parameter.Name))
{
queryParts.Add($"{parameter.Name}={parameter.Value}");
}
else
{
if (_dataReplacerOptions.ReplacementValues != null)
{
var replacementValue = _dataReplacerOptions.ReplacementValues?.GetValue(parameter.Name);
if (replacementValue != null)
{
var type = replacementValue.GetType();
if (type.Equals(typeof(Dictionary<string, string>)))
{
queryParts.Add(GenerateQueryParameters((Dictionary<string, string>)replacementValue));
}
else if (type.Equals(typeof(string[])))
{
var tmp = (string[])replacementValue;
queryParts.Add($"{string.Join("&", tmp.Select(item => $"{parameter.Name}={item}"))}");
}
else if (type.Equals(typeof(int[])))
{
var tmp = (int[])replacementValue;
queryParts.Add($"{string.Join("&", tmp.Select(item => $"{parameter.Name}={item}"))}");
}
else
{
queryParts.Add($"{parameter.Name}={replacementValue}");
}
}
}
else
{
if (parameter.Required)
queryParts.Add($"{parameter.Name}={{{parameter.Name}}}");
}
}
}
if (queryParts.Count == 0)
{
return String.Empty;
}
var query = string.Join("&", queryParts);
if (!query.ToString().StartsWith("?"))
{
return $"?{query}";
}
else
{
return $"{query}";
}
}
private bool HasReplaceValue(string valueName)
{
if (_dataReplacerOptions.ReplacementValues != null)
{
return _dataReplacerOptions.ReplacementValues.KeyExists(valueName);
}
return false;
}
/// <summary>
/// Replace Url path parameters
/// </summary>
/// <returns></returns>
private string GetPath()
{
string path = _httpRequest.Path;
if (_dataReplacerOptions.ReplacementValues != null)
{
foreach (var replacementValue in _dataReplacerOptions.ReplacementValues)
{
var type = replacementValue.Value.GetType();
if (path.ContainsCaseInsensitive($"{{{replacementValue.Key}}}") && (type.Equals(typeof(string)) || type.IsPrimitive))
{
path = path.Replace("{" + replacementValue.Key + "}", replacementValue.Value.ToString());
}
}
}
if (path.StartsWith("/"))
{
path = path.Substring(1, path.Length - 1);
}
return path;
}
private static string GenerateQueryParameters(Dictionary<string, string> keyValuePairs)
{
var parameters = new List<string>();
foreach (var item in keyValuePairs)
{
parameters.Add($"{item.Key}={item.Value},");
}
return string.Join(",", parameters);
}
}
}
| 32.847458 | 137 | 0.463536 | [
"MIT"
] | qatoolkit/qatoolkit-core-net | src/QAToolKit.Core/HttpRequestTools/HttpRequestUrlGenerator.cs | 5,816 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CursorManager : MonoBehaviour
{
public Texture2D idleCursor, activeCursor;
public CursorMode cursorMode = CursorMode.Auto;
public Vector2 hotSpot = Vector2.zero;
private void Start()
{
Cursor.SetCursor(idleCursor, hotSpot, cursorMode);
}
private void Update()
{
if (Input.GetMouseButton (0))
{
Cursor.SetCursor(activeCursor, hotSpot, cursorMode);
}
else if (Input.GetMouseButtonUp(0))
{
Cursor.SetCursor(idleCursor, hotSpot, cursorMode);
}
}
}
| 24.222222 | 64 | 0.646789 | [
"MIT"
] | samsheffield/2D_Level_And_Narrative_Design | Week 3/Assets/Scripts/CursorManager.cs | 654 | C# |
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Exelor.Dto;
using Exelor.Infrastructure.Data;
using FluentValidation;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace Exelor.Features.Users
{
public class UpdateUser
{
public class Command : IRequest<UserDetailsDto>
{
private Command() {}
public Command(
int id,
string firstName,
string lastName)
{
Id = id;
FirstName = firstName;
LastName = lastName;
}
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class CommandValidator : AbstractValidator<Command>
{
public CommandValidator()
{
RuleFor(x => x.Id).NotNull().NotEmpty();
RuleFor(x => x.FirstName).NotNull().NotEmpty();
}
}
public class Handler : IRequestHandler<Command, UserDetailsDto>
{
private readonly ApplicationDbContext _dbContext;
public Handler(
ApplicationDbContext dbContext)
{
_dbContext = dbContext;
}
public async Task<UserDetailsDto> Handle(
Command request,
CancellationToken cancellationToken)
{
var user = await _dbContext.Users
.Include(x => x.Roles)
.ThenInclude(x => x.Role)
.FirstAsync(
x => x.Id == request.Id,
cancellationToken);
user.FirstName = request.FirstName;
user.LastName = request.LastName;
await _dbContext.SaveChangesAsync(cancellationToken);
return new UserDetailsDto(
user.Id,
user.FirstName,
user.LastName,
user.FullName,
user.Email,
string.Join(", ", user.Roles.Select(r => r.Role.Name)));
}
}
}
} | 29.077922 | 76 | 0.497544 | [
"MIT"
] | simplyvinay/exelorlib | Sample.Api/Features/Users/UpdateUser.cs | 2,241 | C# |
using Coldairarrow.Util;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text.RegularExpressions;
namespace Coldairarrow.DataRepository
{
/// <summary>
/// 描述:数据库仓储基类类
/// 作者:Coldairarrow
/// </summary>
/// <seealso cref="IRepository" />
public class DbRepository : IRepository
{
#region 构造函数
/// <summary>
/// 构造函数
/// </summary>
/// <param name="conString">构造参数,可以为数据库连接字符串或者DbContext</param>
/// <param name="dbType">数据库类型</param>
public DbRepository(string conString, DatabaseType dbType)
{
ConnectionString = conString;
DbType = dbType;
}
#endregion
#region 私有成员
protected IRepositoryDbContext Db
{
get
{
if (_disposed || _db == null)
{
_db = DbFactory.GetDbContext(ConnectionString, DbType);
_disposed = false;
}
return _db;
}
set
{
_db = value;
}
}
private IRepositoryDbContext _db { get; set; }
protected bool _disposed { get; set; }
protected DbTransaction _transaction { get; set; }
protected static PropertyInfo GetKeyProperty(Type type)
{
return GetKeyPropertys(type).FirstOrDefault();
}
protected static List<PropertyInfo> GetKeyPropertys(Type type)
{
var properties = type
.GetProperties()
.Where(x => x.GetCustomAttributes(true).Select(o => o.GetType().FullName).Contains(typeof(KeyAttribute).FullName))
.ToList();
return properties;
}
protected string GetDbTableName(Type type)
{
string tableName = string.Empty;
var tableAttribute = type.GetCustomAttribute<TableAttribute>();
if (tableAttribute != null)
tableName = tableAttribute.Name;
else
tableName = type.Name;
return tableName;
}
private void PackWork(IEnumerable<Type> entityTypes, Action work)
{
entityTypes.ForEach(x => Db.CheckEntityType(x));
if (_openedTransaction)
_transactionHandler += work;
else
{
work();
CommitDb();
Dispose();
}
}
private void PackWork(Type entityType, Action work)
{
PackWork(new List<Type> { entityType }, work);
}
protected bool _openedTransaction { get; set; } = false;
protected Action _transactionHandler { get; set; }
private ITransaction _BeginTransaction(IsolationLevel? isolationLevel = null)
{
_openedTransaction = true;
if (isolationLevel == null)
_transaction = Db.Database.BeginTransaction().GetDbTransaction();
else
_transaction = Db.Database.BeginTransaction(isolationLevel.Value).GetDbTransaction();
Db.UseTransaction(_transaction);
return this;
}
private Action<string> _HandleSqlLog { get; set; }
protected virtual string FormatFieldName(string name)
{
throw new NotImplementedException("请在子类实现!");
}
protected virtual string FormatParamterName(string name)
{
return $"@{name}";
}
private (string sql, IReadOnlyDictionary<string, object> paramters) GetWhereSql<T>(IQueryable<T> query) where T : class, new()
{
var querySql = query.ToSql();
string theQSql = querySql.sql.Replace("\r\n", "\n").Replace("\n", " ");
string pattern = "^SELECT.*?FROM.*? AS (.*?) WHERE .*?$";
var match = Regex.Match(theQSql, pattern);
string asTmp = match.Groups[1]?.ToString();
string whereSql = querySql.sql.Split(new string[] { "WHERE" }, StringSplitOptions.None)[1].Replace($"{asTmp}.", "");
return (whereSql, querySql.parameters);
}
#endregion
#region 事物相关
/// <summary>
/// 开始事物
/// </summary>
public ITransaction BeginTransaction()
{
return _BeginTransaction();
}
/// <summary>
/// 开始事物
/// 注:自定义事物级别
/// </summary>
/// <param name="isolationLevel">事物级别</param>
public ITransaction BeginTransaction(IsolationLevel isolationLevel)
{
return _BeginTransaction(isolationLevel);
}
/// <summary>
/// 结束事物
/// </summary>
/// <returns></returns>
public (bool Success, Exception ex) EndTransaction()
{
bool success = true;
Exception resEx = null;
try
{
CommitDb();
CommitTransaction();
}
catch (Exception ex)
{
success = false;
resEx = ex;
RollbackTransaction();
}
finally
{
Dispose();
}
return (success, resEx);
}
#endregion
#region 数据库相关
/// <summary>
/// 连接字符串
/// </summary>
public string ConnectionString { get; }
/// <summary>
/// 数据库类型
/// </summary>
public DatabaseType DbType { get; }
/// <summary>
/// 提交到数据库
/// </summary>
public void CommitDb()
{
_transactionHandler?.Invoke();
Db.SaveChanges();
}
/// <summary>
/// 提交事物
/// </summary>
public void CommitTransaction()
{
_transaction?.Commit();
}
/// <summary>
/// 回滚事物
/// </summary>
public void RollbackTransaction()
{
_transaction?.Rollback();
}
/// <summary>
/// 获取DbContext
/// </summary>
/// <returns></returns>
public DbContext GetDbContext()
{
return Db.GetDbContext();
}
/// <summary>
/// SQL日志处理方法
/// </summary>
/// <value>
/// The handle SQL log.
/// </value>
public Action<string> HandleSqlLog { set => EFCoreSqlLogeerProvider.HandleSqlLog = value; }
/// <summary>
/// 使用已存在的事物
/// </summary>
/// <param name="transaction">事物对象</param>
public void UseTransaction(DbTransaction transaction)
{
if (_transaction != null)
_transaction.Dispose();
_openedTransaction = true;
_transaction = transaction;
Db.UseTransaction(transaction);
}
/// <summary>
/// 获取事物对象
/// </summary>
/// <returns></returns>
public DbTransaction GetTransaction()
{
return _transaction;
}
#endregion
#region 增加数据
/// <summary>
/// 添加单条记录
/// </summary>
/// <typeparam name="T">实体泛型</typeparam>
/// <param name="entity">实体对象</param>
public void Insert<T>(T entity) where T : class, new()
{
Insert(new List<object> { entity });
}
/// <summary>
/// 添加多条记录
/// </summary>
/// <typeparam name="T">实体泛型</typeparam>
/// <param name="entities">实体对象集合</param>
public void Insert<T>(List<T> entities) where T : class, new()
{
Insert(entities.CastToList<object>());
}
/// <summary>
/// 添加多条记录
/// </summary>
/// <param name="entities">对象集合</param>
public void Insert(List<object> entities)
{
PackWork(entities.Select(x => x.GetType()), () =>
{
entities.ForEach(x => Db.Entry(x).State = EntityState.Added);
});
}
/// <summary>
/// 使用Bulk批量导入,速度快
/// </summary>
/// <typeparam name="T">实体泛型</typeparam>
/// <param name="entities">实体集合</param>
/// <exception cref="NotImplementedException">不支持此操作!</exception>
public virtual void BulkInsert<T>(List<T> entities) where T : class, new()
{
throw new NotImplementedException("不支持此操作!");
}
#endregion
#region 删除数据
/// <summary>
/// 删除所有记录
/// </summary>
/// <typeparam name="T">实体泛型</typeparam>
public virtual void DeleteAll<T>() where T : class, new()
{
DeleteAll(typeof(T));
}
/// <summary>
/// 删除所有记录
/// </summary>
/// <param name="type">实体类型</param>
public virtual void DeleteAll(Type type)
{
string tableName = GetDbTableName(type);
string sql = $"DELETE FROM {FormatFieldName(tableName)}";
ExecuteSql(sql);
}
/// <summary>
/// 删除单条记录
/// </summary>
/// <typeparam name="T">实体泛型</typeparam>
/// <param name="entity">实体对象</param>
public void Delete<T>(T entity) where T : class, new()
{
Delete(new List<object> { entity });
}
/// <summary>
/// 删除多条记录
/// </summary>
/// <typeparam name="T">实体泛型</typeparam>
/// <param name="entities">实体对象集合</param>
public void Delete<T>(List<T> entities) where T : class, new()
{
Delete(entities.CastToList<object>());
}
/// <summary>
/// 删除多条记录
/// </summary>
/// <param name="entities">实体对象集合</param>
public void Delete(List<object> entities)
{
PackWork(entities.Select(x => x.GetType()), () =>
{
entities.ForEach(x => Db.Entry(x).State = EntityState.Deleted);
});
}
/// <summary>
/// 按条件删除记录
/// </summary>
/// <typeparam name="T">实体泛型</typeparam>
/// <param name="condition">筛选条件</param>
public void Delete<T>(Expression<Func<T, bool>> condition) where T : class, new()
{
var deleteList = GetIQueryable<T>().Where(condition).ToList();
Delete(deleteList);
}
/// <summary>
/// 删除单条记录
/// </summary>
/// <typeparam name="T">实体泛型</typeparam>
/// <param name="key">主键</param>
public void Delete<T>(string key) where T : class, new()
{
Delete<T>(new List<string> { key });
}
/// <summary>
/// 删除多条记录
/// </summary>
/// <typeparam name="T">实体泛型</typeparam>
/// <param name="keys">多条记录主键集合</param>
public void Delete<T>(List<string> keys) where T : class, new()
{
Delete(typeof(T), keys);
}
/// <summary>
/// 删除单条记录
/// </summary>
/// <param name="type">实体类型</param>
/// <param name="key">主键</param>
public void Delete(Type type, string key)
{
Delete(type, new List<string> { key });
}
/// <summary>
/// 删除多条记录
/// </summary>
/// <param name="type">实体类型</param>
/// <param name="keys">多条记录主键集合</param>
/// <exception cref="Exception">该实体没有主键标识!请使用[Key]标识主键!</exception>
public void Delete(Type type, List<string> keys)
{
var theProperty = GetKeyProperty(type);
if (theProperty == null)
throw new Exception("该实体没有主键标识!请使用[Key]标识主键!");
List<object> deleteList = new List<object>();
keys.ForEach(aKey =>
{
object newData = Activator.CreateInstance(type);
var value = aKey.ChangeType(theProperty.PropertyType);
theProperty.SetValue(newData, value);
deleteList.Add(newData);
});
Delete(deleteList);
}
/// <summary>
/// 使用SQL语句按照条件删除数据
/// 用法:Delete_Sql"Base_User"(x=>x.Id == "Admin")
/// 注:生成的SQL类似于DELETE FROM [Base_User] WHERE [Name] = 'xxx' WHERE [Id] = 'Admin'
/// </summary>
/// <typeparam name="T">实体泛型</typeparam>
/// <param name="where">条件</param>
/// <returns>
/// 影响条数
/// </returns>
public int Delete_Sql<T>(Expression<Func<T, bool>> where) where T : class, new()
{
string tableName = typeof(T).Name;
DbProviderFactory dbProviderFactory = DbProviderFactoryHelper.GetDbProviderFactory(DbType);
var whereSql = GetWhereSql(GetIQueryable<T>().Where(where));
var paramters = whereSql.paramters.Select(x =>
{
var newParamter = dbProviderFactory.CreateParameter();
newParamter.ParameterName = x.Key;
newParamter.Value = x.Value;
return newParamter;
}).ToList();
string sql = $"DELETE FROM {FormatFieldName(tableName)} WHERE {whereSql.sql}";
return ExecuteSql(sql, paramters);
}
#endregion
#region 更新数据
/// <summary>
/// 更新单条记录
/// </summary>
/// <typeparam name="T">实体泛型</typeparam>
/// <param name="entity">实体对象</param>
public void Update<T>(T entity) where T : class, new()
{
Update(new List<object> { entity });
}
/// <summary>
/// 更新多条记录
/// </summary>
/// <typeparam name="T">实体泛型</typeparam>
/// <param name="entities">实体对象集合</param>
public void Update<T>(List<T> entities) where T : class, new()
{
Update(entities.CastToList<object>());
}
/// <summary>
/// 更新多条记录
/// </summary>
/// <param name="entities">实体对象集合</param>
public void Update(List<object> entities)
{
PackWork(entities.Select(x => x.GetType()), () =>
{
entities.ForEach(x => Db.Entry(x).State = EntityState.Modified);
});
}
/// <summary>
/// 更新单条记录的某些属性
/// </summary>
/// <typeparam name="T">实体泛型</typeparam>
/// <param name="entity">实体对象</param>
/// <param name="properties">属性</param>
public void UpdateAny<T>(T entity, List<string> properties) where T : class, new()
{
UpdateAny(new List<object> { entity }, properties);
}
/// <summary>
/// 更新多条记录的某些属性
/// </summary>
/// <typeparam name="T">实体泛型</typeparam>
/// <param name="entities">实体对象集合</param>
/// <param name="properties">属性</param>
public void UpdateAny<T>(List<T> entities, List<string> properties) where T : class, new()
{
UpdateAny(entities.CastToList<object>(), properties);
}
/// <summary>
/// 更新多条记录的某些属性
/// </summary>
/// <param name="entities">实体对象集合</param>
/// <param name="properties">属性</param>
public void UpdateAny(List<object> entities, List<string> properties)
{
PackWork(entities.Select(x => x.GetType()), () =>
{
entities.ForEach(aEntity =>
{
var targetObj = aEntity.ChangeType(Db.CheckEntityType(aEntity.GetType()));
Db.Attach(targetObj);
properties.ForEach(aProperty =>
{
Db.Entry(targetObj).Property(aProperty).IsModified = true;
});
});
});
}
/// <summary>
/// 按照条件更新记录
/// </summary>
/// <typeparam name="T">实体泛型</typeparam>
/// <param name="whereExpre">筛选条件</param>
/// <param name="set">更新操作</param>
public void UpdateWhere<T>(Expression<Func<T, bool>> whereExpre, Action<T> set) where T : class, new()
{
var list = GetIQueryable<T>().Where(whereExpre).ToList();
list.ForEach(aData => set(aData));
Update(list);
}
/// <summary>
/// 使用SQL语句按照条件更新
/// 用法:UpdateWhere_Sql"Base_User"(x=>x.Id == "Admin",("Name","小明"))
/// 注:生成的SQL类似于UPDATE [TABLE] SET [Name] = 'xxx' WHERE [Id] = 'Admin'
/// </summary>
/// <typeparam name="T">实体类型</typeparam>
/// <param name="where">筛选条件</param>
/// <param name="values">字段值设置</param>
/// <returns>
/// 影响条数
/// </returns>
public int UpdateWhere_Sql<T>(Expression<Func<T, bool>> where, params (string field, object value)[] values) where T : class, new()
{
string tableName = typeof(T).Name;
DbProviderFactory dbProviderFactory = DbProviderFactoryHelper.GetDbProviderFactory(DbType);
List<KeyValuePair<string, object>> parameterList = new List<KeyValuePair<string, object>>();
var whereSql = GetWhereSql(GetIQueryable<T>().Where(where));
parameterList.AddRange(whereSql.paramters.ToArray());
List<string> propertySetStr = new List<string>();
values.ToList().ForEach(aProperty =>
{
var paramterName = FormatParamterName($"_p_{aProperty.field}");
parameterList.Add(new KeyValuePair<string, object>(paramterName, aProperty.value));
propertySetStr.Add($" {FormatFieldName(aProperty.field)} = {paramterName} ");
});
var paramters = parameterList.Select(x =>
{
var newParamter = dbProviderFactory.CreateParameter();
newParamter.ParameterName = x.Key;
newParamter.Value = x.Value;
return newParamter;
}).ToList();
string sql = $"UPDATE {FormatFieldName(tableName)} SET {string.Join(",", propertySetStr)} WHERE {whereSql.sql}";
return ExecuteSql(sql, paramters);
}
#endregion
#region 查询数据
/// <summary>
/// 获取单条记录
/// </summary>
/// <typeparam name="T">实体泛型</typeparam>
/// <param name="keyValue">主键</param>
/// <returns></returns>
public T GetEntity<T>(params object[] keyValue) where T : class, new()
{
var obj = Db.Set<T>().Find(keyValue);
if (!obj.IsNullOrEmpty())
Db.Entry(obj).State = EntityState.Detached;
return obj;
}
/// <summary>
/// 获取所有数据
/// </summary>
/// <typeparam name="T">实体泛型</typeparam>
/// <returns></returns>
public List<T> GetList<T>() where T : class, new()
{
return GetIQueryable<T>().ToList();
}
/// <summary>
/// 获取列表
/// </summary>
/// <param name="type">实体类型</param>
/// <returns></returns>
public List<object> GetList(Type type)
{
return GetIQueryable(type).CastToList<object>();
}
/// <summary>
/// 获取IQueryable
/// 注:默认取消实体追踪
/// </summary>
/// <typeparam name="T">实体泛型</typeparam>
/// <returns></returns>
public IQueryable<T> GetIQueryable<T>() where T : class, new()
{
return GetIQueryable(typeof(T)) as IQueryable<T>;
}
/// <summary>
/// 获取IQueryable
/// 注:默认取消实体追踪
/// </summary>
/// <param name="type">实体泛型</param>
/// <returns></returns>
public IQueryable GetIQueryable(Type type)
{
return Db.GetIQueryable(type);
}
/// <summary>
/// 通过SQL获取DataTable
/// </summary>
/// <param name="sql">SQL语句</param>
/// <returns></returns>
public DataTable GetDataTableWithSql(string sql)
{
return GetDataTableWithSql(sql, null);
}
/// <summary>
/// 通过SQL获取DataTable
/// </summary>
/// <param name="sql">SQL语句</param>
/// <param name="parameters">SQL参数</param>
/// <returns></returns>
public DataTable GetDataTableWithSql(string sql, List<DbParameter> parameters)
{
DbProviderFactory dbProviderFactory = DbProviderFactoryHelper.GetDbProviderFactory(DbType);
using (DbConnection conn = dbProviderFactory.CreateConnection())
{
conn.ConnectionString = ConnectionString;
if (conn.State != ConnectionState.Open)
{
conn.Open();
}
using (DbCommand cmd = conn.CreateCommand())
{
cmd.Connection = conn;
cmd.CommandText = sql;
cmd.CommandTimeout = 5 * 60;
if (parameters != null && parameters?.Count > 0)
cmd.Parameters.AddRange(parameters.ToArray());
DbDataAdapter adapter = dbProviderFactory.CreateDataAdapter();
adapter.SelectCommand = cmd;
DataSet table = new DataSet();
adapter.Fill(table);
cmd.Parameters.Clear();
return table.Tables[0];
}
}
}
/// <summary>
/// 通过SQL获取List
/// </summary>
/// <typeparam name="T">实体泛型</typeparam>
/// <param name="sqlStr">SQL语句</param>
/// <returns></returns>
public List<T> GetListBySql<T>(string sqlStr) where T : class, new()
{
return GetListBySql<T>(sqlStr, new List<DbParameter>());
}
/// <summary>
/// 通过SQL获取List
/// </summary>
/// <typeparam name="T">实体泛型</typeparam>
/// <param name="sqlStr">SQL语句</param>
/// <param name="parameters">SQL参数</param>
/// <returns></returns>
public List<T> GetListBySql<T>(string sqlStr, List<DbParameter> parameters) where T : class, new()
{
return Db.Set<T>().FromSql(sqlStr, parameters.ToArray()).ToList();
}
#endregion
#region 执行Sql语句
/// <summary>
/// 执行SQL语句
/// </summary>
/// <param name="sql">SQL语句</param>
public int ExecuteSql(string sql)
{
int count = Db.Database.ExecuteSqlCommand(sql);
if (!_openedTransaction)
Dispose();
return count;
}
/// <summary>
/// 执行SQL语句
/// </summary>
/// <param name="sql">SQL语句</param>
/// <param name="parameters">SQL参数</param>
public int ExecuteSql(string sql, List<DbParameter> parameters)
{
int count = Db.Database.ExecuteSqlCommand(sql, parameters.ToArray());
if (!_openedTransaction)
Dispose();
return count;
}
#endregion
#region Dispose
protected virtual void Dispose(bool disposing)
{
if (_disposed)
return;
if (disposing)
{
_transaction?.Dispose();
Db?.Dispose();
}
_openedTransaction = false;
_transactionHandler = null;
_disposed = true;
}
~DbRepository()
{
Dispose(false);
}
/// <summary>
/// 执行与释放或重置非托管资源关联的应用程序定义的任务。
/// </summary>
public void Dispose()
{
Dispose(true);
//GC.SuppressFinalize(this);
}
#endregion
}
}
| 30.23875 | 139 | 0.50308 | [
"MIT"
] | celonyang/Colder.Fx.Core.AdminLTE | src/Coldairarrow.DataRepository/Repository/DbRepository.cs | 25,657 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("ExpressionParser")]
[assembly: AssemblyDescription("A C# expression parser for a single line string input.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Andre Vianna")]
[assembly: AssemblyProduct("ExpressionParser")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("869cdc74-f58f-4600-8636-d0b0cccd4416")]
[assembly: AssemblyVersion("1.2.2")]
| 39.066667 | 90 | 0.754266 | [
"MIT"
] | AndreVianna/ExpressionParser | ExpressionParser/Properties/AssemblyInfo.cs | 589 | C# |
namespace Core.MessageSpace
{
/// <summary>
/// Definition
/// </summary>
public interface IBaseMessage
{
}
/// <summary>
/// Implementation
/// </summary>
/// <typeparam name="T"></typeparam>
public class BaseMessage : IBaseMessage
{
}
}
| 15.722222 | 42 | 0.568905 | [
"MIT"
] | Indemos/Blazor-Trader | Core/Messages/BaseMessage.cs | 283 | C# |
using System.Collections.Generic;
using Umbraco.Core.PropertyEditors;
namespace Umbraco.Web.PropertyEditors
{
/// <summary>
/// Represents the configuration editor for the datetime value editor.
/// </summary>
public class DateTimeConfigurationEditor : ConfigurationEditor<DateTimeConfiguration>
{
public override IDictionary<string, object> ToValueEditor(object configuration)
{
var d = base.ToValueEditor(configuration);
d["pickTime"] = true;
return d;
}
}
}
| 28.789474 | 89 | 0.669104 | [
"MIT"
] | bharanijayasuri/umbraco8 | src/Umbraco.Web/PropertyEditors/DateTimeConfigurationEditor.cs | 549 | C# |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.CommandLine;
using LocalizableStrings = Microsoft.DotNet.Workloads.Workload.List.LocalizableStrings;
namespace Microsoft.DotNet.Cli
{
internal static class WorkloadListCommandParser
{
// arguments are a list of workload to be detected
public static readonly Option MachineReadableOption = new Option<bool>(
"--machine-readable"
) {
IsHidden = true
};
public static readonly Option VerbosityOption = CommonOptions.VerbosityOption();
public static readonly Option VersionOption = WorkloadUpdateCommandParser.VersionOption;
public static Command GetCommand()
{
var command = new Command("list", LocalizableStrings.CommandDescription);
command.AddOption(MachineReadableOption);
command.AddOption(VerbosityOption);
command.AddOption(VersionOption);
return command;
}
}
}
| 35.1875 | 101 | 0.691829 | [
"MIT"
] | belav/sdk | src/Cli/dotnet/commands/dotnet-workload/list/WorkloadListCommandParser.cs | 1,126 | C# |
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// Управление общими сведениями о сборке осуществляется с помощью
// набора атрибутов. Измените значения этих атрибутов, чтобы изменить сведения,
// связанные со сборкой.
[assembly: AssemblyTitle("Icons8.UI.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Icons8.UI.Tests")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Параметр ComVisible со значением FALSE делает типы в сборке невидимыми
// для COM-компонентов. Если требуется обратиться к типу в этой сборке через
// COM, задайте атрибуту ComVisible значение TRUE для этого типа.
[assembly: ComVisible(false)]
//Чтобы начать сборку локализованных приложений, задайте
//<UICulture>CultureYouAreCodingWith</UICulture> в файле .csproj
//внутри <PropertyGroup>. Например, если используется английский США
//в своих исходных файлах установите <UICulture> в en-US. Затем отмените преобразование в комментарий
//атрибута NeutralResourceLanguage ниже. Обновите "en-US" в
//строка внизу для обеспечения соответствия настройки UICulture в файле проекта.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //где расположены словари ресурсов по конкретным тематикам
//(используется, если ресурс не найден на странице
// или в словарях ресурсов приложения)
ResourceDictionaryLocation.SourceAssembly //где расположен словарь универсальных ресурсов
//(используется, если ресурс не найден на странице,
// в приложении или в каких-либо словарях ресурсов для конкретной темы)
)]
// Сведения о версии сборки состоят из следующих четырех значений:
//
// Основной номер версии
// Дополнительный номер версии
// Номер сборки
// Редакция
//
// Можно задать все значения или принять номера сборки и редакции по умолчанию
// используя "*", как показано ниже:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 43.482143 | 117 | 0.723614 | [
"MIT"
] | HorevIvan/Icons8_UI_Solution | Icons8.UI.Tests/Properties/AssemblyInfo.cs | 3,425 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using HuaweiCloud.SDK.Core;
namespace HuaweiCloud.SDK.ProjectMan.V4.Model
{
/// <summary>
/// Response Object
/// </summary>
public class ListIterationHistoriesResponse : SdkResponse
{
/// <summary>
/// 总数
/// </summary>
[JsonProperty("total", NullValueHandling = NullValueHandling.Ignore)]
public int? Total { get; set; }
/// <summary>
/// 历史记录
/// </summary>
[JsonProperty("histories", NullValueHandling = NullValueHandling.Ignore)]
public List<IterationHistory> Histories { get; set; }
/// <summary>
/// Get the string
/// </summary>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class ListIterationHistoriesResponse {\n");
sb.Append(" total: ").Append(Total).Append("\n");
sb.Append(" histories: ").Append(Histories).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
public override bool Equals(object input)
{
return this.Equals(input as ListIterationHistoriesResponse);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
public bool Equals(ListIterationHistoriesResponse input)
{
if (input == null)
return false;
return
(
this.Total == input.Total ||
(this.Total != null &&
this.Total.Equals(input.Total))
) &&
(
this.Histories == input.Histories ||
this.Histories != null &&
input.Histories != null &&
this.Histories.SequenceEqual(input.Histories)
);
}
/// <summary>
/// Get hash code
/// </summary>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.Total != null)
hashCode = hashCode * 59 + this.Total.GetHashCode();
if (this.Histories != null)
hashCode = hashCode * 59 + this.Histories.GetHashCode();
return hashCode;
}
}
}
}
| 29.340659 | 81 | 0.507116 | [
"Apache-2.0"
] | huaweicloud/huaweicloud-sdk-net | Services/ProjectMan/V4/Model/ListIterationHistoriesResponse.cs | 2,682 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace OAuthApplication.Models
{
// Models returned by MeController actions.
public class GetViewModel
{
public string Hometown { get; set; }
}
} | 22.25 | 47 | 0.730337 | [
"MIT"
] | kranthi467/KranthiPOCs | .NET/OAuthApplication/OAuthApplication/Models/MeViewModels.cs | 269 | C# |
using System;
using System.Xml.Serialization;
using System.ComponentModel.DataAnnotations;
using BroadWorksConnector.Ocip.Validation;
using System.Collections.Generic;
namespace BroadWorksConnector.Ocip.Models
{
/// <summary>
/// Alternate Number Entry.
/// </summary>
[Serializable]
[XmlRoot(Namespace = "")]
[Groups(@"[{""__type"":""Sequence:#BroadWorksConnector.Ocip.Validation"",""id"":""c0d21ef9ba207c335d8347e5172fce1d:449""}]")]
public class AlternateNumberEntry21
{
private string _phoneNumber;
[XmlElement(ElementName = "phoneNumber", IsNullable = true, Namespace = "")]
[Optional]
[Group(@"c0d21ef9ba207c335d8347e5172fce1d:449")]
[MinLength(1)]
[MaxLength(23)]
public string PhoneNumber
{
get => _phoneNumber;
set
{
PhoneNumberSpecified = true;
_phoneNumber = value;
}
}
[XmlIgnore]
protected bool PhoneNumberSpecified { get; set; }
private string _extension;
[XmlElement(ElementName = "extension", IsNullable = true, Namespace = "")]
[Optional]
[Group(@"c0d21ef9ba207c335d8347e5172fce1d:449")]
[MinLength(2)]
[MaxLength(20)]
public string Extension
{
get => _extension;
set
{
ExtensionSpecified = true;
_extension = value;
}
}
[XmlIgnore]
protected bool ExtensionSpecified { get; set; }
private BroadWorksConnector.Ocip.Models.RingPattern? _ringPattern;
[XmlElement(ElementName = "ringPattern", IsNullable = true, Namespace = "")]
[Optional]
[Group(@"c0d21ef9ba207c335d8347e5172fce1d:449")]
public BroadWorksConnector.Ocip.Models.RingPattern? RingPattern
{
get => _ringPattern;
set
{
RingPatternSpecified = true;
_ringPattern = value;
}
}
[XmlIgnore]
protected bool RingPatternSpecified { get; set; }
private string _description;
[XmlElement(ElementName = "description", IsNullable = true, Namespace = "")]
[Optional]
[Group(@"c0d21ef9ba207c335d8347e5172fce1d:449")]
[MinLength(1)]
[MaxLength(40)]
public string Description
{
get => _description;
set
{
DescriptionSpecified = true;
_description = value;
}
}
[XmlIgnore]
protected bool DescriptionSpecified { get; set; }
}
}
| 27.191919 | 129 | 0.563522 | [
"MIT"
] | JTOne123/broadworks-connector-net | BroadworksConnector/Ocip/Models/AlternateNumberEntry21.cs | 2,692 | C# |
using System;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace Essensoft.AspNetCore.Payment.Alipay.Domain
{
/// <summary>
/// ModelColumn Data Structure.
/// </summary>
[Serializable]
public class ModelColumn : AlipayObject
{
/// <summary>
/// 列别名
/// </summary>
[JsonProperty("alias")]
[XmlElement("alias")]
public string Alias { get; set; }
/// <summary>
/// 列值
/// </summary>
[JsonProperty("data")]
[XmlElement("data")]
public string Data { get; set; }
}
}
| 21.5 | 52 | 0.54485 | [
"MIT"
] | AkonCoder/Payment | src/Essensoft.AspNetCore.Payment.Alipay/Domain/ModelColumn.cs | 612 | C# |
// <auto-generated />
using Lab12_HotelDataBase.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace Lab12_HotelDataBase.Migrations
{
[DbContext(typeof(HotelDBContext))]
[Migration("20200522015020_SlightRefactoring")]
partial class SlightRefactoring
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "3.1.4")
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Lab12_HotelDataBase.Models.Amenities", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(50)")
.HasMaxLength(50);
b.HasKey("Id");
b.ToTable("Amenities");
b.HasData(
new
{
Id = 1,
Name = "Coffee"
},
new
{
Id = 2,
Name = "Toilet"
},
new
{
Id = 3,
Name = "Window"
},
new
{
Id = 4,
Name = "Jacuzzi"
},
new
{
Id = 5,
Name = "TikiBar"
});
});
modelBuilder.Entity("Lab12_HotelDataBase.Models.Hotel", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("City")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Country")
.HasColumnType("nvarchar(max)");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Phone")
.HasColumnType("nvarchar(max)");
b.Property<string>("State")
.HasColumnType("nvarchar(max)");
b.Property<string>("StreetAddress")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Hotels");
b.HasData(
new
{
Id = 1,
City = "Seattle",
Name = "AsyncInn"
},
new
{
Id = 2,
City = "Madison",
Name = "SimUInn"
},
new
{
Id = 3,
City = "Cedar Rapids",
Name = "AnachrInn"
},
new
{
Id = 4,
City = "Chicago",
Name = "InSyncInn"
},
new
{
Id = 5,
City = "New York",
Name = "HarlequInn"
});
});
modelBuilder.Entity("Lab12_HotelDataBase.Models.HotelRoom", b =>
{
b.Property<int>("HotelId")
.HasColumnType("int");
b.Property<int>("RoomId")
.HasColumnType("int");
b.Property<bool>("PetFriendly")
.HasColumnType("bit");
b.Property<decimal>("Rate")
.HasColumnType("decimal(18,4)");
b.Property<int>("RoomNumber")
.HasColumnType("int");
b.HasKey("HotelId", "RoomId");
b.HasIndex("HotelId")
.IsUnique();
b.HasIndex("RoomId")
.IsUnique();
b.ToTable("HotelRooms");
});
modelBuilder.Entity("Lab12_HotelDataBase.Models.Room", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Layout")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Rooms");
b.HasData(
new
{
Id = 1,
Layout = "Quick n Easy",
Name = "Low Baller"
},
new
{
Id = 2,
Layout = "1 Queen",
Name = "Don't Ask, We Tell"
},
new
{
Id = 3,
Layout = "7 Queens",
Name = "Super Sleeper"
},
new
{
Id = 4,
Layout = "The Works",
Name = "King Suite"
},
new
{
Id = 5,
Layout = "Exotic retreat in a retreat",
Name = "Sleepy Cove"
},
new
{
Id = 6,
Layout = "Come back with more money to find out!",
Name = "Penthouse"
});
});
modelBuilder.Entity("Lab12_HotelDataBase.Models.RoomAmenities", b =>
{
b.Property<int>("AmenitiesId")
.HasColumnType("int");
b.Property<int>("RoomId")
.HasColumnType("int");
b.HasKey("AmenitiesId", "RoomId");
b.HasIndex("RoomId")
.IsUnique();
b.ToTable("RoomAmenities");
});
modelBuilder.Entity("Lab12_HotelDataBase.Models.HotelRoom", b =>
{
b.HasOne("Lab12_HotelDataBase.Models.Hotel", "Hotel")
.WithOne("HotelRoom")
.HasForeignKey("Lab12_HotelDataBase.Models.HotelRoom", "HotelId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Lab12_HotelDataBase.Models.Room", "Room")
.WithOne("HotelRoom")
.HasForeignKey("Lab12_HotelDataBase.Models.HotelRoom", "RoomId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Lab12_HotelDataBase.Models.RoomAmenities", b =>
{
b.HasOne("Lab12_HotelDataBase.Models.Hotel", "Amenities")
.WithMany()
.HasForeignKey("AmenitiesId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Lab12_HotelDataBase.Models.Room", "Room")
.WithOne("RoomAmenities")
.HasForeignKey("Lab12_HotelDataBase.Models.RoomAmenities", "RoomId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
#pragma warning restore 612, 618
}
}
}
| 35.962406 | 125 | 0.366193 | [
"MIT"
] | cnickels21/Lab11-HotelDataBase | Lab12-HotelDataBase/Migrations/20200522015020_SlightRefactoring.Designer.cs | 9,568 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("02. Tribonaci")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("02. Tribonaci")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("3a8f6681-685e-4795-97f5-f7b6f057fcc6")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.810811 | 84 | 0.742673 | [
"MIT"
] | Camyul/Modul_2_CSharp | DSA/14. Dynamic-Programming/02. Tribonaci/Properties/AssemblyInfo.cs | 1,402 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SineWaveMovement : MonoBehaviour {
Vector3 pos;
// Use this for initialization
void Start () {
pos = transform.position;
}
// Update is called once per frame
void Update () {
transform.position = new Vector3 (pos.x + Mathf.Sin (Time.time * 3) * 10, pos.y, pos.z);
}
}
| 20.888889 | 90 | 0.702128 | [
"MIT"
] | milank-s/Prototypes | Assets/Scripts/SineWaveMovement.cs | 378 | C# |
using System.Net.Http;
using System.Threading.Tasks;
using System.Text.Json;
using System.Text;
namespace Conesoft.DNSimple
{
static class JsonHelperMethods
{
public static async Task<T> GetJsonAsync<T>(this HttpClient client, string requestUri)
{
var stream = await client.GetStreamAsync(requestUri);
return await JsonSerializer.DeserializeAsync<T>(stream);
}
public static async Task<HttpResponse> PostJsonAsync<T>(this HttpClient client, string requestUri, T value)
{
var messageWithHeaders = new StringContent(JsonSerializer.Serialize(value), Encoding.UTF8, "application/json");
return new HttpResponse(await client.PostAsync(requestUri, messageWithHeaders));
}
public static async Task PatchJsonAsync<T>(this HttpClient client, string requestUri, T value)
{
var messageWithHeaders = new StringContent(JsonSerializer.Serialize(value), Encoding.UTF8, "application/json");
await client.PatchAsync(requestUri, messageWithHeaders);
}
public class HttpResponse
{
private readonly HttpResponseMessage httpResponseMessage;
public HttpResponse(HttpResponseMessage httpResponseMessage)
{
this.httpResponseMessage = httpResponseMessage;
}
public async Task<T> Response<T>()
{
var stream = await httpResponseMessage.Content.ReadAsStreamAsync();
return await JsonSerializer.DeserializeAsync<T>(stream);
}
}
}
}
| 36.044444 | 123 | 0.657213 | [
"MIT"
] | conesoft/dnsimple | src/Conesoft.DNSimple/JsonHelperMethods.cs | 1,624 | C# |
using UnityEngine;
using System.Collections;
// Handles the placement of houses on the luthadel map to generate the city.
public class Environment_LuthadelMapGenerator : Environment {
[SerializeField]
private Texture2D map = null;
// The sizes are in terms of pixels of the map texture, not meters.
public GameObject[] houses = null;
public int[] houseSizes = null;
private Texture2D originalTexture = null;
private int width = 0, height = 0;
private void OnValidate() {
originalTexture = map;
height = map.height;
width = map.width;
}
public void GenerateHouses() {
/*
* For each pixel:
* If it's black or blue, skip it. It's a road, river, etc.
* If it's white, it's valid zoning for a house. Place a house under certain conditions.
* Choose a house based on random chance and Luthadel zoning. If that house is surrounded by enough white pixels to fit, place it.
* Then, set those pixels to be blue, meaning the space is occupied.
* While we were checking nearby pixels to place the house, find the closest black pixel, and face the house towards it (make the house face a road)
*
*/
Transform buildings = transform.Find("GeneratedBuildings");
float scaleX = transform.Find("Map").localScale.x;
float scaleY = transform.Find("Map").localScale.y;
Texture2D newTex = new Texture2D(width, height);
newTex.filterMode = FilterMode.Point;
Color[] pixels = map.GetPixels();
for(int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
// tests: place houses in a small section
if(i >1300 && i < 1500 && j > 1200 && j < 1500) {
// if black, skip
if(pixels[GetPixel(j, i)] == Color.black) {
continue;
}
// choose the building for this area
int houseIndex = Random.Range(0, houses.Length);
int zoneSize = houseSizes[houseIndex];
bool bad = false;
// check if the zone has space (i.e. everything is white)
// Assumes the house's origin is at its XY center
// does not account for edge of screen out of bounds
int zj = 0, zi = 0;
for (zi = i - zoneSize/2; zi < i + zoneSize/2 && !bad; zi++) {
for (zj = j - zoneSize/2; zj < j + zoneSize/2; zj++) {
if (pixels[GetPixel(zj, zi)] != Color.white) {
bad = true;
break;
}
}
}
if (bad)
continue;
// Confirm zone by setting all to blue
for (zi = i - zoneSize / 2; zi < i + zoneSize / 2 && !bad; zi++) {
for (zj = j - zoneSize / 2; zj < j + zoneSize / 2; zj++) {
pixels[GetPixel(zj, zi)] = Color.blue;
}
}
// radial search around the zone to find the nearest road
// does not account for edge of screen, but that's always black, so...
bool found = false;
int offset = 0;
int blackCount = 0;
int blackI = 0, blackJ = 0;
while (!found) {
zi = i - zoneSize / 2 - 1 - offset;
zj = j - zoneSize / 2 - offset;
// Bottom row
while( zj < j + zoneSize/2+offset) {
if (pixels[GetPixel(zj, zi)] == Color.black) {
//pixels[GetPixel(zj, zi)] = Color.red;
found = true;
blackCount++;
blackJ += zj;
blackI += zi;
}
//pixels[GetPixel(zj, zi)] = Color.green;
zj++;
}
// Right column
while(zi < i + zoneSize / 2 + offset) {
if (pixels[GetPixel(zj, zi)] == Color.black) {
//pixels[GetPixel(zj, zi)] = Color.red;
found = true;
blackCount++;
blackJ += zj;
blackI += zi;
break;
}
//pixels[GetPixel(zj, zi)] = Color.green;
zi++;
}
// Top row
while (zj > j - zoneSize / 2-1- offset) {
if (pixels[GetPixel(zj, zi)] == Color.black) {
//pixels[GetPixel(zj, zi)] = Color.red;
found = true;
blackCount++;
blackJ += zj;
blackI += zi;
break;
}
//pixels[GetPixel(zj, zi)] = Color.green;
zj--;
}
// Left column
while (zi > i - zoneSize / 2-2- offset) {
if (pixels[GetPixel(zj, zi)] == Color.black) {
//pixels[GetPixel(zj, zi)] = Color.red;
found = true;
blackCount++;
blackJ += zj;
blackI += zi;
break;
}
//pixels[GetPixel(zj, zi)] = Color.green;
zi--;
}
offset++;
}
// The house should look at the "road", defined by the average of the black squares in the first circle around the house with black squares.
zj = blackJ / blackCount;
zi = blackI / blackCount;
Vector2 diff = new Vector2(zj - j, i - zi);
float rot_z = Mathf.Atan2(diff.y, diff.x) * Mathf.Rad2Deg;
Quaternion rotation = Quaternion.Euler(0, rot_z + 90, 0);
Vector3 worldPosition = new Vector3((j / (float)width - .5f) * scaleX, 0, (i / (float)height - .5f) * scaleY) + transform.position;
GameObject house = UnityEditor.PrefabUtility.InstantiatePrefab(houses[houseIndex] as Object) as GameObject;
house.transform.position = worldPosition;
house.transform.rotation = rotation;
house.transform.parent = buildings;
}
}
}
newTex.SetPixels(pixels);
newTex.Apply();
transform.Find("Map").GetComponent<Renderer>().material.SetTexture("_MainTex", newTex);
}
private int GetPixel(int x, int y) {
return y * width + x;
}
public void DestroyHouses() {
Transform buildings = transform.Find("GeneratedBuildings");
for (int i = buildings.childCount - 1; i >= 0; i--) {
if(buildings.GetChild(i).name.Contains("Luthadel_")) {
DestroyImmediate(buildings.GetChild(i).gameObject);
}
}
}
public void ResetMapColors() {
transform.Find("Map").GetComponent<Renderer>().material.SetTexture("_MainTex", originalTexture);
}
}
| 44.810056 | 165 | 0.427004 | [
"Apache-2.0",
"MIT"
] | austin-j-taylor/Invested | Assets/Editor/Environment_LuthadelMapGenerator.cs | 8,023 | C# |
using MYOB.AccountRight.SDK.Communication;
using MYOB.AccountRight.SDK.Contracts.Version2.Sale;
namespace MYOB.AccountRight.SDK.Services.Sale
{
/// <summary>
/// A service that provides access to the <see cref="ItemQuote"/> resource
/// </summary>
public sealed class ItemQuoteService : PdfServiceBase<ItemQuote>
{
/// <summary>
/// Initialise a service that can use <see cref="ItemQuote"/> resources
/// </summary>
/// <param name="configuration">The configuration required to communicate with the API service</param>
/// <param name="webRequestFactory">A custom implementation of the <see cref="WebRequestFactory"/>, if one is not supplied a default <see cref="WebRequestFactory"/> will be used.</param>
/// <param name="keyService">An implementation of a service that will store/persist the OAuth tokens required to communicate with the cloud based API at http://api.myob.com/accountright </param>
public ItemQuoteService(IApiConfiguration configuration, IWebRequestFactory webRequestFactory = null, IOAuthKeyService keyService = null)
: base(configuration, webRequestFactory, keyService)
{
}
/// <summary>
/// The route to the service (after the company file identifier)
/// </summary>
public override string Route
{
get { return "Sale/Quote/Item"; }
}
}
} | 47.7 | 202 | 0.673655 | [
"MIT"
] | AnshumanSaurabhMYOB/AccountRight_Live_API_.Net_SDK | MYOB.API.SDK/SDK/Services/Version2/Sale/ItemQuoteService.cs | 1,433 | C# |
using System;
namespace OnLineShop.MVP.Categories.Admin
{
public class CategoryAdminEventArgs : EventArgs
{
public CategoryAdminEventArgs(int id, string name)
{
this.Id = id;
this.Name = name;
}
public int Id { get; set; }
public string Name { get; set; }
}
}
| 17.947368 | 58 | 0.56305 | [
"MIT"
] | dushka-dragoeva/OnLineShop | OnLineShop/OnLineShop.MVP/Categories/Admin/CategoryAdminEventArgs.cs | 343 | C# |
using System;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Threading.Tasks;
using Latitude55.Api.Models;
namespace Latitude55.Api
{
public interface IAttributesController
{
Task<IActionResult> Get();
}
} | 16.375 | 42 | 0.740458 | [
"Apache-2.0"
] | GeorgeTsaplin/hakaton74_portal | backend/PortalApi/IAttributesController.cs | 264 | C# |
using Abp.Application.Services.Dto;
using Abp.Collections.Extensions;
using Abp.Domain.Repositories;
using Abp.Extensions;
using System;
using System.Web;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Linq.Dynamic.Core;
using Microsoft.EntityFrameworkCore;
using Abp.Linq.Extensions;
using Abp.AutoMapper;
using Abp.UI;
using System.Data;
using System.Data.SqlClient;
using tibs.stem.NewCustomerCompanys;
using tibs.stem.Products;
using tibs.stem.QuotationProducts;
using tibs.stem.Quotations;
using tibs.stem.Quotationss.Dto;
using tibs.stem.QuotationStatuss;
using tibs.stem.Sections;
using tibs.stem.QuotationProductss.Dto;
using tibs.stem.ImportHistorys;
using tibs.stem.Citys;
using tibs.stem.ProductImageUrls;
using tibs.stem.Inquirys;
using tibs.stem.TemporaryProducts;
using tibs.stem.Discounts;
using System.Globalization;
using tibs.stem.EnquiryStatuss;
using tibs.stem.Authorization.Users.Profile.Dto;
using tibs.stem.LeadDetails;
using tibs.stem.Storage;
using tibs.stem.Milestones;
using Microsoft.AspNetCore.Identity;
using Abp.Authorization.Users;
using tibs.stem.EnquiryDetails;
using tibs.stem.Team;
using tibs.stem.TeamDetails;
using tibs.stem.Authorization.Roles;
using tibs.stem.Quotationss.Exporting;
using tibs.stem.Dto;
using tibs.stem.Authorization.Users;
using tibs.stem.AcitivityTracks;
using tibs.stem.Inquirys.Dto;
using tibs.stem.Views;
using NPOI.SS.UserModel;
using System.IO;
using NPOI.XSSF.UserModel;
using Microsoft.Extensions.Configuration;
using System.Net;
using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Hosting;
using tibs.stem.LeadReasons;
using tibs.stem.Url;
namespace tibs.stem.Quotationss
{
public class QuotationAppService : stemAppServiceBase, IQuotationAppService
{
private readonly IRepository<Quotation> _quotationRepository;
private readonly IRepository<NewCompany> _newCompanyRepository;
private readonly IRepository<QuotationStatus> _quotationStatusRepository;
private readonly IRepository<Section> _sectionRepository;
private readonly IRepository<Product> _productRepository;
private readonly IRepository<QuotationProduct> _quotationProductRepository;
private readonly IRepository<ImportHistory> _ImportHistoryRepository;
private readonly IRepository<NewAddressInfo> _NewAddressInfoRepository;
private readonly IRepository<City> _CityRepository;
private readonly IRepository<ProductImageUrl> _ProductImageRepository;
private readonly IRepository<ProductImageUrl> _productImageUrlRepository;
private readonly IRepository<Inquiry> _inquiryRepository;
private readonly IRepository<TemporaryProduct> _TempProductRepository;
private readonly IRepository<NewContactInfo> _NewContactInfoRepository;
private readonly IRepository<Discount> _discountRepository;
private readonly IRepository<EnquiryStatus> _enqStatusRepository;
private readonly IRepository<LeadDetail> _LeadDetailRepository;
private readonly IBinaryObjectManager _binaryObjectManager;
private readonly IRepository<StageDetails> _StageDetailRepository;
private readonly RoleManager _roleManager;
private readonly IRepository<UserRole, long> _userRoleRepository;
private readonly IRepository<EnquiryDetail> _enquiryDetailRepository;
private readonly IRepository<Teams> _TeamRepository;
private readonly IRepository<TeamDetail> _TeamDetailRepository;
private readonly IRepository<TemporaryProductImage> _TempProductImageRepository;
private readonly IQuotationListExcelExporter _quotationListExcelExporter;
private List<QuotationReportListDto> inquirylistdto;
private readonly IUserEmailer _userEmailer;
private readonly IRepository<AcitivityTrack> _acitivityTrackRepository;
private readonly IQuotationInquiryFilterListExcelExporter _QuotationInquiryFilterListExcelExporter;
private readonly IRepository<View> _ViewRepository;
private readonly ITeamEnquiryReportExcelExporter _TeamEnquiryReportExcelExporter;
private readonly ITeamReportExcelExporter _TeamReportExcelExporter;
private readonly IAllTeamReportExcelExporter _AllTeamReportExcelExporter;
private readonly IWebUrlService _webUrlService;
public static IConfigurationRoot Configuration { get; set; }
private readonly IHostingEnvironment _hostingEnvironment;
private readonly IRepository<LeadReason> _leadReasonTrackRepository;
public QuotationAppService(
IRepository<Quotation> quotationRepository,
IRepository<NewCompany> newCompanyRepository,
IRepository<AcitivityTrack> acitivityTrackRepository,
IRepository<QuotationStatus> quotationStatusRepository,
IRepository<Section> sectionRepository,
IRepository<Product> productRepository,
IQuotationListExcelExporter quotationListExcelExporter,
IRepository<LeadDetail> LeadDetailRepository,
IRepository<QuotationProduct> quotationProductRepository,
IRepository<ImportHistory> ImportHistoryRepository,
IRepository<NewAddressInfo> NewAddressInfoRepository,
IRepository<City> CityRepository,
IRepository<ProductImageUrl> ProductImageRepository,
IRepository<ProductImageUrl> productImageUrlRepository,
IRepository<Inquiry> inquiryRepository,
IRepository<TemporaryProduct> TempProductRepository,
IRepository<NewContactInfo> NewContactInfoRepository,
IRepository<Discount> discountRepository,
IBinaryObjectManager binaryObjectManager,
IRepository<EnquiryStatus> enqStatusRepository,
IRepository<StageDetails> StageDetailRepository,
IUserEmailer userEmailer,
IHostingEnvironment hostingEnvironment,
RoleManager roleManager, IRepository<UserRole, long> userRoleRepository,
IRepository<EnquiryDetail> enquiryDetailRepository,
IRepository<Teams> TeamRepository,
IRepository<TeamDetail> TeamDetailRepository,
IQuotationInquiryFilterListExcelExporter QuotationInquiryFilterListExcelExporter,
IRepository<View> ViewRepository,
IRepository<TemporaryProductImage> TempProductImageRepository,
ITeamEnquiryReportExcelExporter TeamEnquiryReportExcelExporter,
ITeamReportExcelExporter TeamReportExcelExporter,
IAllTeamReportExcelExporter AllTeamReportExcelExporter,
IRepository<LeadReason> leadReasonTrackRepository,
IWebUrlService webUrlService
)
{
_quotationRepository = quotationRepository;
_webUrlService = webUrlService;
_LeadDetailRepository = LeadDetailRepository;
_newCompanyRepository = newCompanyRepository;
_quotationStatusRepository = quotationStatusRepository;
_sectionRepository = sectionRepository;
_productRepository = productRepository;
_quotationProductRepository = quotationProductRepository;
_ImportHistoryRepository = ImportHistoryRepository;
_NewAddressInfoRepository = NewAddressInfoRepository;
_CityRepository = CityRepository;
_ProductImageRepository = ProductImageRepository;
_productImageUrlRepository = productImageUrlRepository;
_inquiryRepository = inquiryRepository;
_TempProductRepository = TempProductRepository;
_NewContactInfoRepository = NewContactInfoRepository;
_discountRepository = discountRepository;
_enqStatusRepository = enqStatusRepository;
_binaryObjectManager = binaryObjectManager;
_StageDetailRepository = StageDetailRepository;
_roleManager = roleManager;
_userRoleRepository = userRoleRepository;
_enquiryDetailRepository = enquiryDetailRepository;
_TeamRepository = TeamRepository;
_TeamDetailRepository = TeamDetailRepository;
_TempProductImageRepository = TempProductImageRepository;
_quotationListExcelExporter = quotationListExcelExporter;
_userEmailer = userEmailer;
_acitivityTrackRepository = acitivityTrackRepository;
_QuotationInquiryFilterListExcelExporter = QuotationInquiryFilterListExcelExporter;
_ViewRepository = ViewRepository;
_TeamEnquiryReportExcelExporter = TeamEnquiryReportExcelExporter;
_TeamReportExcelExporter = TeamReportExcelExporter;
_AllTeamReportExcelExporter = AllTeamReportExcelExporter;
_hostingEnvironment = hostingEnvironment;
_leadReasonTrackRepository = leadReasonTrackRepository;
}
public async Task<PagedResultDto<QuotationListDto>> GetQuotation(GetQuotationInput input)
{
long userid = (int)AbpSession.UserId;
var userrole = (from c in UserManager.Users
join urole in _userRoleRepository.GetAll() on c.Id equals urole.UserId
join role in _roleManager.Roles on urole.RoleId equals role.Id
where urole.UserId == userid
select role).FirstOrDefault();
var query = _quotationRepository.GetAll().Where(p => p.Id == 0);
if (userrole.DisplayName == "Sales Executive")
{
query = (from q in _quotationRepository.GetAll()
where q.Revised == false && q.SalesPersonId == userid && q.IsClosed != true && q.Archieved != true && q.Void != true
select q
);
}
else if (userrole.DisplayName == "Sales Manager" || userrole.DisplayName == "Sales Manager / Sales Executive")
{
query = (from q in _quotationRepository.GetAll()
join enq in _inquiryRepository.GetAll() on q.InquiryId equals enq.Id
join enqDetail in _enquiryDetailRepository.GetAll() on enq.Id equals enqDetail.InquiryId
join team in _TeamRepository.GetAll() on enqDetail.TeamId equals team.Id
join usr in UserManager.Users on team.SalesManagerId equals usr.Id
where q.Revised == false && team.SalesManagerId == userid && q.IsClosed != true && q.Archieved != true && q.Void != true
select q
);
}
else if (userrole.DisplayName == "Designer")
{
query = (from q in _quotationRepository.GetAll()
join enq in _inquiryRepository.GetAll() on q.InquiryId equals enq.Id
join leadDetail in _LeadDetailRepository.GetAll() on enq.Id equals leadDetail.InquiryId
where q.Revised == false && leadDetail.DesignerId == userid && q.IsClosed != true && q.Archieved != true && q.Void != true
select q
);
}
else if (userrole.DisplayName == "Sales Coordinator / Sales Executive")
{
query = (from q in _quotationRepository.GetAll()
where q.Revised == false && q.SalesPersonId == userid && q.IsClosed != true && q.Archieved != true && q.Void != true
select q).Union(from q in _quotationRepository.GetAll()
join enq in _inquiryRepository.GetAll() on q.InquiryId equals enq.Id
join leadDetail in _LeadDetailRepository.GetAll() on enq.Id equals leadDetail.InquiryId
where q.Revised == false && leadDetail.CoordinatorId == userid && q.IsClosed != true && q.Archieved != true && q.Void != true
select q).Distinct().OrderBy(p => p.Id);
}
else if (userrole.DisplayName == "Sales Coordinator")
{
query = (from q in _quotationRepository.GetAll()
join enq in _inquiryRepository.GetAll() on q.InquiryId equals enq.Id
join leadDetail in _LeadDetailRepository.GetAll() on enq.Id equals leadDetail.InquiryId
where q.Revised == false && leadDetail.CoordinatorId == userid && q.IsClosed != true && q.Archieved != true && q.Void != true
select q
);
}
else
{
query = _quotationRepository.GetAll().Where(p => p.Revised == false);
}
query = query
.Include(u => u.NewCompanys)
.Include(u => u.Quotationstatus)
.WhereIf(
!input.Filter.IsNullOrWhiteSpace(),
u =>
u.RefNo.Contains(input.Filter) ||
u.Id.ToString().Contains(input.Filter) ||
u.CustomerId.ToString().Contains(input.Filter) ||
u.NewCompanys.Name.Contains(input.Filter) ||
u.Quotationstatus.Name.Contains(input.Filter)
);
System.Globalization.CultureInfo info = System.Globalization.CultureInfo.GetCultureInfo("en");
var reg = (from r in query
join ur in UserManager.Users on r.CreatorUserId equals ur.Id
select new QuotationListDto
{
Id = r.Id,
RefNo = r.RefNo,
Name = r.Name,
CustomerId = r.CustomerId,
TermsandCondition = r.TermsandCondition,
NewCompanyId = r.NewCompanyId,
CompanyName = r.NewCompanyId != null ? r.NewCompanys.Name : "",
StatusName = r.Quotationstatus.Name,
QuotationStatusId = r.QuotationStatusId,
SalesPersonId = r.SalesPersonId,
SalesPersonName = r.SalesPersonId != null ? r.SalesPerson.UserName : "",
CreationTime = r.LastModificationTime ?? r.CreationTime,
SCreationTime = r.CreationTime.ToString(),
Email = r.Email,
MobileNumber = r.MobileNumber,
AttentionName = r.AttentionContactId != null ? (r.AttentionContact.Name + " " + r.AttentionContact.LastName) : "",
LostDate = r.LostDate,
WonDate = r.WonDate,
SubmittedDate = r.SubmittedDate,
Lost = r.Lost,
Won = r.Won,
Submitted = r.Submitted,
Optional = r.Optional,
Void = r.Void,
InquiryName = r.InquiryId > 0 ? r.Inquiry.Name : "",
Total = r.IsVat == true ? (r.Negotiation == true ? r.Total - r.OverAllDiscountAmount : r.Total) + r.VatAmount : r.Negotiation == true ? r.Total - r.OverAllDiscountAmount : r.Total,
Stotal = (r.IsVat == true ? (r.Negotiation == true ? r.Total - r.OverAllDiscountAmount : r.Total) + r.VatAmount : r.Negotiation == true ? r.Total - r.OverAllDiscountAmount : r.Total).ToString("N2", info),
CreatedBy = ur.UserName ?? "",
CreatorUserId = r.CreatorUserId ?? 0,
CompatitorName = r.CompatitorId > 0 ? r.Compatitors.Name : "",
ReasonName = r.ReasonId > 0 ? r.LostReason.LeadReasonName : "",
ReasonId = r.ReasonId,
CompatitorId = r.CompatitorId,
ReasonRemark = r.ReasonRemark,
PONumber = r.PONumber,
Vat = r.Vat,
IsVat = r.IsVat,
VatAmount = r.VatAmount,
OrgDate = r.OrgDate,
Revised = r.Revised,
RefQNo = r.RefQNo,
RFQNo = r.RFQNo,
IsApproved = r.IsApproved,
OverAllDiscountAmount = r.OverAllDiscountAmount,
OverAllDiscountPercentage = r.OverAllDiscountPercentage,
Negotiation = r.Negotiation,
NegotiationDate = r.NegotiationDate,
});
var quotationCount = await reg.CountAsync();
var quotationlist = await reg
.OrderByDescending(p => p.CreationTime)
.PageBy(input)
.ToListAsync();
if (input.Sorting != "RefNo,CompanyName,InquiryName,AttentionName,SalesPersonName,SCreationTime,Void,Total,CreatedBy")
{
quotationlist = await reg
.OrderBy(input.Sorting)
.PageBy(input)
.ToListAsync();
}
var QuotationListDtos = quotationlist.MapTo<List<QuotationListDto>>();
return new PagedResultDto<QuotationListDto>(quotationCount, QuotationListDtos);
}
public async Task<GetQuotation> GetQuotationForEdit(NullableIdDto input)
{
var output = new GetQuotation();
var query = _quotationRepository
.GetAll().Where(p => p.Id == input.Id && p.Revised != true);
if (query.Count() > 0)
{
var quotations = (from a in query
select new QuotationListDto
{
Id = a.Id,
RefNo = a.RefNo,
Name = a.Name,
CustomerId = a.CustomerId,
TermsandCondition = a.TermsandCondition,
CompanyName = a.NewCompanys.Name,
StatusName = a.Quotationstatus.Name,
SalesPersonName = a.SalesPerson.UserName,
QuotationStatusId = a.QuotationStatusId,
NewCompanyId = a.NewCompanyId,
SalesPersonId = a.SalesPersonId,
AttentionContactId = a.AttentionContactId,
AttentionName = a.AttentionContactId != null ? (a.AttentionContact.Name + " " + a.AttentionContact.LastName) : "",
Total = a.Optional == true ? a.Total : 0,
TotalFormat = a.Total.ToString("N", new CultureInfo("en-US")),
Email = a.Email,
MobileNumber = a.MobileNumber,
Discount = 0,
LostDate = a.LostDate,
WonDate = a.WonDate,
SubmittedDate = a.SubmittedDate,
Lost = a.Lost,
Won = a.Won,
Submitted = a.Submitted,
InquiryId = a.InquiryId ?? 0,
MileStoneId = a.MileStoneId,
Optional = a.Optional,
InquiryName = a.InquiryId != null ? a.Inquiry.Name : "",
DiscountAmount = 0,
Void = a.Void,
StageId = a.StageId,
CompatitorName = a.CompatitorId > 0 ? a.Compatitors.Name : "",
ReasonName = a.ReasonId > 0 ? a.LostReason.LeadReasonName : "",
ReasonId = a.ReasonId,
CompatitorId = a.CompatitorId,
ReasonRemark = a.ReasonRemark,
PONumber = a.PONumber,
Vat = a.Vat,
VatAmount = a.VatAmount,
IsVat = a.IsVat,
OrgDate = a.OrgDate,
Revised = a.Revised,
RevisionId = a.RevisionId,
RFQNo = a.RFQNo,
RefQNo = a.RefQNo,
IsApproved = a.IsApproved,
OverAllDiscountAmount = a.OverAllDiscountAmount,
OverAllDiscountPercentage = a.OverAllDiscountPercentage,
Negotiation = a.Negotiation,
NegotiationDate = a.NegotiationDate,
PaymentDate = a.PaymentDate,
DiscountEmail = a.DiscountEmail,
LeadStatusId = 0,
LeadStatusName = "",
LcNumber = a.Inquiry.LCNumber != null ? a.Inquiry.LCNumber : ""
}).FirstOrDefault();
var data = (from r in _quotationProductRepository.GetAll() where r.QuotationId == input.Id where r.Approval == true select r.TotalAmount).Sum();
if (data > 0)
{
quotations.Total = data;
quotations.TotalFormat = data.ToString("N", new CultureInfo("en-US"));
}
var data2 = (from r in _quotationProductRepository.GetAll() where r.QuotationId == input.Id where r.Approval == false select r.OverAllPrice).Sum();
if (data2 > 0)
{
quotations.Total = quotations.Total + data2;
quotations.TotalFormat = (quotations.Total).ToString("N", new CultureInfo("en-US"));
}
var TotalValue = quotations.Optional == true ? quotations.Total : (from r in _quotationProductRepository.GetAll() where r.QuotationId == input.Id select r.OverAllPrice).Sum();
decimal TotalDiscount = TotalValue - quotations.Total;
if (TotalValue > 0)
{
quotations.Discount = (float)(Math.Round((TotalDiscount * 100) / TotalValue, 2));
quotations.DiscountAmount = TotalDiscount;
quotations.DiscountAmountFormat = TotalDiscount.ToString("N", new CultureInfo("en-US"));
}
if (quotations.SalesPersonId > 0)
{
byte[] bytes = new byte[0];
var Account = (from c in UserManager.Users where c.Id == (long)quotations.SalesPersonId select c).FirstOrDefault();
quotations.SalespersonImage = Account.ProfilePictureUrl;
}
var leadDetail = _LeadDetailRepository.GetAll().Where(p => p.InquiryId == quotations.InquiryId).FirstOrDefault();
if (leadDetail != null)
{
if (leadDetail.DesignerId > 0)
{
byte[] bytes = new byte[0];
var Account = (from c in UserManager.Users where c.Id == (long)leadDetail.DesignerId select c).FirstOrDefault();
quotations.DesignerName = Account.UserName;
quotations.DesignerImage = Account.ProfilePictureUrl;
}
}
var leadstatus = _inquiryRepository.GetAll().Where(p => p.Id == quotations.InquiryId).Select(C => C.LeadStatuss).FirstOrDefault();
if (leadstatus != null)
{
quotations.LeadStatusId = leadstatus.Id;
quotations.LeadStatusName = leadstatus.LeadStatusName;
}
output.quotation = quotations.MapTo<QuotationListDto>();
}
return output;
}
public async Task<GetQuotation> GetQuotationRevisionForEdit(NullableIdDto input)
{
var output = new GetQuotation();
var query = _quotationRepository
.GetAll().Where(p => p.Id == input.Id);
var quotations = (from a in query
select new QuotationListDto
{
Id = a.Id,
RefNo = a.RefNo,
Name = a.Name,
CustomerId = a.CustomerId,
TermsandCondition = a.TermsandCondition,
CompanyName = a.NewCompanys.Name,
StatusName = a.Quotationstatus.Name,
SalesPersonName = a.SalesPerson.UserName,
QuotationStatusId = a.QuotationStatusId,
NewCompanyId = a.NewCompanyId,
SalesPersonId = a.SalesPersonId,
AttentionContactId = a.AttentionContactId,
AttentionName = a.AttentionContactId != null ? (a.AttentionContact.Name + " " + a.AttentionContact.LastName) : "",
Total = 0,
TotalFormat = a.Total.ToString("N", new CultureInfo("en-US")),
Email = a.Email,
MobileNumber = a.MobileNumber,
Discount = 0,
LostDate = a.LostDate,
WonDate = a.WonDate,
SubmittedDate = a.SubmittedDate,
Lost = a.Lost,
Won = a.Won,
Submitted = a.Submitted,
InquiryId = a.InquiryId ?? 0,
MileStoneId = a.MileStoneId,
Optional = a.Optional,
InquiryName = a.InquiryId != null ? a.Inquiry.Name : "",
DiscountAmount = 0,
Void = a.Void,
StageId = a.StageId,
CompatitorName = a.CompatitorId > 0 ? a.Compatitors.Name : "",
ReasonName = a.ReasonId > 0 ? a.LostReason.LeadReasonName : "",
ReasonId = a.ReasonId,
CompatitorId = a.CompatitorId,
ReasonRemark = a.ReasonRemark,
PONumber = a.PONumber,
Vat = a.Vat,
VatAmount = a.VatAmount,
IsVat = a.IsVat,
OrgDate = a.OrgDate,
Revised = a.Revised,
RevisionId = a.RevisionId,
RFQNo = a.RFQNo,
RefQNo = a.RefQNo,
IsApproved = a.IsApproved,
OverAllDiscountAmount = a.OverAllDiscountAmount,
OverAllDiscountPercentage = a.OverAllDiscountPercentage,
Negotiation = a.Negotiation,
NegotiationDate = a.NegotiationDate,
DiscountEmail = a.DiscountEmail
}).FirstOrDefault();
var data = (from r in _quotationProductRepository.GetAll() where r.QuotationId == input.Id where r.Approval == true select r.TotalAmount).Sum();
if (data > 0)
{
quotations.Total = data;
quotations.TotalFormat = data.ToString("N", new CultureInfo("en-US"));
}
var data2 = (from r in _quotationProductRepository.GetAll() where r.QuotationId == input.Id where r.Approval == false select r.OverAllPrice).Sum();
if (data2 > 0)
{
quotations.Total = quotations.Total + data2;
quotations.TotalFormat = (quotations.Total).ToString("N", new CultureInfo("en-US"));
}
var TotalValue = (from r in _quotationProductRepository.GetAll() where r.QuotationId == input.Id select r.OverAllPrice).Sum();
decimal TotalDiscount = TotalValue - quotations.Total;
if (TotalValue > 0)
{
quotations.Discount = (float)(Math.Round((TotalDiscount * 100) / TotalValue, 2));
quotations.DiscountAmount = TotalDiscount;
quotations.DiscountAmountFormat = TotalDiscount.ToString("N", new CultureInfo("en-US"));
}
if (quotations.SalesPersonId > 0)
{
byte[] bytes = new byte[0];
var Account = (from c in UserManager.Users where c.Id == (long)quotations.SalesPersonId select c).FirstOrDefault();
var profilePictureId = Account.ProfilePictureId;
quotations.SalespersonImage = "/assets/common/images/default-profile-picture.png";
if (profilePictureId != null)
{
var file = await _binaryObjectManager.GetOrNullAsync((Guid)profilePictureId);
if (file != null)
{
bytes = file.Bytes;
GetProfilePictureOutput img = new GetProfilePictureOutput(Convert.ToBase64String(bytes));
quotations.SalespersonImage = "data:image/jpeg;base64," + img.ProfilePicture;
}
}
}
var leadDetail = _LeadDetailRepository.GetAll().Where(p => p.InquiryId == quotations.InquiryId).FirstOrDefault();
if (leadDetail != null)
{
if (leadDetail.DesignerId > 0)
{
byte[] bytes = new byte[0];
var Account = (from c in UserManager.Users where c.Id == (long)leadDetail.DesignerId select c).FirstOrDefault();
quotations.DesignerName = Account.UserName;
var profilePictureId = Account.ProfilePictureId;
quotations.DesignerImage = "/assets/common/images/default-profile-picture.png";
if (profilePictureId != null)
{
var file = await _binaryObjectManager.GetOrNullAsync((Guid)profilePictureId);
if (file != null)
{
bytes = file.Bytes;
GetProfilePictureOutput img = new GetProfilePictureOutput(Convert.ToBase64String(bytes));
quotations.DesignerImage = "data:image/jpeg;base64," + img.ProfilePicture;
}
}
}
}
output.quotation = quotations.MapTo<QuotationListDto>();
return output;
}
public async Task<int> CreateOrUpdateQuotation(CreateQuotationInput input)
{
if (input.Id != 0)
{
await UpdateQuotation(input);
}
else
{
input.Id = CreateQuotation(input);
}
return input.Id;
}
public int CreateQuotation(CreateQuotationInput input)
{
int id = 0;
if (input.InquiryId > 0)
{
var date = DateTime.Now.ToString("yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture);
if (input.Optional != true)
{
input.MileStoneId = 5;
input.StageId = 2;
}
if (input.Submitted == true)
{
input.SubmittedDate = DateTime.Now;
}
var discription = _discountRepository.GetAll().Where(p => p.Id == 1).FirstOrDefault();
var countryCode = (from r in _NewAddressInfoRepository.GetAll().Where(p => p.NewCompanyId == input.NewCompanyId) join s in _CityRepository.GetAll() on r.CityId equals s.Id select s.Country.CountryCode).FirstOrDefault();
var quotation = input.MapTo<Quotation>();
if (input.AttentionContactId > 0)
{
var email = _NewContactInfoRepository.GetAll().Where(c => c.NewContacId == input.AttentionContactId && c.NewInfoTypeId == 4).FirstOrDefault();
var mbil = _NewContactInfoRepository.GetAll().Where(c => c.NewContacId == input.AttentionContactId && c.NewInfoTypeId == 7).FirstOrDefault();
if (email != null)
{
quotation.Email = email.InfoData;
}
if (mbil != null)
{
quotation.MobileNumber = mbil.InfoData;
}
quotation.TermsandCondition = discription.QuotationDescription;
quotation.Vat = discription.Vat;
quotation.IsVat = true;
quotation.DiscountEmail = false;
quotation.VatAmount = input.Total > 0 ? (input.Total * discription.Vat) / 100 : 0;
quotation.OrgDate = DateTime.Now;
quotation.RevisionId = null;
}
id = _quotationRepository.InsertAndGetId(quotation);
var quot = _quotationRepository.GetAll().Where(p => p.Id == id).FirstOrDefault();
var val = _quotationRepository.GetAll().Where(p => p.CreationTime.ToString("yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture) == date).Count() + 1;
quot.RefNo = "Q" + date + val.ToString("000") + "-R0";
var val2 = _quotationRepository.GetAll().Where(p => p.RefNo == quot.RefNo).Count();
while (val2 > 0)
{
val = val + 1;
quot.RefNo = "Q" + date + val.ToString("000") + "-R0";
val2 = _quotationRepository.GetAll().Where(p => p.RefNo == quot.RefNo).Count();
}
quot.RevisionId = id;
_quotationRepository.UpdateAsync(quot);
if (input.InquiryId > 0)
{
UpdateEnq((int)input.InquiryId);
}
}
return id;
}
public void UpdateQuotationOptional(int Id)
{
ConnectionAppService db = new ConnectionAppService();
using (SqlConnection con = new SqlConnection(db.ConnectionString()))
{
using (SqlCommand cmd = new SqlCommand("Sp_UpdateQuotationOptional", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@QuotationId", SqlDbType.VarChar).Value = Id;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
void UpdateEnq(int Id)
{
var inquiry = (from r in _inquiryRepository.GetAll() where r.Id == Id select r).FirstOrDefault();
inquiry.MileStoneId = 5;
inquiry.StatusId = 2;
var inquirys = inquiry.MapTo<Inquiry>();
_inquiryRepository.UpdateAsync(inquirys);
var enquiryDetail = (from r in _enquiryDetailRepository.GetAll() where r.InquiryId == Id && r.IsDeleted == false select r).FirstOrDefault();
if (enquiryDetail.LastActivity == null)
{
enquiryDetail.LastActivity = DateTime.Now.AddDays(1);
}
if(enquiryDetail.ClosureDate == null)
{
enquiryDetail.ClosureDate = DateTime.Now.AddDays(1);
}
var linkcomp = enquiryDetail.MapTo<EnquiryDetail>();
_enquiryDetailRepository.UpdateAsync(linkcomp);
}
public async Task UpdateQuotation(CreateQuotationInput input)
{
var oldquotations = _quotationRepository.GetAll().AsNoTracking().Where(u => u.Id == input.Id).FirstOrDefault();
var wonStage = _enqStatusRepository.GetAll().Where(p => p.EnqStatusName == "OE Processing").Select(c => c.Id).FirstOrDefault();
var lostStage = _enqStatusRepository.GetAll().Where(p => p.EnqStatusName == "Lost").Select(c => c.Id).FirstOrDefault();
var stage = _StageDetailRepository.GetAll().Where(p => p.MileStoneId == input.MileStoneId && p.StageId == input.StageId).FirstOrDefault();
if (stage == null)
{
var stageId = _StageDetailRepository.GetAll().Where(p => p.MileStoneId == input.MileStoneId).FirstOrDefault();
if (stageId != null)
{
input.StageId = stageId.StageId;
}
}
var vallu = _quotationRepository
.GetAll().Where(u => u.RefNo == input.RefNo && u.Id != input.Id).FirstOrDefault();
if (input.Optional != true)
{
var quotationProductTotals1 = (from r in _quotationProductRepository.GetAll().Where(p => p.QuotationId == input.Id) where r.Approval == true select r.TotalAmount).Sum();
var quotationProductTotals2 = (from r in _quotationProductRepository.GetAll().Where(p => p.QuotationId == input.Id) where r.Approval == false select r.OverAllPrice).Sum();
input.Total = quotationProductTotals1 + quotationProductTotals2;
}
if (oldquotations.QuotationStatusId == 1 && input.QuotationStatusId == 2)
{
var quotationprod = _quotationProductRepository.GetAll().Where(u => u.QuotationId == input.Id).ToList();
if (quotationprod.Count > 0 || input.Optional == true)
{
input.MileStoneId = 6;
input.StageId = 4;
var quot = await _quotationRepository.GetAsync(input.Id);
quot.LastModificationTime = DateTime.Now;
ObjectMapper.Map(input, quot);
if (vallu == null)
{
await _quotationRepository.UpdateAsync(quot);
if (input.NextActivity != null)
{
var enquiryDetail = _enquiryDetailRepository.GetAll().Where(p => p.InquiryId == quot.InquiryId).FirstOrDefault();
var enqdetail = enquiryDetail.MapTo<EnquiryDetail>();
enqdetail.LastActivity = input.NextActivity;
await _enquiryDetailRepository.UpdateAsync(enqdetail);
EnqActCreate actinput = new EnqActCreate()
{
EnquiryId = (int)quot.InquiryId,
PreviousStatus = "Pre-Quote(Initiate Contact)",
CurrentStatus = "Quoted(Quote 1 of Many)",
ActivityId = 7,
Title = "Status Update",
Message = "Ticket Status Updated Successfully"
};
var Activity = actinput.MapTo<AcitivityTrack>();
await _acitivityTrackRepository.InsertAsync(Activity);
}
}
else
{
throw new UserFriendlyException("Ooops!", "Duplicate Data Occured ");
}
}
else
{
throw new UserFriendlyException("Ooops!", "There is no product in the Quotation");
}
}
else
{
var oldquotation = _quotationRepository.GetAll().AsNoTracking().Where(u => u.Id == input.Id).FirstOrDefault();
var val = _quotationRepository
.GetAll().Where(u => u.RefNo == input.RefNo && u.Id != input.Id && u.PONumber != null && u.PONumber == input.PONumber).FirstOrDefault();
if (oldquotation.Lost == false && input.Lost == true)
{
input.LostDate = DateTime.Now;
input.WonDate = null;
input.PONumber = null;
input.MileStoneId = 10;
input.StageId = lostStage;
//await SendLostMail(input.Id, input.CompatitorId, input.ReasonId, input.ReasonRemark);
}
else if (input.Lost == false)
{
input.LostDate = null;
input.ReasonId = null;
input.CompatitorId = null;
input.ReasonRemark = null;
}
if (oldquotation.Submitted == false && input.Submitted == true)
{
input.SubmittedDate = DateTime.Now;
}
else if (input.Submitted == false)
input.SubmittedDate = null;
if (oldquotation.Negotiation == false && input.Negotiation == true)
{
input.NegotiationDate = DateTime.Now;
input.StageId = 9;
input.MileStoneId = 9;
}
if (oldquotation.Won == false && input.Won == true)
{
input.WonDate = DateTime.Now;
input.LostDate = null;
input.ReasonId = null;
input.CompatitorId = null;
input.ReasonRemark = null;
input.MileStoneId = 10;
input.StageId = wonStage;
}
else if (input.Won == false)
{
input.WonDate = null;
input.PONumber = null;
}
if (oldquotations.QuotationStatusId == 2 && input.QuotationStatusId == 1)
{
input.MileStoneId = 5;
input.StageId = null;
input.Submitted = false;
input.Won = false;
input.Lost = false;
input.SubmittedDate = null;
input.WonDate = null;
input.LostDate = null;
}
var quot = await _quotationRepository.GetAsync(input.Id);
quot.LastModificationTime = DateTime.Now;
ObjectMapper.Map(input, quot);
if (val == null)
{
if (oldquotation.QuotationStatusId != 2 && input.QuotationStatusId == 2)
{
var enquiryDetail = _enquiryDetailRepository.GetAll().Where(p => p.InquiryId == oldquotation.InquiryId).FirstOrDefault();
var enqdetail = enquiryDetail.MapTo<EnquiryDetail>();
enqdetail.LastActivity = input.NextActivity;
await _enquiryDetailRepository.UpdateAsync(enqdetail);
}
await _quotationRepository.UpdateAsync(quot);
if (quot.QuotationStatusId == 5 || quot.QuotationStatusId == 4)
{
await _quotationRepository.UpdateAsync(quot);
ConnectionAppService db = new ConnectionAppService();
using (SqlConnection con = new SqlConnection(db.ConnectionString()))
{
using (SqlCommand cmd = new SqlCommand("Sp_VoidQuotation", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@QuotationId", SqlDbType.Int).Value = input.Id;
cmd.Parameters.Add("@TableId", SqlDbType.Int).Value = quot.QuotationStatusId;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
}
else
{
throw new UserFriendlyException("Ooops!", "Duplicate Data Occured in Po Number '" + input.PONumber);
}
}
}
public async Task UpdateQuotationWonorLost(UpdateQuotationInput input)
{
var quot = await _quotationRepository.GetAsync(input.Id);
quot.LastModificationTime = DateTime.Now;
quot.MileStoneId = input.MileStoneId;
quot.StageId = input.StageId;
quot.PaymentDate = input.PaymentDate;
if (input.Won == true)
{
quot.WonDate = DateTime.Now;
quot.Won = true;
quot.PONumber = input.PONumber;
quot.QuotationStatusId = 4;
}
if (input.Lost == true)
{
quot.LostDate = DateTime.Now;
quot.ReasonId = input.ReasonId;
quot.CompatitorId = input.CompatitorId;
quot.Lost = true;
quot.ReasonRemark = input.ReasonRemark;
quot.QuotationStatusId = 5;
}
if (input.Lost == false)
{
quot.LostDate = null;
quot.ReasonId = null;
quot.CompatitorId = null;
quot.Lost = false;
quot.ReasonRemark = null;
}
if (input.Won == false)
{
quot.WonDate = null;
quot.Won = false;
quot.PONumber = null;
}
var val = 0;
if (quot.QuotationStatusId == 5 || quot.QuotationStatusId == 4)
{
val = _quotationRepository
.GetAll().Where(u => u.Id != input.Id && u.PONumber != null && u.PONumber == input.PONumber).Count();
if (val > 0)
{
throw new UserFriendlyException("Ooops!", "Duplicate Data Occured in Po Number '" + input.PONumber);
}
else
{
await _quotationRepository.UpdateAsync(quot);
ConnectionAppService db = new ConnectionAppService();
using (SqlConnection con = new SqlConnection(db.ConnectionString()))
{
using (SqlCommand cmd = new SqlCommand("Sp_VoidQuotation", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@QuotationId", SqlDbType.Int).Value = input.Id;
cmd.Parameters.Add("@TableId", SqlDbType.Int).Value = quot.QuotationStatusId;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
}
}
public async Task<GetSection> GetSectionForEdit(NullableIdDto input)
{
var output = new GetSection();
var query = _sectionRepository
.GetAll().Where(p => p.Id == input.Id);
var sections = (from a in query
select new SectionListDto
{
Id = a.Id,
Name = a.Name,
QuotationId = a.QuotationId,
RefNo = a.quotation.RefNo,
}).FirstOrDefault();
output.section = sections.MapTo<SectionListDto>();
return output;
}
public async Task CreateOrUpdateSection(CreateSectionInput input)
{
if (input.Id != 0)
{
await UpdateSection(input);
}
else
{
await CreateSection(input);
}
}
public async Task CreateSection(CreateSectionInput input)
{
var section = input.MapTo<Section>();
var val = _sectionRepository
.GetAll().Where(u => u.Name == input.Name && u.Id == input.QuotationId).FirstOrDefault();
if (val == null)
{
await _sectionRepository.InsertAsync(section);
}
else
{
throw new UserFriendlyException("Ooops!", "Duplicate Data Occured in Name '" + input.Name + "'...");
}
}
public async Task UpdateSection(CreateSectionInput input)
{
var section = input.MapTo<Section>();
var val = _sectionRepository
.GetAll().Where(u => u.Name == input.Name && u.Id != input.Id && u.Id == input.QuotationId).FirstOrDefault();
if (val == null)
{
await _sectionRepository.UpdateAsync(section);
}
else
{
throw new UserFriendlyException("Ooops!", "Duplicate Data Occured in Name '" + input.Name + "' ...");
}
}
public async Task<Array> GetQuotationProduct(GetQuotationProductInput input)
{
var sectionGroup = (from r in _sectionRepository.GetAll() where r.QuotationId == input.Id select r).ToArray();
var query = _quotationProductRepository.GetAll().Where(p => p.QuotationId == input.Id);
var reg = (from r in query
select new QuotationProductListDto
{
Id = r.Id,
ProductCode = r.ProductId > 0 ? r.product.ProductCode : r.ProductCode,
Quantity = r.Quantity,
Discount = r.Discount,
UnitOfMeasurement = r.UnitOfMeasurement,
UnitOfPrice = r.UnitOfPrice,
SUnitOfPrice = r.UnitOfPrice.ToString("N", new CultureInfo("en-US")),
TotalAmount = r.Approval == true ? r.TotalAmount : r.OverAllPrice,
STotalAmount = (r.Approval == true ? r.TotalAmount : r.OverAllPrice).ToString("N", new CultureInfo("en-US")),
ProductId = r.ProductId,
ProductName = r.ProductId != null ? r.product.ProductName : "",
QuotationId = r.QuotationId,
RefNo = r.QuotationId > 0 ? r.quotation.RefNo : "",
SectionId = r.SectionId,
SectionName = r.SectionId != null ? r.section.Name : "",
Locked = r.Locked,
Approval = r.Approval,
Discountable = r.Discountable,
CreationTime = r.CreationTime,
TemporaryProductId = r.TemporaryProductId
}).ToList();
foreach (var data in reg)
{
if (data.TemporaryProductId > 0)
{
var TempImage = _TempProductImageRepository.GetAll().Where(p => p.TemporaryProductId == data.TemporaryProductId).FirstOrDefault();
if (TempImage != null)
{
data.ImageUrl = TempImage.ImageUrl;
}
}
else if (data.ProductId > 0)
{
var Image = _ProductImageRepository.GetAll().Where(q => q.ProductId == data.ProductId).FirstOrDefault();
if (Image != null)
{
data.ImageUrl = Image.ImageUrl;
}
}
}
var QuotationProductListDtos = reg.MapTo<List<QuotationProductListDto>>();
var SubListout = new List<QuotationProductOutput>();
foreach (var newsts in sectionGroup)
{
var subtotal = (from r in reg where r.SectionId == newsts.Id select r.TotalAmount).Sum();
SubListout.Add(new QuotationProductOutput {
name = newsts.Name,
subtotal = subtotal,
subtotalFormat = subtotal.ToString("N", new CultureInfo("en-US")),
GetQuotationProduct = (from r in reg where r.SectionId == newsts.Id select r).OrderBy(p => p.CreationTime).ToArray()
});
}
return SubListout.ToArray();
}
public async Task<GetQuotationProduct> GetQuotationProductForEdit(NullableIdDto input)
{
var output = new GetQuotationProduct();
var query = _quotationProductRepository
.GetAll().Where(p => p.Id == input.Id);
var products = (from a in query
select new QuotationProductListDto
{
Id = a.Id,
ProductCode = a.ProductId != null ? a.product.ProductCode : a.TemporaryCode,
Quantity = a.Quantity,
Discount = a.Discount,
UnitOfMeasurement = a.UnitOfMeasurement,
UnitOfPrice = a.UnitOfPrice,
TotalAmount = a.TotalAmount,
RefNo = a.quotation.RefNo,
ProductName = a.product.ProductSpecifications.Name,
SectionName = a.section.Name,
SectionId = a.SectionId,
ProductId = a.ProductId,
TemporaryProductId = a.TemporaryProductId,
QuotationId = a.QuotationId,
Discountable = a.Discountable,
Locked = a.Locked,
OverAllDiscount = a.OverAllDiscount,
OverAllPrice = a.OverAllPrice,
Approval = a.Approval,
TemporaryCode = a.TemporaryCode,
ImageUrl = "",
CreationTime = a.CreationTime
}).FirstOrDefault();
if (products.Locked == true && products.TemporaryProductId > 0)
{
var data = _TempProductRepository.GetAll().Where(p => p.Id == products.TemporaryProductId).FirstOrDefault();
products.UnitOfPrice = (decimal)(data.Price ?? 0);
}
if (products.ProductId > 0)
{
var imageqry = _productImageUrlRepository.GetAll().Where(p => p.ProductId == products.ProductId).FirstOrDefault();
if (imageqry != null)
products.ImageUrl = imageqry.ImageUrl;
}
if (products.TemporaryProductId > 0)
{
var tempImage = _TempProductImageRepository.GetAll().Where(q => q.TemporaryProductId == products.TemporaryProductId).FirstOrDefault();
if (tempImage != null)
{
products.ImageUrl = tempImage.ImageUrl;
}
}
output.product = products.MapTo<QuotationProductListDto>();
return output;
}
public async Task CreateOrUpdateQuotationProduct(QuotationProductInput input)
{
if (input.Id != 0)
{
await UpdateQuotationProduct(input);
}
else
{
await CreateQuotationProduct(input);
}
}
public async Task CreateQuotationProduct(QuotationProductInput input)
{
decimal quotationProductTotals = 0;
var product = input.MapTo<QuotationProduct>();
var val = _quotationProductRepository
.GetAll().Where(u => u.ProductCode == input.ProductCode && u.QuotationId == input.QuotationId && u.SectionId == input.SectionId).FirstOrDefault();
if (val == null)
{
await _quotationProductRepository.InsertAsync(product);
quotationProductTotals = quotationProductTotals + (from r in _quotationProductRepository.GetAll().Where(p => p.QuotationId == input.QuotationId && p.Approval == true) select r.TotalAmount).Sum();
quotationProductTotals = quotationProductTotals + (from r in _quotationProductRepository.GetAll().Where(p => p.QuotationId == input.QuotationId && p.Approval == false) select r.OverAllPrice).Sum();
var quotation = _quotationRepository.GetAll().Where(q => q.Id == input.QuotationId).FirstOrDefault();
quotation.Optional = false;
quotation.Total = quotationProductTotals + (input.Approval == true ? input.TotalAmount : input.OverAllPrice);
if (quotation.Total > 0 && quotation.Vat > 0 && quotation.IsVat == true)
{
quotation.VatAmount = (quotation.Total * quotation.Vat) / 100;
}
if (input.Approval == false)
{
quotation.DiscountEmail = true;
}
await _quotationRepository.UpdateAsync(quotation);
}
else
{
throw new UserFriendlyException("Ooops!", "Duplicate Data Occured in ProductCode...");
}
}
public async Task UpdateQuotationProduct(QuotationProductInput input)
{
decimal quotationProductTotals = 0;
input.TemporaryCode = input.ProductCode;
bool qapp = _quotationProductRepository.GetAll().Where(p => p.Id == input.Id).Select(p => p.Approval).FirstOrDefault();
int qpcount = _quotationProductRepository.GetAll().Where(p => p.QuotationId == input.QuotationId && p.Approval == false).Count();
var val = _quotationProductRepository
.GetAll().Where(u => u.ProductCode == input.ProductCode && u.QuotationId == input.QuotationId && u.SectionId == input.SectionId && u.Id != input.Id).FirstOrDefault();
if (val == null)
{
var product = await _quotationProductRepository.GetAsync(input.Id);
ObjectMapper.Map(input, product);
await _quotationProductRepository.UpdateAsync(product);
quotationProductTotals = quotationProductTotals + (from r in _quotationProductRepository.GetAll().Where(p => p.QuotationId == input.QuotationId && p.Id != input.Id && p.Approval == true) select r.TotalAmount).Sum();
quotationProductTotals = quotationProductTotals + (from r in _quotationProductRepository.GetAll().Where(p => p.QuotationId == input.QuotationId && p.Id != input.Id && p.Approval == false) select r.OverAllPrice).Sum();
var quotation = _quotationRepository.GetAll().Where(q => q.Id == input.QuotationId).FirstOrDefault();
var data =
quotation.Total = quotationProductTotals + (input.Approval == true ? input.TotalAmount : input.OverAllPrice);
if (quotation.Total > 0 && quotation.Vat > 0 && quotation.IsVat == true)
{
quotation.VatAmount = (quotation.Total * quotation.Vat) / 100;
}
if ( qpcount >= 2)
{
quotation.DiscountEmail = true;
} else if (qpcount == 0 && input.Approval == true)
{
quotation.DiscountEmail = false;
}
else if(input.Approval == true && qapp == false)
{
quotation.DiscountEmail = false;
}
else
{
quotation.DiscountEmail = true;
}
await _quotationRepository.UpdateAsync(quotation);
}
else
{
throw new UserFriendlyException("Ooops!", "Duplicate Data Occured in ProductCode...");
}
}
public async Task DeleteQuotationProduct(EntityDto input)
{
var query = (from r in _quotationProductRepository.GetAll().Where(p => p.Id == input.Id) select r).FirstOrDefault();
int qpcount = _quotationProductRepository.GetAll().Where(p => p.QuotationId == query.QuotationId && p.Approval == false).Count();
await _quotationProductRepository.DeleteAsync(input.Id);
decimal quotationproductamount = 0;
var quotation = _quotationRepository.GetAll().Where(q => q.Id == query.QuotationId).FirstOrDefault();
if (query.Approval == true)
{
quotationproductamount = query.TotalAmount;
}
else
{
quotationproductamount = query.OverAllPrice;
}
quotation.Total = quotation.Total - quotationproductamount;
if (quotation.Total > 0 && quotation.Vat > 0 && quotation.IsVat == true)
{
quotation.VatAmount = (quotation.Total * quotation.Vat) / 100;
}
if (query.Approval == false && qpcount < 2)
{
quotation.DiscountEmail = false;
}
await _quotationRepository.UpdateAsync(quotation);
}
public async Task DeleteSection(EntityDto input)
{
await _sectionRepository.DeleteAsync(input.Id);
}
public async Task GetDeleteQuotation(EntityDto input)
{
ConnectionAppService db = new ConnectionAppService();
DataTable ds = new DataTable();
using (SqlConnection conn = new SqlConnection(db.ConnectionString()))
{
SqlCommand sqlComm = new SqlCommand("Sp_DeleteAllDetails", conn);
sqlComm.Parameters.AddWithValue("@TableId", 8);
sqlComm.Parameters.AddWithValue("@Id", input.Id);
sqlComm.CommandType = CommandType.StoredProcedure;
conn.Open();
sqlComm.ExecuteNonQuery();
conn.Close();
}
}
public async Task GetProductImport(ImportQuotationInput input)
{
ConnectionAppService db = new ConnectionAppService();
try
{
using (SqlConnection con = new SqlConnection(db.ConnectionString()))
{
using (SqlCommand cmd = new SqlCommand("sp_ReadFile_QuotationProduct", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@Path", SqlDbType.VarChar).Value = input.File;
cmd.Parameters.Add("@File", SqlDbType.VarChar).Value = input.FileName;
cmd.Parameters.Add("@QuotationId", SqlDbType.Int).Value = input.QuotationId;
con.Open();
cmd.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
throw new UserFriendlyException("Ooops!", " Imported Text File is Not Supported Format");
}
}
public async Task<PagedResultDto<ImportHistoryList>> GetImportHistory(GetImportHistoryInput input)
{
var query = _ImportHistoryRepository.GetAll().Where(p => p.QuotationId == input.QuotationId);
var ImportHistory = (from a in query
select new ImportHistoryList
{
Id = a.Id,
FileName = a.FileName,
QuotationId = a.QuotationId,
ProductCode = a.ProductCode,
Quantity = a.Quantity,
SectionName = a.SectionName,
Status = a.Status,
CreationTime = a.CreationTime.ToString(),
});
var ImportHistoryCount = await ImportHistory.CountAsync();
var importHistorylist = await ImportHistory
.OrderBy(input.Sorting)
.PageBy(input)
.ToListAsync();
var ImportHistoryList = importHistorylist.MapTo<List<ImportHistoryList>>();
return new PagedResultDto<ImportHistoryList>(ImportHistoryCount, ImportHistoryList);
}
public async Task GetQuotationProductUnlock(ProductLinkInput input)
{
ConnectionAppService db = new ConnectionAppService();
using (SqlConnection con = new SqlConnection(db.ConnectionString()))
{
using (SqlCommand cmd = new SqlCommand("Sp_LinkQuotationProduct", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@TempProductId", SqlDbType.VarChar).Value = input.TempProductId;
con.Open();
cmd.ExecuteNonQuery();
}
}
}
public async Task GetExchangeProduct(ExchangeInput input)
{
var query = _quotationProductRepository.GetAll().Where(p => p.Id == input.Id).FirstOrDefault();
var product = _productRepository.GetAll().Where(r => r.Id == input.ProdId).FirstOrDefault();
if (product != null)
{
query.ProductId = product.Id;
query.ProductCode = product.ProductCode;
query.Locked = false;
await _quotationProductRepository.UpdateAsync(query);
}
else
{
throw new UserFriendlyException("Ooops!, Product does not exists");
}
}
public async Task GetApproveProduct(EntityDto input)
{
var query = _quotationProductRepository.GetAll().Where(p => p.Id == input.Id).FirstOrDefault();
var dismcount = _quotationProductRepository.GetAll().Where(p => p.QuotationId == query.QuotationId && p.Approval == false).Count();
if (query != null)
{
query.Approval = true;
//query.Locked = false;
await _quotationProductRepository.UpdateAsync(query);
decimal quotationProductTotals = 0;
quotationProductTotals = quotationProductTotals + (from r in _quotationProductRepository.GetAll().Where(p => p.QuotationId == query.QuotationId && p.Approval == true && p.Id != input.Id) select r.TotalAmount).Sum();
quotationProductTotals = quotationProductTotals + (from r in _quotationProductRepository.GetAll().Where(p => p.QuotationId == query.QuotationId && p.Approval == false && p.Id != input.Id) select r.OverAllPrice).Sum();
var quotation = _quotationRepository.GetAll().Where(q => q.Id == query.QuotationId).FirstOrDefault();
quotation.Total = quotationProductTotals + query.TotalAmount;
if (dismcount < 2)
{
quotation.DiscountEmail = false;
}
if (quotation.Total > 0 && quotation.Vat > 0 && quotation.IsVat == true)
{
quotation.VatAmount = (quotation.Total * quotation.Vat) / 100;
}
await _quotationRepository.UpdateAsync(quotation);
}
else
{
throw new UserFriendlyException("Ooops!, Product does not exists");
}
}
public bool CheckQuotationIsOptional(NullableIdDto input)
{
var data = false;
var query = _quotationRepository.GetAll().Where(p => p.InquiryId == input.Id).ToList();
if (query.Count() > 0)
{
data = true;
}
return data;
}
public ListResultDto<QuotationListDto> GetInquiryWiseQuotation(NullableIdDto input)
{
var query = _quotationRepository.GetAll().Where(p => p.Id == input.Id).FirstOrDefault();
var reg = (from r in _quotationRepository.GetAll() where r.InquiryId == query.InquiryId && r.Id != input.Id && r.Revised == false
select new QuotationListDto
{
Id = r.Id,
RefNo = r.RefNo,
Name = r.Name,
CustomerId = r.CustomerId,
TermsandCondition = r.TermsandCondition,
NewCompanyId = r.NewCompanyId,
CompanyName = r.NewCompanyId != null ? r.NewCompanys.Name : "",
StatusName = r.Quotationstatus.Name,
QuotationStatusId = r.QuotationStatusId,
SalesPersonId = r.SalesPersonId,
SalesPersonName = r.SalesPersonId != null ? r.SalesPerson.UserName : "",
CreationTime = r.LastModificationTime ?? r.CreationTime,
SCreationTime = r.CreationTime.ToString(),
Email = r.Email,
MobileNumber = r.MobileNumber,
AttentionName = r.AttentionContactId != null ? (r.AttentionContact.Name + " " + r.AttentionContact.LastName) : "",
LostDate = r.LostDate,
WonDate = r.WonDate,
SubmittedDate = r.SubmittedDate,
Lost = r.Lost,
Won = r.Won,
Submitted = r.Submitted,
Optional = r.Optional,
Void = r.Void,
InquiryName = r.InquiryId > 0 ? r.Inquiry.Name : "",
Total = r.Total,
CreatedBy = "",
CreatorUserId = r.CreatorUserId ?? 0
});
var quotationlist = reg.ToList();
return new ListResultDto<QuotationListDto>(quotationlist.MapTo<List<QuotationListDto>>());
}
public async Task<PagedResultDto<QuotationListDto>> GetRevisedQuotation(NullableIdDto input)
{
var RevisionId = (from r in _quotationRepository.GetAll() where r.Id == input.Id select r.RevisionId).FirstOrDefault();
var query = _quotationRepository.GetAll().Where(r => r.Revised == true && r.RevisionId == RevisionId);
var reg = (from r in query
select new QuotationListDto
{
Id = r.Id,
RefNo = r.RefNo,
Name = r.Name,
CustomerId = r.CustomerId,
TermsandCondition = r.TermsandCondition,
NewCompanyId = r.NewCompanyId,
CompanyName = r.NewCompanyId != null ? r.NewCompanys.Name : "",
StatusName = r.Quotationstatus.Name,
QuotationStatusId = r.QuotationStatusId,
SalesPersonId = r.SalesPersonId,
SalesPersonName = r.SalesPersonId != null ? r.SalesPerson.UserName : "",
CreationTime = r.LastModificationTime ?? r.CreationTime,
SCreationTime = r.CreationTime.ToString(),
Email = r.Email,
MobileNumber = r.MobileNumber,
AttentionName = r.AttentionContactId != null ? (r.AttentionContact.Name + " " + r.AttentionContact.LastName) : "",
LostDate = r.LostDate,
WonDate = r.WonDate,
SubmittedDate = r.SubmittedDate,
Lost = r.Lost,
Won = r.Won,
Submitted = r.Submitted,
Optional = r.Optional,
Void = r.Void,
InquiryName = r.InquiryId > 0 ? r.Inquiry.Name : "",
Total = r.Total,
CreatedBy = "",
CreatorUserId = r.CreatorUserId ?? 0,
CompatitorName = r.CompatitorId > 0 ? r.Compatitors.Name : "",
ReasonName = r.ReasonId > 0 ? r.LostReason.LeadReasonName : "",
ReasonId = r.ReasonId,
CompatitorId = r.CompatitorId,
ReasonRemark = r.ReasonRemark,
PONumber = r.PONumber,
Vat = r.Vat,
VatAmount = r.VatAmount,
OrgDate = r.OrgDate,
Revised = r.Revised
});
var quotationCount = await reg.CountAsync();
var quotationlist = await reg
.OrderByDescending(p => p.CreationTime)
.ToListAsync();
foreach (var data in quotationlist)
{
if (data.CreatorUserId > 0)
{
try
{
var user = await UserManager.GetUserByIdAsync(data.CreatorUserId);
data.CreatedBy = user.UserName;
}
catch (Exception ex)
{
}
}
}
var QuotationListDtos = quotationlist.MapTo<List<QuotationListDto>>();
return new PagedResultDto<QuotationListDto>(quotationCount, QuotationListDtos);
}
public async Task<int> QuotationRevision(QuotationRevisionInput input)
{
int quotationId = 0;
var approve = true;
long userid = (long)AbpSession.UserId;
var userrole = (from c in UserManager.Users
join urole in _userRoleRepository.GetAll() on c.Id equals urole.UserId
join role in _roleManager.Roles on urole.RoleId equals role.Id
where urole.UserId == userid
select role).FirstOrDefault();
if (userrole.DisplayName == "Sales Manager" || userrole.DisplayName == "Sales Manager / Sales Executive" || userrole.DisplayName == "Chief Operations Manager")
{
approve = false;
}
ConnectionAppService db = new ConnectionAppService();
DataTable ds = new DataTable();
try
{
using (SqlConnection con = new SqlConnection(db.ConnectionString()))
{
SqlCommand sqlComm = new SqlCommand("Sp_QuotationRevision", con);
sqlComm.Parameters.AddWithValue("@QuotationId", input.Id);
sqlComm.Parameters.AddWithValue("@UserId", userid);
sqlComm.Parameters.AddWithValue("@NextActivity", input.NextActivity);
sqlComm.Parameters.AddWithValue("@type", input.TypeId);
sqlComm.Parameters.AddWithValue("@Approval", approve);
sqlComm.CommandType = CommandType.StoredProcedure;
using (SqlDataAdapter da = new SqlDataAdapter(sqlComm))
{
da.Fill(ds);
}
var tquotationId = ds.Rows[0]["Id"].ToString();
quotationId = int.Parse(tquotationId);
}
}
catch (Exception ex)
{
}
return quotationId;
}
public async Task UpdateQuotationVatAmount(NullableIdDto input)
{
var quotationProductTotals = (from r in _quotationProductRepository.GetAll().Where(p => p.QuotationId == input.Id) select r.TotalAmount).Sum();
var quotation = _quotationRepository.GetAll().Where(q => q.Id == input.Id).FirstOrDefault();
quotation.Total = quotationProductTotals;
if (quotation.Total > 0 && quotation.Vat > 0 && quotation.IsVat == true)
{
quotation.VatAmount = (quotation.Total * quotation.Vat) / 100;
}
await _quotationRepository.UpdateAsync(quotation);
}
public async Task SetDiscountForProducts(int TypeId,int QuotationId, Decimal NewDiscount)
{
ConnectionAppService db = new ConnectionAppService();
DataTable ds = new DataTable();
using (SqlConnection conn = new SqlConnection(db.ConnectionString()))
{
SqlCommand sqlComm = new SqlCommand("Sp_SetDiscountForQuotationProducts", conn);
sqlComm.Parameters.AddWithValue("@TypeId", TypeId);
sqlComm.Parameters.AddWithValue("@QuotationId", QuotationId);
sqlComm.Parameters.AddWithValue("@NewDiscount", NewDiscount);
sqlComm.CommandType = CommandType.StoredProcedure;
conn.Open();
sqlComm.ExecuteNonQuery();
conn.Close();
}
}
public async Task<FileDto> GetQuotationToExcel()
{
long userid = (int)AbpSession.UserId;
var userrole = (from c in UserManager.Users
join urole in _userRoleRepository.GetAll() on c.Id equals urole.UserId
join role in _roleManager.Roles on urole.RoleId equals role.Id
where urole.UserId == userid
select role).FirstOrDefault();
var query = _quotationRepository.GetAll().Where(p => p.Id == 0);
if (userrole.DisplayName == "Sales Executive")
{
query = (from q in _quotationRepository.GetAll()
where q.Revised == false && q.SalesPersonId == userid && q.IsClosed != true && q.Archieved != true && q.Void != true
select q
);
}
else if (userrole.DisplayName == "Sales Manager" || userrole.DisplayName == "Sales Manager / Sales Executive")
{
query = (from q in _quotationRepository.GetAll()
join enq in _inquiryRepository.GetAll() on q.InquiryId equals enq.Id
join enqDetail in _enquiryDetailRepository.GetAll() on enq.Id equals enqDetail.InquiryId
join team in _TeamRepository.GetAll() on enqDetail.TeamId equals team.Id
join usr in UserManager.Users on team.SalesManagerId equals usr.Id
where q.Revised == false && team.SalesManagerId == userid && q.IsClosed != true && q.Archieved != true && q.Void != true
select q
);
}
else if (userrole.DisplayName == "Designer")
{
query = (from q in _quotationRepository.GetAll()
join enq in _inquiryRepository.GetAll() on q.InquiryId equals enq.Id
join leadDetail in _LeadDetailRepository.GetAll() on enq.Id equals leadDetail.InquiryId
where q.Revised == false && leadDetail.DesignerId == userid && q.IsClosed != true && q.Archieved != true && q.Void != true
select q
);
}
else if (userrole.DisplayName == "Sales Coordinator")
{
query = (from q in _quotationRepository.GetAll()
join enq in _inquiryRepository.GetAll() on q.InquiryId equals enq.Id
join leadDetail in _LeadDetailRepository.GetAll() on enq.Id equals leadDetail.InquiryId
where q.Revised == false && leadDetail.CoordinatorId == userid && q.IsClosed != true && q.Archieved != true && q.Void != true
select q
);
}
else if (userrole.DisplayName == "Sales Coordinator / Sales Executive")
{
query = (from q in _quotationRepository.GetAll()
where q.Revised == false && q.SalesPersonId == userid && q.IsClosed != true && q.Archieved != true && q.Void != true
select q).Union(from q in _quotationRepository.GetAll()
join enq in _inquiryRepository.GetAll() on q.InquiryId equals enq.Id
join leadDetail in _LeadDetailRepository.GetAll() on enq.Id equals leadDetail.InquiryId
where q.Revised == false && leadDetail.CoordinatorId == userid && q.IsClosed != true && q.Archieved != true && q.Void != true
select q).Distinct().OrderBy(p => p.Id);
}
else
{
query = _quotationRepository.GetAll().Where(p => p.Revised == false);
}
var reg = (from r in query
join ur in UserManager.Users on r.CreatorUserId equals ur.Id
select new QuotationListDto
{
Id = r.Id,
RefNo = r.RefNo,
Name = r.Name,
CustomerId = r.CustomerId,
TermsandCondition = r.TermsandCondition,
NewCompanyId = r.NewCompanyId,
CompanyName = r.NewCompanyId != null ? r.NewCompanys.Name : "",
StatusName = r.Quotationstatus.Name,
QuotationStatusId = r.QuotationStatusId,
SalesPersonId = r.SalesPersonId,
SalesPersonName = r.SalesPersonId != null ? r.SalesPerson.UserName : "",
CreationTime = r.LastModificationTime ?? r.CreationTime,
SCreationTime = r.CreationTime.ToString(),
Email = r.Email,
MobileNumber = r.MobileNumber,
AttentionName = r.AttentionContactId != null ? (r.AttentionContact.Name + " " + r.AttentionContact.LastName) : "",
LostDate = r.LostDate,
WonDate = r.WonDate,
SubmittedDate = r.SubmittedDate,
Lost = r.Lost,
Won = r.Won,
Submitted = r.Submitted,
Optional = r.Optional,
Void = r.Void,
InquiryName = r.InquiryId > 0 ? r.Inquiry.Name : "",
Total = r.IsVat == true ? (r.Negotiation == true ? r.Total - r.OverAllDiscountAmount : r.Total) + r.VatAmount : r.Negotiation == true ? r.Total - r.OverAllDiscountAmount : r.Total,
CreatedBy = ur.UserName ?? "",
CreatorUserId = r.CreatorUserId ?? 0,
CompatitorName = r.CompatitorId > 0 ? r.Compatitors.Name : "",
ReasonName = r.ReasonId > 0 ? r.LostReason.LeadReasonName : "",
ReasonId = r.ReasonId,
CompatitorId = r.CompatitorId,
ReasonRemark = r.ReasonRemark,
PONumber = r.PONumber,
Vat = r.Vat,
IsVat = r.IsVat,
VatAmount = r.VatAmount,
OrgDate = r.OrgDate,
Revised = r.Revised,
RefQNo = r.RefQNo,
RFQNo = r.RFQNo,
IsApproved = r.IsApproved,
OverAllDiscountAmount = r.OverAllDiscountAmount,
OverAllDiscountPercentage = r.OverAllDiscountPercentage,
Negotiation = r.Negotiation,
NegotiationDate = r.NegotiationDate
});
var quotationCount = await reg.CountAsync();
var quotationlist = await reg
.OrderByDescending(p => p.CreationTime)
.ToListAsync();
var QuotationListDtos = quotationlist.MapTo<List<QuotationListDto>>();
return _quotationListExcelExporter.ExportToFile(QuotationListDtos);
}
public async Task<PagedResultDto<QuotationInquiryFilter>> GetQuotationInquiryFilter(FilterByDto input)
{
string userid = input.UserIds;
if (userid == null)
{
var userrole = (from c in UserManager.Users
join urole in _userRoleRepository.GetAll() on c.Id equals urole.UserId
join role in _roleManager.Roles on urole.RoleId equals role.Id
where urole.UserId == AbpSession.UserId
select role).FirstOrDefault();
if (userrole.DisplayName == "Sales Executive" || userrole.DisplayName == "Sales Coordinator / Sales Executive")
userid = Convert.ToString(AbpSession.UserId);
}
var quotationCount = 0;
try
{
ConnectionAppService db = new ConnectionAppService();
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(db.ConnectionString()))
{
SqlCommand sqlComm = new SqlCommand("Sp_GetQuotationInquiryFilter", con);
sqlComm.Parameters.AddWithValue("@Id", input.Id);
sqlComm.Parameters.AddWithValue("@QuotationCreateBy", input.QuotationCreateBy);
sqlComm.Parameters.AddWithValue("@QuotationStatus", input.StatusForQuotation);
sqlComm.Parameters.AddWithValue("@Salesman", input.Salesman);
sqlComm.Parameters.AddWithValue("@InquiryCreateBy", input.InquiryCreateBy);
sqlComm.Parameters.AddWithValue("@PotentialCustomer", input.PotentialCustomer);
sqlComm.Parameters.AddWithValue("@MileStoneName", input.MileStoneName);
sqlComm.Parameters.AddWithValue("@EnquiryStatus", input.Status);
sqlComm.Parameters.AddWithValue("@TeamName", input.TeamName);
sqlComm.Parameters.AddWithValue("@Coordinator", input.Coordinator);
sqlComm.Parameters.AddWithValue("@Designer", input.Designer);
sqlComm.Parameters.AddWithValue("@DesignationName", input.DesignationName);
sqlComm.Parameters.AddWithValue("@Emirates", input.Emirates);
sqlComm.Parameters.AddWithValue("@DepatmentName ", input.DepatmentName);
sqlComm.Parameters.AddWithValue("@Categories", input.Categories);
sqlComm.Parameters.AddWithValue("@Status", input.EnquiryStatus);
sqlComm.Parameters.AddWithValue("@WhyBafco", input.WhyBafco);
sqlComm.Parameters.AddWithValue("@Probability", input.Probability);
sqlComm.Parameters.AddWithValue("@InquiryCreation", input.InquiryCreation);
sqlComm.Parameters.AddWithValue("@QuotationCreation", input.QuotationCreation);
sqlComm.Parameters.AddWithValue("@ClosureDate", input.ClosureDate);
sqlComm.Parameters.AddWithValue("@LastActivityDate", input.LastActivity);
sqlComm.Parameters.AddWithValue("@QtnDateFilterId", input.QtnDateFilterId);
sqlComm.Parameters.AddWithValue("@ClsDateFilterId", input.ClsDateFilterId);
sqlComm.Parameters.AddWithValue("@LastActDateFilterId", input.LastActDateFilterId);
sqlComm.CommandType = CommandType.StoredProcedure;
using (SqlDataAdapter da = new SqlDataAdapter(sqlComm))
{
da.Fill(dt);
}
// var c = dt.Rows.Count;
var Listdto = (from DataRow dr in dt.Rows
select new QuotationInquiryFilter
{
QuotationRefNo = Convert.ToString(dr["REFNO"]),
QuotationCreation = Convert.ToString(dr["QCreationTime"]),
QuotationCreateBy = Convert.ToString(dr["QCreator"]),
QuotationStatus = Convert.ToString(dr["QuotationStatus"]),
Salesman = Convert.ToString(dr["Sales"]),
QuotationValue = Convert.ToString(dr["Total"].ToString()),
TitleOfInquiry = Convert.ToString(dr["Name"]),
InquiryRefNo = Convert.ToString(dr["Submission"]),
InquiryCreation = Convert.ToString(dr["ICreationTime"]),
InquiryCreateBy = Convert.ToString(dr["Creator"]),
PotentialCustomer = Convert.ToString(dr["Company"]),
Email = Convert.ToString(dr["Email"]),
MobileNumber = Convert.ToString(dr["MBNO"]),
MileStoneName = Convert.ToString(dr["Milestone"]),
EnquiryStatus = Convert.ToString(dr["Status"]),
Total = Convert.ToString(dr["Estimation"].ToString()),
TeamName = Convert.ToString(dr["Team"]),
Coordinator = Convert.ToString(dr["Coordinator"]),
Designer = Convert.ToString(dr["Designer"]),
DesignationName = Convert.ToString(dr["Designation"]),
Emirates = Convert.ToString(dr["Location"]),
DepatmentName = Convert.ToString(dr["Depatment"]),
ClosureDate = Convert.ToString(dr["ClosureDate"]),
LastActivity = Convert.ToString(dr["LastActivity"]),
Probability = Convert.ToString(dr["Percentage"]),
AreaName = Convert.ToString(dr["Area"]),
BuildingName = Convert.ToString(dr["Building"]),
Categories = Convert.ToString(dr["LeadType"]),
Status = Convert.ToString(dr["Status"]),
WhyBafco = Convert.ToString(dr["Whybafco"]),
CoordinatorId = Convert.ToInt32(dr["CoordinatorId"]),
SalesPersonId = Convert.ToInt32(dr["SalesId"]),
SalesManagerId = Convert.ToInt32(dr["ManagerId"]),
DesignerId = Convert.ToInt32(dr["DesignerId"]),
CreatorUserId = Convert.ToInt32(dr["CreatorUserId"]),
QuotationId = Convert.ToInt32(dr["Qid"])
});
quotationCount = Listdto.Count();
Listdto = Listdto.Skip(input.SkipCount).Take(input.MaxResultCount);
var QuotationListDtos = Listdto.MapTo<List<QuotationInquiryFilter>>();
return new PagedResultDto<QuotationInquiryFilter>(quotationCount, QuotationListDtos);
}
}
catch (Exception obj)
{
string dd = obj.Message.ToString();
return new PagedResultDto<QuotationInquiryFilter>(0, null);
}
}
public async Task SendDiscountMail(NullableIdDto input)
{
var qut = (from r in _quotationRepository.GetAll()
where r.Id == input.Id && r.Revised != true
select new DiscountEmailFirst
{
Id = r.Id,
SalesPersonId = r.SalesPersonId,
QuotationRefNo = r.RefNo,
FirstName = r.SalesPerson.Name,
LastName = r.SalesPerson.Surname
}).FirstOrDefault();
var qutsal = _quotationRepository.GetAll().Where(p => p.Id == input.Id && p.Revised != true).Select(p => p.SalesPerson.UserName).FirstOrDefault();
var salesmanager = (from a in _TeamDetailRepository.GetAll()
where a.SalesmanId == qut.SalesPersonId && a.IsDeleted == false
join b in _TeamRepository.GetAll().Where(p => p.IsDeleted == false) on a.TeamId equals b.Id
select b.SalesManager.EmailAddress).FirstOrDefault();
try
{
await _userEmailer.DiscountEmailSendSalesManager(qut.Id, salesmanager, qut.QuotationRefNo, qut.FirstName + ' ' + qut.LastName);
}
catch (Exception ex)
{
throw;
}
}
public async Task OverAllApproveQuote(NullableIdDto input)
{
ConnectionAppService db = new ConnectionAppService();
DataTable ds = new DataTable();
using (SqlConnection conn = new SqlConnection(db.ConnectionString()))
{
SqlCommand sqlComm = new SqlCommand("Sp_OverAllQuotationApproval", conn);
sqlComm.Parameters.AddWithValue("@QuotationId", input.Id);
sqlComm.CommandType = CommandType.StoredProcedure;
conn.Open();
sqlComm.ExecuteNonQuery();
conn.Close();
}
}
public async Task<PagedResultDto<QuotationReportListDto>> GetTeamEnquiryReport(QuotationReportInput input)
{
var inquirycount = 0;
DateTime currentdate = DateTime.Now;
var currentmonth = new DateTime(currentdate.Year, currentdate.Month, 1);
var currentyear = currentmonth.AddYears(1);
var listmonths = Enumerable.Range(0, 12).Select(m => currentmonth.AddMonths(m)).ToArray();
var query = _enquiryDetailRepository.GetAll().Where(p => p.AssignedbyId == input.SalesId && p.ClosureDate >= currentmonth && p.ClosureDate < currentyear);
string viewquery = "SELECT * FROM [dbo].[View_ForecastReport]";
DataTable viewtable = new DataTable();
ConnectionAppService db = new ConnectionAppService();
try
{
SqlConnection con = new SqlConnection(db.ConnectionString());
con.Open();
SqlCommand cmd = new SqlCommand(viewquery, con);
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
sda.Fill(viewtable);
}
con.Close();
}
catch (Exception ex)
{
}
var viewdata = (from DataRow dr in viewtable.Rows
select new ForecastDataList
{
Id = Convert.ToInt32(dr["Id"]),
QuotationRefno = Convert.ToString(dr["QuotationRefno"]),
QuotationTotal = Convert.ToDecimal(dr["QuotationTotal"]),
StagePercent = Convert.ToDecimal(dr["StagePercent"]),
EnqStage = Convert.ToString(dr["EnqStage"]),
CreatorUserId = Convert.ToInt32(dr["CreatorUserId"]),
SalesManagerId = Convert.ToInt32(dr["SalesManagerId"]),
SalesPersonId = Convert.ToInt32(dr["SalesPersonId"]),
CoordinatorId = Convert.ToInt32(dr["CoordinatorId"]),
DesignerId = Convert.ToInt32(dr["DesignerId"]),
});
try
{
var inqwdet = (from r in query
join enq in _inquiryRepository.GetAll().Where(p => p.Lost != true && p.Won != true && p.Junk != true && p.IsClosed != true && p.IsClosed != true && p.MileStoneId > 3) on r.InquiryId equals enq.Id
select new QuotationReportListDto
{
Date = r.CreationTime.ToString("dd-MMM-yy"),
InquiryName = r.InquiryId > 0 ? r.Inquirys.Name : "",
Status = enq.LeadStatusId > 0 ? enq.LeadStatuss.LeadStatusName : "",
CompanyName = enq.Companys.Name ?? "",
QuotationId = 0,
InquiryId = enq.Id,
ClosureDate = r.ClosureDate ?? null,
AccountManager = r.AssignedbyId > 0 ? r.AbpAccountManager.UserName : "",
NewOrExisting = enq.Companys.NewCustomerTypes.Title ?? "",
Location = enq.LocationId > 0 ? enq.Locations.LocationName : "",
AEDValue = Math.Round(r.EstimationValue, 2),
Stage = "New",
Percentage = 0,
WeightedAED = 0,
Total1Value = 0,
Total2Value = 0,
Total3Value = 0,
Total4Value = 0,
Total5Value = 0,
Total6Value = 0,
Total7Value = 0,
Total8Value = 0,
Total9Value = 0,
Total10Value = 0,
Total11Value = 0,
Total12Value = 0,
Total1ValueFormat = listmonths[0].ToString("MMM-yyyy"),
Total2ValueFormat = listmonths[1].ToString("MMM-yyyy"),
Total3ValueFormat = listmonths[2].ToString("MMM-yyyy"),
Total4ValueFormat = listmonths[3].ToString("MMM-yyyy"),
Total5ValueFormat = listmonths[4].ToString("MMM-yyyy"),
Total6ValueFormat = listmonths[5].ToString("MMM-yyyy"),
Total7ValueFormat = listmonths[6].ToString("MMM-yyyy"),
Total8ValueFormat = listmonths[7].ToString("MMM-yyyy"),
Total9ValueFormat = listmonths[8].ToString("MMM-yyyy"),
Total10ValueFormat = listmonths[9].ToString("MMM-yyyy"),
Total11ValueFormat = listmonths[10].ToString("MMM-yyyy"),
Total12ValueFormat = listmonths[11].ToString("MMM-yyyy"),
ActionDate = r.LastActivity != null ? r.LastActivity.ToString() : "",
Notes = r.Inquirys.Remarks ?? ""
});
inquirycount = await inqwdet.CountAsync();
var inquirylist = await inqwdet
.OrderBy(p => p.Date)
.PageBy(input)
.ToListAsync();
inquirylistdto = inquirylist.MapTo<List<QuotationReportListDto>>();
}
catch (Exception ex)
{
}
try
{
foreach (var item in inquirylistdto)
{
var data = (from r in viewdata where r.Id == item.InquiryId select r).FirstOrDefault();
if (data != null)
{
item.AEDValue = data.QuotationTotal;
item.WeightedAED = Math.Round(data.StagePercent * data.QuotationTotal / 100, 2);
item.Stage = data.EnqStage;
item.DesignerId = data.DesignerId;
item.SalesPersonId = data.SalesPersonId;
item.SalesManagerId = data.SalesManagerId;
item.CreatorUserId = data.CreatorUserId;
item.CoordinatorId = data.CoordinatorId;
item.Percentage = data.StagePercent;
var InquiryDetailClosureDate = item.ClosureDate;
if (InquiryDetailClosureDate != null)
{
var Month = InquiryDetailClosureDate.GetValueOrDefault().ToString("MMM-yyyy");
if (listmonths[0].ToString("MMM-yyyy") == Month)
{
item.Total1Value = Math.Round(item.WeightedAED, 2);
}
else if (listmonths[1].ToString("MMM-yyyy") == Month)
{
item.Total2Value = Math.Round(item.WeightedAED, 2);
}
else if (listmonths[2].ToString("MMM-yyyy") == Month)
{
item.Total3Value = Math.Round(item.WeightedAED, 2);
}
else if (listmonths[3].ToString("MMM-yyyy") == Month)
{
item.Total4Value = Math.Round(item.WeightedAED, 2);
}
else if (listmonths[4].ToString("MMM-yyyy") == Month)
{
item.Total5Value = Math.Round(item.WeightedAED, 2);
}
else if (listmonths[5].ToString("MMM-yyyy") == Month)
{
item.Total6Value = Math.Round(item.WeightedAED, 2);
}
else if (listmonths[6].ToString("MMM-yyyy") == Month)
{
item.Total7Value = Math.Round(item.WeightedAED, 2);
}
else if (listmonths[7].ToString("MMM-yyyy") == Month)
{
item.Total8Value = Math.Round(item.WeightedAED, 2);
}
else if (listmonths[8].ToString("MMM-yyyy") == Month)
{
item.Total9Value = Math.Round(item.WeightedAED, 2);
}
else if (listmonths[9].ToString("MMM-yyyy") == Month)
{
item.Total10Value = Math.Round(item.WeightedAED, 2);
}
else if (listmonths[10].ToString("MMM-yyyy") == Month)
{
item.Total11Value = Math.Round(item.WeightedAED, 2);
}
else if (listmonths[11].ToString("MMM-yyyy") == Month)
{
item.Total12Value = Math.Round(item.WeightedAED, 2);
}
}
}
}
}
catch (Exception ex)
{
throw;
}
return new PagedResultDto<QuotationReportListDto>(inquirycount, inquirylistdto);
}
public async Task<PagedResultDto<TeamReportListDto>> GetTeamReport(TeamReportInput input)
{
var query = (from r in _TeamDetailRepository.GetAll()
join s in _TeamRepository.GetAll() on r.TeamId equals s.Id
where r.TeamId == input.TeamId select new {
SalesId = r.SalesmanId,
ManagerId = s.SalesManagerId,
SalesName = r.Salesman.UserName,
TeamId = s.Id,
TeamName = r.Team.Name
}).ToList();
if(query.Count() > 0)
{
var manager = (from r in _TeamDetailRepository.GetAll()
join s in _TeamRepository.GetAll() on r.TeamId equals s.Id
where r.TeamId == input.TeamId
select new
{
SalesId = r.SalesmanId,
ManagerId = s.SalesManagerId,
SalesName = r.Salesman.UserName,
TeamId = s.Id,
TeamName = r.Team.Name
}).FirstOrDefault();
if(manager != null)
{
var userrole = (from c in UserManager.Users
join urole in _userRoleRepository.GetAll() on c.Id equals urole.UserId
join role in _roleManager.Roles on urole.RoleId equals role.Id
where urole.UserId == manager.ManagerId
select role).FirstOrDefault();
if (userrole.DisplayName == "Sales Manager / Sales Executive")
{
var user = await UserManager.GetUserByIdAsync((long)AbpSession.UserId);
query.Add(new { SalesId = manager.ManagerId, ManagerId = (long)manager.ManagerId, SalesName = user.UserName, TeamId = (int)manager.TeamId, TeamName = manager.TeamName });
}
}
}
DateTime currentdate = DateTime.Now;
var currentmonth = new DateTime(currentdate.Year, currentdate.Month, 1);
var currentyear = currentmonth.AddYears(1);
var listmonths = Enumerable.Range(0, 12).Select(m => currentmonth.AddMonths(m)).ToArray();
string viewquery = "SELECT * FROM [dbo].[View_ForecastReport]";
DataTable viewtable = new DataTable();
ConnectionAppService db = new ConnectionAppService();
try
{
SqlConnection con = new SqlConnection(db.ConnectionString());
con.Open();
SqlCommand cmd = new SqlCommand(viewquery, con);
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
sda.Fill(viewtable);
}
con.Close();
}
catch (Exception ex)
{
}
var viewdata = (from DataRow dr in viewtable.Rows
select new ForecastDataList
{
Id = Convert.ToInt32(dr["Id"]),
QuotationRefno = Convert.ToString(dr["QuotationRefno"]),
QuotationTotal = Convert.ToDecimal(dr["QuotationTotal"]),
StagePercent = Convert.ToDecimal(dr["StagePercent"]),
EnqStage = Convert.ToString(dr["EnqStage"])
});
var reg = (from r in query
select new TeamReportListDto
{
TeamName = r.TeamName ?? "",
AccountManager = r.SalesName ?? "",
AccountManagerId = r.SalesId,
TotalAEDValue = 0,
TeamId = r.TeamId,
TotalWeightedAED = 0,
Total1Value = 0,
Total2Value = 0,
Total3Value = 0,
Total4Value = 0,
Total5Value = 0,
Total6Value = 0,
Total7Value = 0,
Total8Value = 0,
Total9Value = 0,
Total10Value = 0,
Total11Value = 0,
Total12Value = 0,
Total1ValueFormat = listmonths[0].ToString("MMM-yyyy"),
Total2ValueFormat = listmonths[1].ToString("MMM-yyyy"),
Total3ValueFormat = listmonths[2].ToString("MMM-yyyy"),
Total4ValueFormat = listmonths[3].ToString("MMM-yyyy"),
Total5ValueFormat = listmonths[4].ToString("MMM-yyyy"),
Total6ValueFormat = listmonths[5].ToString("MMM-yyyy"),
Total7ValueFormat = listmonths[6].ToString("MMM-yyyy"),
Total8ValueFormat = listmonths[7].ToString("MMM-yyyy"),
Total9ValueFormat = listmonths[8].ToString("MMM-yyyy"),
Total10ValueFormat = listmonths[9].ToString("MMM-yyyy"),
Total11ValueFormat = listmonths[10].ToString("MMM-yyyy"),
Total12ValueFormat = listmonths[11].ToString("MMM-yyyy"),
});
var teamDetailCount = reg.Count();
var teamDetaillist = reg
.ToList();
var TeamDetailListDtos = teamDetaillist.MapTo<List<TeamReportListDto>>();
try
{
foreach (var salesman in TeamDetailListDtos)
{
var SalesmanId = (from u in UserManager.Users where u.UserName == salesman.AccountManager select u.Id).FirstOrDefault();
var enqDetail = (from t in _enquiryDetailRepository.GetAll().Where(r => r.AssignedbyId == SalesmanId && r.ClosureDate >= currentmonth && r.ClosureDate < currentyear) join enq in _inquiryRepository.GetAll().Where(p => p.Lost != true && p.Won != true && p.Junk != true && p.IsClosed != true && p.MileStoneId > 3) on t.InquiryId equals enq.Id select t).ToArray();
decimal salesmanaedvalue = 0;
decimal salesmanweightvalue = 0;
if (enqDetail.Length > 0)
{
foreach (var item in enqDetail)
{
decimal qutsalesmanaedvalue = Math.Round(item.EstimationValue, 2);
decimal qutsalesmanweightvalue = 0;
var data = (from r in viewdata where r.Id == item.InquiryId select r).FirstOrDefault();
if (data != null)
{
qutsalesmanaedvalue = data.QuotationTotal;
qutsalesmanweightvalue = Math.Round(data.StagePercent * data.QuotationTotal / 100, 2);
salesmanaedvalue = salesmanaedvalue + qutsalesmanaedvalue;
salesmanweightvalue = salesmanweightvalue + qutsalesmanweightvalue;
var InquiryDetailClosureDate = item.ClosureDate;
if (InquiryDetailClosureDate != null)
{
var Month = InquiryDetailClosureDate.GetValueOrDefault().ToString("MMM-yyyy");
if (listmonths[0].ToString("MMM-yyyy") == Month)
{
salesman.Total1Value = Math.Round(Convert.ToDecimal(salesman.Total1Value + qutsalesmanweightvalue), 2);
}
else if (listmonths[1].ToString("MMM-yyyy") == Month)
{
salesman.Total2Value = Math.Round(Convert.ToDecimal(salesman.Total2Value + qutsalesmanweightvalue), 2);
}
else if (listmonths[2].ToString("MMM-yyyy") == Month)
{
salesman.Total3Value = Math.Round(Convert.ToDecimal(salesman.Total3Value + qutsalesmanweightvalue), 2);
}
else if (listmonths[3].ToString("MMM-yyyy") == Month)
{
salesman.Total4Value = Math.Round(Convert.ToDecimal(salesman.Total4Value + qutsalesmanweightvalue), 2);
}
else if (listmonths[4].ToString("MMM-yyyy") == Month)
{
salesman.Total5Value = Math.Round(Convert.ToDecimal(salesman.Total5Value + qutsalesmanweightvalue), 2);
}
else if (listmonths[5].ToString("MMM-yyyy") == Month)
{
salesman.Total6Value = Math.Round(Convert.ToDecimal(salesman.Total6Value + qutsalesmanweightvalue), 2);
}
else if (listmonths[6].ToString("MMM-yyyy") == Month)
{
salesman.Total7Value = Math.Round(Convert.ToDecimal(salesman.Total7Value + qutsalesmanweightvalue), 2);
}
else if (listmonths[7].ToString("MMM-yyyy") == Month)
{
salesman.Total8Value = Math.Round(Convert.ToDecimal(salesman.Total8Value + qutsalesmanweightvalue), 2);
}
else if (listmonths[8].ToString("MMM-yyyy") == Month)
{
salesman.Total9Value = Math.Round(Convert.ToDecimal(salesman.Total9Value + qutsalesmanweightvalue), 2);
}
else if (listmonths[9].ToString("MMM-yyyy") == Month)
{
salesman.Total10Value = Math.Round(Convert.ToDecimal(salesman.Total10Value + qutsalesmanweightvalue), 2);
}
else if (listmonths[10].ToString("MMM-yyyy") == Month)
{
salesman.Total11Value = Math.Round(Convert.ToDecimal(salesman.Total11Value + qutsalesmanweightvalue), 2);
}
else if (listmonths[11].ToString("MMM-yyyy") == Month)
{
salesman.Total12Value = Math.Round(Convert.ToDecimal(salesman.Total12Value + qutsalesmanweightvalue), 2);
}
}
}
}
}
salesman.TotalAEDValue = Math.Round(salesmanaedvalue, 2);
salesman.TotalWeightedAED = Math.Round(salesmanweightvalue, 2);
}
}
catch (Exception ex)
{
}
return new PagedResultDto<TeamReportListDto>(teamDetailCount, TeamDetailListDtos);
}
public async Task<PagedResultDto<TeamReportListDto>> GetAllTeamReport(TeamReportInput input)
{
var query = _TeamRepository.GetAll();
DateTime currentdate = DateTime.Now;
var currentmonth = new DateTime(currentdate.Year, currentdate.Month, 1);
var currentyear = currentmonth.AddYears(1);
var listmonths = Enumerable.Range(0, 12).Select(m => currentmonth.AddMonths(m)).ToArray();
string viewquery = "SELECT * FROM [dbo].[View_ForecastReport]";
DataTable viewtable = new DataTable();
ConnectionAppService db = new ConnectionAppService();
try
{
SqlConnection con = new SqlConnection(db.ConnectionString());
con.Open();
SqlCommand cmd = new SqlCommand(viewquery, con);
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
sda.Fill(viewtable);
}
con.Close();
}
catch (Exception ex)
{
}
var viewdata = (from DataRow dr in viewtable.Rows
select new ForecastDataList
{
Id = Convert.ToInt32(dr["Id"]),
QuotationRefno = Convert.ToString(dr["QuotationRefno"]),
QuotationTotal = Convert.ToDecimal(dr["QuotationTotal"]),
StagePercent = Convert.ToDecimal(dr["StagePercent"]),
EnqStage = Convert.ToString(dr["EnqStage"])
});
if (input.TeamId > 0)
{
query = _TeamRepository.GetAll().Where(p => p.Id == input.TeamId);
}
query = query
.WhereIf(
!input.Filter.IsNullOrWhiteSpace(),
u =>
u.Name.Contains(input.Filter)
);
var reg = (from r in query
select new TeamReportListDto
{
TeamName = r.Name,
TeamId = r.Id,
AccountManager = "",
TotalAEDValue = 0,
TotalWeightedAED = 0,
Total1Value = 0,
Total2Value = 0,
Total3Value = 0,
Total4Value = 0,
Total5Value = 0,
Total6Value = 0,
Total7Value = 0,
Total8Value = 0,
Total9Value = 0,
Total10Value = 0,
Total11Value = 0,
Total12Value = 0,
Total1ValueFormat = listmonths[0].ToString("MMM-yyyy"),
Total2ValueFormat = listmonths[1].ToString("MMM-yyyy"),
Total3ValueFormat = listmonths[2].ToString("MMM-yyyy"),
Total4ValueFormat = listmonths[3].ToString("MMM-yyyy"),
Total5ValueFormat = listmonths[4].ToString("MMM-yyyy"),
Total6ValueFormat = listmonths[5].ToString("MMM-yyyy"),
Total7ValueFormat = listmonths[6].ToString("MMM-yyyy"),
Total8ValueFormat = listmonths[7].ToString("MMM-yyyy"),
Total9ValueFormat = listmonths[8].ToString("MMM-yyyy"),
Total10ValueFormat = listmonths[9].ToString("MMM-yyyy"),
Total11ValueFormat = listmonths[10].ToString("MMM-yyyy"),
Total12ValueFormat = listmonths[11].ToString("MMM-yyyy"),
});
var teamCount = await reg.CountAsync();
var teamlist = await reg
.PageBy(input)
.ToListAsync();
var TeamListDtos = teamlist.MapTo<List<TeamReportListDto>>();
foreach (var team in TeamListDtos)
{
var TeamId = (from p in _TeamRepository.GetAll() where p.Name == team.TeamName select p.Id).FirstOrDefault();
var enqDetail = (from t in _enquiryDetailRepository.GetAll().Where(r => r.TeamId == TeamId && r.ClosureDate >= currentmonth && r.ClosureDate < currentyear) join enq in _inquiryRepository.GetAll().Where(p => p.Lost != true && p.Won != true && p.Junk != true && p.IsClosed != true && p.MileStoneId > 3) on t.InquiryId equals enq.Id select t).ToArray();
decimal teamaedvalue = 0;
decimal teamweightvalue = 0;
if (enqDetail.Length > 0)
{
foreach (var item in enqDetail)
{
decimal qutsalesmanaedvalue = Math.Round(item.EstimationValue, 2);
decimal qutsalesmanweightvalue = 0;
try
{
var data = (from r in viewdata where r.Id == item.InquiryId select r).FirstOrDefault();
if (data != null)
{
qutsalesmanaedvalue = data.QuotationTotal;
qutsalesmanweightvalue = Math.Round(data.StagePercent * data.QuotationTotal / 100, 2);
teamaedvalue = teamaedvalue + qutsalesmanaedvalue;
teamweightvalue = teamweightvalue + qutsalesmanweightvalue;
var InquiryDetailClosureDate = item.ClosureDate;
if (InquiryDetailClosureDate != null)
{
var Month = InquiryDetailClosureDate.GetValueOrDefault().ToString("MMM-yyyy");
if (listmonths[0].ToString("MMM-yyyy") == Month)
{
team.Total1Value = Math.Round(Convert.ToDecimal(team.Total1Value + qutsalesmanweightvalue), 2);
}
else if (listmonths[1].ToString("MMM-yyyy") == Month)
{
team.Total2Value = Math.Round(Convert.ToDecimal(team.Total2Value + qutsalesmanweightvalue), 2);
}
else if (listmonths[2].ToString("MMM-yyyy") == Month)
{
team.Total3Value = Math.Round(Convert.ToDecimal(team.Total3Value + qutsalesmanweightvalue), 2);
}
else if (listmonths[3].ToString("MMM-yyyy") == Month)
{
team.Total4Value = Math.Round(Convert.ToDecimal(team.Total4Value + qutsalesmanweightvalue), 2);
}
else if (listmonths[4].ToString("MMM-yyyy") == Month)
{
team.Total5Value = Math.Round(Convert.ToDecimal(team.Total5Value + qutsalesmanweightvalue), 2);
}
else if (listmonths[5].ToString("MMM-yyyy") == Month)
{
team.Total6Value = Math.Round(Convert.ToDecimal(team.Total6Value + qutsalesmanweightvalue), 2);
}
else if (listmonths[6].ToString("MMM-yyyy") == Month)
{
team.Total7Value = Math.Round(Convert.ToDecimal(team.Total7Value + qutsalesmanweightvalue), 2);
}
else if (listmonths[7].ToString("MMM-yyyy") == Month)
{
team.Total8Value = Math.Round(Convert.ToDecimal(team.Total8Value + qutsalesmanweightvalue), 2);
}
else if (listmonths[8].ToString("MMM-yyyy") == Month)
{
team.Total9Value = Math.Round(Convert.ToDecimal(team.Total9Value + qutsalesmanweightvalue), 2);
}
else if (listmonths[9].ToString("MMM-yyyy") == Month)
{
team.Total10Value = Math.Round(Convert.ToDecimal(team.Total10Value + qutsalesmanweightvalue), 2);
}
else if (listmonths[10].ToString("MMM-yyyy") == Month)
{
team.Total11Value = Math.Round(Convert.ToDecimal(team.Total11Value + qutsalesmanweightvalue), 2);
}
else if (listmonths[11].ToString("MMM-yyyy") == Month)
{
team.Total12Value = Math.Round(Convert.ToDecimal(team.Total12Value + qutsalesmanweightvalue), 2);
}
}
}
}
catch (Exception ex)
{
}
}
}
team.TotalAEDValue = Math.Round(teamaedvalue, 2);
team.TotalWeightedAED = Math.Round(teamweightvalue, 2);
}
return new PagedResultDto<TeamReportListDto>(teamCount, TeamListDtos);
}
public async Task<FileDto> GetQuotationInquiryFilterToExcel(NullableIdDto input)
{
var View = (from v in _ViewRepository.GetAll() where v.Id == input.Id select v).FirstOrDefault();
List<string> RemovedColumns = new List<string>();
if (View.Query != null)
{
RemovedColumns = View.Query.Split(',').ToList<string>();
}
ConnectionAppService db = new ConnectionAppService();
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(db.ConnectionString()))
{
SqlCommand sqlComm = new SqlCommand("Sp_GetQuotationInquiryFilter", con);
sqlComm.Parameters.AddWithValue("@Id", input.Id);
sqlComm.Parameters.AddWithValue("@QuotationCreateBy", null);
sqlComm.Parameters.AddWithValue("@QuotationStatus", null);
sqlComm.Parameters.AddWithValue("@Salesman", null);
sqlComm.Parameters.AddWithValue("@InquiryCreateBy", null);
sqlComm.Parameters.AddWithValue("@PotentialCustomer", null);
sqlComm.Parameters.AddWithValue("@MileStoneName", null);
sqlComm.Parameters.AddWithValue("@EnquiryStatus", null);
sqlComm.Parameters.AddWithValue("@TeamName", null);
sqlComm.Parameters.AddWithValue("@Coordinator", null);
sqlComm.Parameters.AddWithValue("@Designer", null);
sqlComm.Parameters.AddWithValue("@DesignationName", null);
sqlComm.Parameters.AddWithValue("@Emirates", null);
sqlComm.Parameters.AddWithValue("@DepatmentName ", null);
sqlComm.Parameters.AddWithValue("@Categories", null);
sqlComm.Parameters.AddWithValue("@Status", null);
sqlComm.Parameters.AddWithValue("@WhyBafco", null);
sqlComm.Parameters.AddWithValue("@Probability", null);
sqlComm.Parameters.AddWithValue("@InquiryCreation", null);
sqlComm.Parameters.AddWithValue("@QuotationCreation", null);
sqlComm.Parameters.AddWithValue("@ClosureDate", null);
sqlComm.Parameters.AddWithValue("@LastActivityDate", null);
sqlComm.Parameters.AddWithValue("@QtnDateFilterId", 0);
sqlComm.Parameters.AddWithValue("@ClsDateFilterId", 0);
sqlComm.Parameters.AddWithValue("@LastActDateFilterId", 0);
sqlComm.CommandType = CommandType.StoredProcedure;
using (SqlDataAdapter da = new SqlDataAdapter(sqlComm))
{
da.Fill(dt);
}
var Listdto = (from DataRow dr in dt.Rows
select new QuotationInquiryFilter
{
QuotationRefNo = Convert.ToString(dr["REFNO"]),
QuotationCreation = Convert.ToString(dr["QCreationTime"]),
QuotationCreateBy = Convert.ToString(dr["QCreator"]),
QuotationStatus = Convert.ToString(dr["QuotationStatus"]),
Salesman = Convert.ToString(dr["Sales"]),
QuotationValue = Convert.ToString(dr["Total"].ToString()),
TitleOfInquiry = Convert.ToString(dr["Name"]),
InquiryRefNo = Convert.ToString(dr["Submission"]),
InquiryCreation = Convert.ToString(dr["ICreationTime"]),
InquiryCreateBy = Convert.ToString(dr["Creator"]),
PotentialCustomer = Convert.ToString(dr["Company"]),
Email = Convert.ToString(dr["Email"]),
MobileNumber = Convert.ToString(dr["MBNO"]),
MileStoneName = Convert.ToString(dr["Milestone"]),
EnquiryStatus = Convert.ToString(dr["Status"]),
Total = Convert.ToString(dr["Estimation"].ToString()),
TeamName = Convert.ToString(dr["Team"]),
Coordinator = Convert.ToString(dr["Coordinator"]),
Designer = Convert.ToString(dr["Designer"]),
DesignationName = Convert.ToString(dr["Designation"]),
Emirates = Convert.ToString(dr["Location"]),
DepatmentName = Convert.ToString(dr["Depatment"]),
ClosureDate = Convert.ToString(dr["ClosureDate"]),
LastActivity = Convert.ToString(dr["LastActivity"]),
Probability = Convert.ToString(dr["Percentage"]),
AreaName = Convert.ToString(dr["Area"]),
BuildingName = Convert.ToString(dr["Building"]),
Categories = Convert.ToString(dr["LeadType"]),
Status = Convert.ToString(dr["Status"]),
WhyBafco = Convert.ToString(dr["Whybafco"])
});
var QuotationListDtos = Listdto.MapTo<List<QuotationInquiryFilter>>();
return _QuotationInquiryFilterListExcelExporter.ExportToFile(QuotationListDtos, View.Name, RemovedColumns);
}
}
public async Task<FileDto> GetTeamEnquiryReportExcel(NullableIdDto input)
{
DateTime currentdate = DateTime.Now;
var currentmonth = new DateTime(currentdate.Year, currentdate.Month, 1);
var currentyear = currentmonth.AddYears(1);
var listmonths = Enumerable.Range(0, 12).Select(m => currentmonth.AddMonths(m)).ToArray();
var query = _enquiryDetailRepository.GetAll().Where(p => p.AssignedbyId == input.Id && p.ClosureDate >= currentmonth && p.ClosureDate < currentyear);
string viewquery = "SELECT * FROM [dbo].[View_ForecastReport]";
DataTable viewtable = new DataTable();
ConnectionAppService db = new ConnectionAppService();
try
{
SqlConnection con = new SqlConnection(db.ConnectionString());
con.Open();
SqlCommand cmd = new SqlCommand(viewquery, con);
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
sda.Fill(viewtable);
}
con.Close();
}
catch (Exception ex)
{
}
var viewdata = (from DataRow dr in viewtable.Rows
select new ForecastDataList
{
Id = Convert.ToInt32(dr["Id"]),
QuotationRefno = Convert.ToString(dr["QuotationRefno"]),
QuotationTotal = Convert.ToDecimal(dr["QuotationTotal"]),
StagePercent = Convert.ToDecimal(dr["StagePercent"]),
EnqStage = Convert.ToString(dr["EnqStage"])
});
try
{
var inqwdet = (from r in query
join enq in _inquiryRepository.GetAll().Where(p => p.Lost != true && p.Won != true && p.Junk != true && p.IsClosed != true && p.MileStoneId > 3) on r.InquiryId equals enq.Id
select new QuotationReportListDto
{
Date = r.CreationTime.ToString("dd-MMM-yy"),
InquiryName = r.InquiryId > 0 ? r.Inquirys.Name : "",
Status = enq.LeadStatusId > 0 ? enq.LeadStatuss.LeadStatusName : "",
CompanyName = enq.Companys.Name ?? "",
QuotationId = 0,
InquiryId = enq.Id,
ClosureDate = r.ClosureDate ?? null,
AccountManager = r.AssignedbyId > 0 ? r.AbpAccountManager.UserName : "",
NewOrExisting = enq.Companys.NewCustomerTypes.Title ?? "",
Location = enq.LocationId > 0 ? enq.Locations.LocationName : "",
AEDValue = Math.Round(r.EstimationValue, 2),
Stage = "New",
Percentage = 0,
WeightedAED = 0,
Total1Value = 0,
Total2Value = 0,
Total3Value = 0,
Total4Value = 0,
Total5Value = 0,
Total6Value = 0,
Total7Value = 0,
Total8Value = 0,
Total9Value = 0,
Total10Value = 0,
Total11Value = 0,
Total12Value = 0,
Total1ValueFormat = listmonths[0].ToString("MMM-yyyy"),
Total2ValueFormat = listmonths[1].ToString("MMM-yyyy"),
Total3ValueFormat = listmonths[2].ToString("MMM-yyyy"),
Total4ValueFormat = listmonths[3].ToString("MMM-yyyy"),
Total5ValueFormat = listmonths[4].ToString("MMM-yyyy"),
Total6ValueFormat = listmonths[5].ToString("MMM-yyyy"),
Total7ValueFormat = listmonths[6].ToString("MMM-yyyy"),
Total8ValueFormat = listmonths[7].ToString("MMM-yyyy"),
Total9ValueFormat = listmonths[8].ToString("MMM-yyyy"),
Total10ValueFormat = listmonths[9].ToString("MMM-yyyy"),
Total11ValueFormat = listmonths[10].ToString("MMM-yyyy"),
Total12ValueFormat = listmonths[11].ToString("MMM-yyyy"),
ActionDate = r.LastActivity != null ? r.LastActivity.ToString() : "",
Notes = r.Inquirys.Remarks ?? ""
});
inquirylistdto = inqwdet.MapTo<List<QuotationReportListDto>>();
}
catch (Exception ex)
{
}
try
{
foreach (var item in inquirylistdto)
{
var data = (from r in viewdata where r.Id == item.InquiryId select r).FirstOrDefault();
if (data != null)
{
item.AEDValue = data.QuotationTotal;
item.WeightedAED = Math.Round(data.StagePercent * data.QuotationTotal / 100, 2);
item.Stage = data.EnqStage;
item.Percentage = data.StagePercent;
var InquiryDetailClosureDate = item.ClosureDate;
if (InquiryDetailClosureDate != null)
{
var Month = InquiryDetailClosureDate.GetValueOrDefault().ToString("MMM-yyyy");
if (listmonths[0].ToString("MMM-yyyy") == Month)
{
item.Total1Value = Math.Round(item.WeightedAED, 2);
}
else if (listmonths[1].ToString("MMM-yyyy") == Month)
{
item.Total2Value = Math.Round(item.WeightedAED, 2);
}
else if (listmonths[2].ToString("MMM-yyyy") == Month)
{
item.Total3Value = Math.Round(item.WeightedAED, 2);
}
else if (listmonths[3].ToString("MMM-yyyy") == Month)
{
item.Total4Value = Math.Round(item.WeightedAED, 2);
}
else if (listmonths[4].ToString("MMM-yyyy") == Month)
{
item.Total5Value = Math.Round(item.WeightedAED, 2);
}
else if (listmonths[5].ToString("MMM-yyyy") == Month)
{
item.Total6Value = Math.Round(item.WeightedAED, 2);
}
else if (listmonths[6].ToString("MMM-yyyy") == Month)
{
item.Total7Value = Math.Round(item.WeightedAED, 2);
}
else if (listmonths[7].ToString("MMM-yyyy") == Month)
{
item.Total8Value = Math.Round(item.WeightedAED, 2);
}
else if (listmonths[8].ToString("MMM-yyyy") == Month)
{
item.Total9Value = Math.Round(item.WeightedAED, 2);
}
else if (listmonths[9].ToString("MMM-yyyy") == Month)
{
item.Total10Value = Math.Round(item.WeightedAED, 2);
}
else if (listmonths[10].ToString("MMM-yyyy") == Month)
{
item.Total11Value = Math.Round(item.WeightedAED, 2);
}
else if (listmonths[11].ToString("MMM-yyyy") == Month)
{
item.Total12Value = Math.Round(item.WeightedAED, 2);
}
}
}
}
}
catch (Exception ex)
{
throw;
}
QuotationReportListDto TotalReport = new QuotationReportListDto
{
Date = "Total",
AEDValue = 0,
WeightedAED = 0,
Total1Value = 0,
Total2Value = 0,
Total3Value = 0,
Total4Value = 0,
Total5Value = 0,
Total6Value = 0,
Total7Value = 0,
Total8Value = 0,
Total9Value = 0,
Total10Value = 0,
Total11Value = 0,
Total12Value = 0
};
foreach (var item in inquirylistdto)
{
TotalReport.AEDValue = Decimal.Add(TotalReport.AEDValue, item.AEDValue);
TotalReport.WeightedAED = Decimal.Add(TotalReport.WeightedAED, item.WeightedAED);
TotalReport.Total1Value = Decimal.Add(TotalReport.Total1Value, item.Total1Value);
TotalReport.Total2Value = Decimal.Add(TotalReport.Total2Value, item.Total2Value);
TotalReport.Total3Value = Decimal.Add(TotalReport.Total3Value, item.Total3Value);
TotalReport.Total4Value = Decimal.Add(TotalReport.Total4Value, item.Total4Value);
TotalReport.Total5Value = Decimal.Add(TotalReport.Total5Value, item.Total5Value);
TotalReport.Total6Value = Decimal.Add(TotalReport.Total6Value, item.Total6Value);
TotalReport.Total7Value = Decimal.Add(TotalReport.Total7Value, item.Total7Value);
TotalReport.Total8Value = Decimal.Add(TotalReport.Total8Value, item.Total8Value);
TotalReport.Total9Value = Decimal.Add(TotalReport.Total9Value, item.Total9Value);
TotalReport.Total10Value = Decimal.Add(TotalReport.Total10Value, item.Total10Value);
TotalReport.Total11Value = Decimal.Add(TotalReport.Total11Value, item.Total11Value);
TotalReport.Total12Value = Decimal.Add(TotalReport.Total12Value, item.Total12Value);
}
return _TeamEnquiryReportExcelExporter.ExportToFile(inquirylistdto, TotalReport);
}
public async Task<FileDto> GetTeamReportExcel(NullableIdDto input)
{
var query = _TeamDetailRepository.GetAll().Where(p => p.TeamId == input.Id);
DateTime currentdate = DateTime.Now;
var currentmonth = new DateTime(currentdate.Year, currentdate.Month, 1);
var currentyear = currentmonth.AddYears(1);
var listmonths = Enumerable.Range(0, 12).Select(m => currentmonth.AddMonths(m)).ToArray();
string viewquery = "SELECT * FROM [dbo].[View_ForecastReport]";
DataTable viewtable = new DataTable();
ConnectionAppService db = new ConnectionAppService();
try
{
SqlConnection con = new SqlConnection(db.ConnectionString());
con.Open();
SqlCommand cmd = new SqlCommand(viewquery, con);
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
sda.Fill(viewtable);
}
con.Close();
}
catch (Exception ex)
{
}
var viewdata = (from DataRow dr in viewtable.Rows
select new ForecastDataList
{
Id = Convert.ToInt32(dr["Id"]),
QuotationRefno = Convert.ToString(dr["QuotationRefno"]),
QuotationTotal = Convert.ToDecimal(dr["QuotationTotal"]),
StagePercent = Convert.ToDecimal(dr["StagePercent"]),
EnqStage = Convert.ToString(dr["EnqStage"])
});
var reg = (from r in query
select new TeamReportListDto
{
TeamName = r.Team.Name ?? "",
AccountManager = r.Salesman.UserName ?? "",
AccountManagerId = r.SalesmanId,
TotalAEDValue = 0,
TeamId = (int)(r.TeamId ?? 0),
TotalWeightedAED = 0,
Total1Value = 0,
Total2Value = 0,
Total3Value = 0,
Total4Value = 0,
Total5Value = 0,
Total6Value = 0,
Total7Value = 0,
Total8Value = 0,
Total9Value = 0,
Total10Value = 0,
Total11Value = 0,
Total12Value = 0,
Total1ValueFormat = listmonths[0].ToString("MMM-yyyy"),
Total2ValueFormat = listmonths[1].ToString("MMM-yyyy"),
Total3ValueFormat = listmonths[2].ToString("MMM-yyyy"),
Total4ValueFormat = listmonths[3].ToString("MMM-yyyy"),
Total5ValueFormat = listmonths[4].ToString("MMM-yyyy"),
Total6ValueFormat = listmonths[5].ToString("MMM-yyyy"),
Total7ValueFormat = listmonths[6].ToString("MMM-yyyy"),
Total8ValueFormat = listmonths[7].ToString("MMM-yyyy"),
Total9ValueFormat = listmonths[8].ToString("MMM-yyyy"),
Total10ValueFormat = listmonths[9].ToString("MMM-yyyy"),
Total11ValueFormat = listmonths[10].ToString("MMM-yyyy"),
Total12ValueFormat = listmonths[11].ToString("MMM-yyyy"),
});
var TeamDetailListDtos = reg.MapTo<List<TeamReportListDto>>();
try
{
foreach (var salesman in TeamDetailListDtos)
{
var SalesmanId = (from u in UserManager.Users where u.UserName == salesman.AccountManager select u.Id).FirstOrDefault();
var enqDetail = (from t in _enquiryDetailRepository.GetAll().Where(r => r.AssignedbyId == SalesmanId && r.ClosureDate >= currentmonth && r.ClosureDate < currentyear) join enq in _inquiryRepository.GetAll().Where(p => p.Lost != true && p.Won != true && p.Junk != true && p.IsClosed != true && p.MileStoneId > 3) on t.InquiryId equals enq.Id select t).ToArray();
decimal salesmanaedvalue = 0;
decimal salesmanweightvalue = 0;
if (enqDetail.Length > 0)
{
foreach (var item in enqDetail)
{
decimal qutsalesmanaedvalue = Math.Round(item.EstimationValue, 2);
decimal qutsalesmanweightvalue = 0;
var data = (from r in viewdata where r.Id == item.InquiryId select r).FirstOrDefault();
if (data != null)
{
qutsalesmanaedvalue = data.QuotationTotal;
qutsalesmanweightvalue = Math.Round(data.StagePercent * data.QuotationTotal / 100, 2);
salesmanaedvalue = salesmanaedvalue + qutsalesmanaedvalue;
salesmanweightvalue = salesmanweightvalue + qutsalesmanweightvalue;
var InquiryDetailClosureDate = item.ClosureDate;
if (InquiryDetailClosureDate != null)
{
var Month = InquiryDetailClosureDate.GetValueOrDefault().ToString("MMM-yyyy");
if (listmonths[0].ToString("MMM-yyyy") == Month)
{
salesman.Total1Value = Math.Round(Convert.ToDecimal(salesman.Total1Value + qutsalesmanweightvalue), 2);
}
else if (listmonths[1].ToString("MMM-yyyy") == Month)
{
salesman.Total2Value = Math.Round(Convert.ToDecimal(salesman.Total2Value + qutsalesmanweightvalue), 2);
}
else if (listmonths[2].ToString("MMM-yyyy") == Month)
{
salesman.Total3Value = Math.Round(Convert.ToDecimal(salesman.Total3Value + qutsalesmanweightvalue), 2);
}
else if (listmonths[3].ToString("MMM-yyyy") == Month)
{
salesman.Total4Value = Math.Round(Convert.ToDecimal(salesman.Total4Value + qutsalesmanweightvalue), 2);
}
else if (listmonths[4].ToString("MMM-yyyy") == Month)
{
salesman.Total5Value = Math.Round(Convert.ToDecimal(salesman.Total5Value + qutsalesmanweightvalue), 2);
}
else if (listmonths[5].ToString("MMM-yyyy") == Month)
{
salesman.Total6Value = Math.Round(Convert.ToDecimal(salesman.Total6Value + qutsalesmanweightvalue), 2);
}
else if (listmonths[6].ToString("MMM-yyyy") == Month)
{
salesman.Total7Value = Math.Round(Convert.ToDecimal(salesman.Total7Value + qutsalesmanweightvalue), 2);
}
else if (listmonths[7].ToString("MMM-yyyy") == Month)
{
salesman.Total8Value = Math.Round(Convert.ToDecimal(salesman.Total8Value + qutsalesmanweightvalue), 2);
}
else if (listmonths[8].ToString("MMM-yyyy") == Month)
{
salesman.Total9Value = Math.Round(Convert.ToDecimal(salesman.Total9Value + qutsalesmanweightvalue), 2);
}
else if (listmonths[9].ToString("MMM-yyyy") == Month)
{
salesman.Total10Value = Math.Round(Convert.ToDecimal(salesman.Total10Value + qutsalesmanweightvalue), 2);
}
else if (listmonths[10].ToString("MMM-yyyy") == Month)
{
salesman.Total11Value = Math.Round(Convert.ToDecimal(salesman.Total11Value + qutsalesmanweightvalue), 2);
}
else if (listmonths[11].ToString("MMM-yyyy") == Month)
{
salesman.Total12Value = Math.Round(Convert.ToDecimal(salesman.Total12Value + qutsalesmanweightvalue), 2);
}
}
}
}
}
salesman.TotalAEDValue = Math.Round(salesmanaedvalue, 2);
salesman.TotalWeightedAED = Math.Round(salesmanweightvalue, 2);
}
}
catch (Exception ex)
{
}
TeamReportListDto TotalReport = new TeamReportListDto
{
AccountManager = "Total",
TotalAEDValue = 0,
TotalWeightedAED = 0,
Total1Value = 0,
Total2Value = 0,
Total3Value = 0,
Total4Value = 0,
Total5Value = 0,
Total6Value = 0,
Total7Value = 0,
Total8Value = 0,
Total9Value = 0,
Total10Value = 0,
Total11Value = 0,
Total12Value = 0
};
foreach (var item in TeamDetailListDtos)
{
TotalReport.TotalAEDValue = Decimal.Add(TotalReport.TotalAEDValue, item.TotalAEDValue);
TotalReport.TotalWeightedAED = Decimal.Add(TotalReport.TotalWeightedAED, item.TotalWeightedAED);
TotalReport.Total1Value = Decimal.Add(TotalReport.Total1Value, item.Total1Value);
TotalReport.Total2Value = Decimal.Add(TotalReport.Total2Value, item.Total2Value);
TotalReport.Total3Value = Decimal.Add(TotalReport.Total3Value, item.Total3Value);
TotalReport.Total4Value = Decimal.Add(TotalReport.Total4Value, item.Total4Value);
TotalReport.Total5Value = Decimal.Add(TotalReport.Total5Value, item.Total5Value);
TotalReport.Total6Value = Decimal.Add(TotalReport.Total6Value, item.Total6Value);
TotalReport.Total7Value = Decimal.Add(TotalReport.Total7Value, item.Total7Value);
TotalReport.Total8Value = Decimal.Add(TotalReport.Total8Value, item.Total8Value);
TotalReport.Total9Value = Decimal.Add(TotalReport.Total9Value, item.Total9Value);
TotalReport.Total10Value = Decimal.Add(TotalReport.Total10Value, item.Total10Value);
TotalReport.Total11Value = Decimal.Add(TotalReport.Total11Value, item.Total11Value);
TotalReport.Total12Value = Decimal.Add(TotalReport.Total12Value, item.Total12Value);
}
return _TeamReportExcelExporter.ExportToFile(TeamDetailListDtos, TotalReport);
}
public async Task<FileDto> GetAllTeamReportExcel()
{
var query = _TeamRepository.GetAll();
DateTime currentdate = DateTime.Now;
var currentmonth = new DateTime(currentdate.Year, currentdate.Month, 1);
var currentyear = currentmonth.AddYears(1);
var listmonths = Enumerable.Range(0, 12).Select(m => currentmonth.AddMonths(m)).ToArray();
string viewquery = "SELECT * FROM [dbo].[View_ForecastReport]";
DataTable viewtable = new DataTable();
ConnectionAppService db = new ConnectionAppService();
try
{
SqlConnection con = new SqlConnection(db.ConnectionString());
con.Open();
SqlCommand cmd = new SqlCommand(viewquery, con);
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
sda.Fill(viewtable);
}
con.Close();
}
catch (Exception ex)
{
}
var viewdata = (from DataRow dr in viewtable.Rows
select new ForecastDataList
{
Id = Convert.ToInt32(dr["Id"]),
QuotationRefno = Convert.ToString(dr["QuotationRefno"]),
QuotationTotal = Convert.ToDecimal(dr["QuotationTotal"]),
StagePercent = Convert.ToDecimal(dr["StagePercent"]),
EnqStage = Convert.ToString(dr["EnqStage"])
});
var reg = (from r in query
select new TeamReportListDto
{
TeamName = r.Name,
TeamId = r.Id,
AccountManager = "",
TotalAEDValue = 0,
TotalWeightedAED = 0,
Total1Value = 0,
Total2Value = 0,
Total3Value = 0,
Total4Value = 0,
Total5Value = 0,
Total6Value = 0,
Total7Value = 0,
Total8Value = 0,
Total9Value = 0,
Total10Value = 0,
Total11Value = 0,
Total12Value = 0,
Total1ValueFormat = listmonths[0].ToString("MMM-yyyy"),
Total2ValueFormat = listmonths[1].ToString("MMM-yyyy"),
Total3ValueFormat = listmonths[2].ToString("MMM-yyyy"),
Total4ValueFormat = listmonths[3].ToString("MMM-yyyy"),
Total5ValueFormat = listmonths[4].ToString("MMM-yyyy"),
Total6ValueFormat = listmonths[5].ToString("MMM-yyyy"),
Total7ValueFormat = listmonths[6].ToString("MMM-yyyy"),
Total8ValueFormat = listmonths[7].ToString("MMM-yyyy"),
Total9ValueFormat = listmonths[8].ToString("MMM-yyyy"),
Total10ValueFormat = listmonths[9].ToString("MMM-yyyy"),
Total11ValueFormat = listmonths[10].ToString("MMM-yyyy"),
Total12ValueFormat = listmonths[11].ToString("MMM-yyyy"),
});
var TeamListDtos = reg.MapTo<List<TeamReportListDto>>();
foreach (var team in TeamListDtos)
{
var TeamId = (from p in _TeamRepository.GetAll() where p.Name == team.TeamName select p.Id).FirstOrDefault();
var enqDetail = (from t in _enquiryDetailRepository.GetAll().Where(r => r.TeamId == TeamId && r.ClosureDate >= currentmonth && r.ClosureDate < currentyear) join enq in _inquiryRepository.GetAll().Where(p => p.Lost != true && p.Won != true && p.Junk != true && p.IsClosed != true && p.MileStoneId > 3) on t.InquiryId equals enq.Id select t).ToArray();
decimal teamaedvalue = 0;
decimal teamweightvalue = 0;
if (enqDetail.Length > 0)
{
foreach (var item in enqDetail)
{
decimal qutsalesmanaedvalue = Math.Round(item.EstimationValue, 2);
decimal qutsalesmanweightvalue = 0;
try
{
var data = (from r in viewdata where r.Id == item.InquiryId select r).FirstOrDefault();
if (data != null)
{
qutsalesmanaedvalue = data.QuotationTotal;
qutsalesmanweightvalue = Math.Round(data.StagePercent * data.QuotationTotal / 100, 2);
teamaedvalue = teamaedvalue + qutsalesmanaedvalue;
teamweightvalue = teamweightvalue + qutsalesmanweightvalue;
var InquiryDetailClosureDate = item.ClosureDate;
if (InquiryDetailClosureDate != null)
{
var Month = InquiryDetailClosureDate.GetValueOrDefault().ToString("MMM-yyyy");
if (listmonths[0].ToString("MMM-yyyy") == Month)
{
team.Total1Value = Math.Round(Convert.ToDecimal(team.Total1Value + qutsalesmanweightvalue), 2);
}
else if (listmonths[1].ToString("MMM-yyyy") == Month)
{
team.Total2Value = Math.Round(Convert.ToDecimal(team.Total2Value + qutsalesmanweightvalue), 2);
}
else if (listmonths[2].ToString("MMM-yyyy") == Month)
{
team.Total3Value = Math.Round(Convert.ToDecimal(team.Total3Value + qutsalesmanweightvalue), 2);
}
else if (listmonths[3].ToString("MMM-yyyy") == Month)
{
team.Total4Value = Math.Round(Convert.ToDecimal(team.Total4Value + qutsalesmanweightvalue), 2);
}
else if (listmonths[4].ToString("MMM-yyyy") == Month)
{
team.Total5Value = Math.Round(Convert.ToDecimal(team.Total5Value + qutsalesmanweightvalue), 2);
}
else if (listmonths[5].ToString("MMM-yyyy") == Month)
{
team.Total6Value = Math.Round(Convert.ToDecimal(team.Total6Value + qutsalesmanweightvalue), 2);
}
else if (listmonths[6].ToString("MMM-yyyy") == Month)
{
team.Total7Value = Math.Round(Convert.ToDecimal(team.Total7Value + qutsalesmanweightvalue), 2);
}
else if (listmonths[7].ToString("MMM-yyyy") == Month)
{
team.Total8Value = Math.Round(Convert.ToDecimal(team.Total8Value + qutsalesmanweightvalue), 2);
}
else if (listmonths[8].ToString("MMM-yyyy") == Month)
{
team.Total9Value = Math.Round(Convert.ToDecimal(team.Total9Value + qutsalesmanweightvalue), 2);
}
else if (listmonths[9].ToString("MMM-yyyy") == Month)
{
team.Total10Value = Math.Round(Convert.ToDecimal(team.Total10Value + qutsalesmanweightvalue), 2);
}
else if (listmonths[10].ToString("MMM-yyyy") == Month)
{
team.Total11Value = Math.Round(Convert.ToDecimal(team.Total11Value + qutsalesmanweightvalue), 2);
}
else if (listmonths[11].ToString("MMM-yyyy") == Month)
{
team.Total12Value = Math.Round(Convert.ToDecimal(team.Total12Value + qutsalesmanweightvalue), 2);
}
}
}
}
catch (Exception ex)
{
}
}
}
team.TotalAEDValue = Math.Round(teamaedvalue, 2);
team.TotalWeightedAED = Math.Round(teamweightvalue, 2);
}
TeamReportListDto TotalReport = new TeamReportListDto
{
TeamName = "Total",
TotalAEDValue = 0,
TotalWeightedAED = 0,
Total1Value = 0,
Total2Value = 0,
Total3Value = 0,
Total4Value = 0,
Total5Value = 0,
Total6Value = 0,
Total7Value = 0,
Total8Value = 0,
Total9Value = 0,
Total10Value = 0,
Total11Value = 0,
Total12Value = 0
};
foreach (var item in TeamListDtos)
{
TotalReport.TotalAEDValue = Decimal.Add(TotalReport.TotalAEDValue, item.TotalAEDValue);
TotalReport.TotalWeightedAED = Decimal.Add(TotalReport.TotalWeightedAED, item.TotalWeightedAED);
TotalReport.Total1Value = Decimal.Add(TotalReport.Total1Value, item.Total1Value);
TotalReport.Total2Value = Decimal.Add(TotalReport.Total2Value, item.Total2Value);
TotalReport.Total3Value = Decimal.Add(TotalReport.Total3Value, item.Total3Value);
TotalReport.Total4Value = Decimal.Add(TotalReport.Total4Value, item.Total4Value);
TotalReport.Total5Value = Decimal.Add(TotalReport.Total5Value, item.Total5Value);
TotalReport.Total6Value = Decimal.Add(TotalReport.Total6Value, item.Total6Value);
TotalReport.Total7Value = Decimal.Add(TotalReport.Total7Value, item.Total7Value);
TotalReport.Total8Value = Decimal.Add(TotalReport.Total8Value, item.Total8Value);
TotalReport.Total9Value = Decimal.Add(TotalReport.Total9Value, item.Total9Value);
TotalReport.Total10Value = Decimal.Add(TotalReport.Total10Value, item.Total10Value);
TotalReport.Total11Value = Decimal.Add(TotalReport.Total11Value, item.Total11Value);
TotalReport.Total12Value = Decimal.Add(TotalReport.Total12Value, item.Total12Value);
}
return _AllTeamReportExcelExporter.ExportToFile(TeamListDtos, TotalReport);
}
public void StandardPreviewExcelNew(NullableIdDto input)
{
var sectionGroup = (from s in _sectionRepository.GetAll() where s.QuotationId == input.Id select s).ToArray();
var query = _quotationProductRepository.GetAll().Where(p => p.QuotationId == input.Id);
var reg = (from z in query
select new QuotationProductListDto
{
Id = z.Id,
ProductCode = z.ProductId > 0 ? z.product.ProductCode : z.ProductCode,
Quantity = z.Quantity,
Discount = z.Discount,
UnitOfMeasurement = z.UnitOfMeasurement,
UnitOfPrice = z.UnitOfPrice,
TotalAmount = z.Approval == true ? z.TotalAmount : z.OverAllPrice,
ProductId = z.ProductId,
RefNo = z.QuotationId > 0 ? z.quotation.RefNo : "",
SectionId = z.SectionId,
SectionName = z.SectionId != null ? z.section.Name : "",
Locked = z.Locked,
CreationTime = z.CreationTime,
TemporaryProductId = z.TemporaryProductId,
Description = z.ProductId > 0 ? z.product.Description : z.TemporaryProducts.Description,
ImageUrl = "Common/Images/img-not-available.png"
}).ToList();
foreach (var data in reg)
{
if (data.TemporaryProductId > 0)
{
var TempImage = _TempProductImageRepository.GetAll().Where(p => p.TemporaryProductId == data.TemporaryProductId).FirstOrDefault();
if (TempImage != null)
{
data.ImageUrl = TempImage.ImageUrl;
}
}
else if (data.ProductId > 0)
{
var Image = _ProductImageRepository.GetAll().Where(q => q.ProductId == data.ProductId).FirstOrDefault();
if (Image != null)
{
data.ImageUrl = Image.ImageUrl;
}
}
}
var QuotationProductListDtos = reg.MapTo<List<QuotationProductListDto>>();
var SubListout = new List<QuotationProductOutput>();
foreach (var newsts in sectionGroup)
{
var subtotal = (from q in reg where q.SectionId == newsts.Id select q.TotalAmount).Sum();
SubListout.Add(new QuotationProductOutput
{
name = newsts.Name,
subtotal = subtotal,
GetQuotationProduct = (from t in reg where t.SectionId == newsts.Id select t).OrderBy(p => p.CreationTime).ToArray()
});
}
string pathSource = _hostingEnvironment.WebRootPath + "\\Common\\File\\Excel\\PreviewExcelTemplate.xlsx";
IWorkbook templateWorkbook;
using (FileStream fs = new FileStream(pathSource, FileMode.Open, FileAccess.Read))
{
templateWorkbook = new XSSFWorkbook(fs);
}
string sheetName = "Preview";
ISheet sheet = templateWorkbook.GetSheet(sheetName);
var QuotationDetail = _quotationRepository.GetAll().Where(p => p.Id == input.Id);
var Quotations = (from a in QuotationDetail
select new QuotationListDto
{
Id = a.Id,
SCreationTime = a.CreationTime.ToString("dd-MMM-yyyy"),
NewCompanyId = a.NewCompanyId,
CompanyName = a.NewCompanys.Name,
AttentionContactId = a.AttentionContactId,
AttentionName = a.AttentionContactId != null ? (a.AttentionContact.TitleOfCourtesies.Name + "." + a.AttentionContact.Name + " " + a.AttentionContact.LastName) : "",
MobileNumber = a.MobileNumber ?? "",
InquiryId = a.InquiryId ?? 0,
InquiryName = a.Inquiry.LocationId != null ? a.Inquiry.Locations.LocationName : "Dubai, UAE",
Email = a.Email ?? "",
SalesPersonId = a.SalesPersonId,
SalesPersonName = a.SalesPerson.Name,
RFQNo = a.RFQNo ?? "",
RefNo = a.RefNo ?? "",
CustomerId = a.NewCompanys.CustomerId ?? "",
RefQNo = a.RefQNo ?? "",
Name = a.Name ?? "Quotation"
}).FirstOrDefault();
ICell QuotationName = sheet.GetRow(5).GetCell(0);
QuotationName.SetCellValue(Quotations.Name);
ICell QuotationDate = sheet.GetRow(7).GetCell(1);
QuotationDate.SetCellValue(Quotations.SCreationTime);
ICell QuotationClient = sheet.GetRow(8).GetCell(1);
QuotationClient.SetCellValue(Quotations.CompanyName);
ICell QuotationAttn = sheet.GetRow(9).GetCell(1);
QuotationAttn.SetCellValue(Quotations.AttentionName);
ICell QuotationTel = sheet.GetRow(10).GetCell(1);
QuotationTel.SetCellValue(Quotations.MobileNumber);
ICell QuotationAdd = sheet.GetRow(11).GetCell(1);
QuotationAdd.SetCellValue(Quotations.InquiryName);
ICell QuotationEmail = sheet.GetRow(12).GetCell(1);
QuotationEmail.SetCellValue(Quotations.Email);
ICell QuotationSales = sheet.GetRow(7).GetCell(5);
QuotationSales.SetCellValue(Quotations.SalesPersonName);
ICell QuotationRFQ = sheet.GetRow(7).GetCell(7);
QuotationRFQ.SetCellValue(Quotations.RFQNo);
ICell QuotationNo = sheet.GetRow(9).GetCell(3);
QuotationNo.SetCellValue("Quotation No.\n" + Quotations.RefNo);
ICell QuotationCustomerId = sheet.GetRow(9).GetCell(5);
QuotationCustomerId.SetCellValue("Customer ID\n" + Quotations.CustomerId);
ICell QuotationRefNo = sheet.GetRow(9).GetCell(7);
QuotationRefNo.SetCellValue("Ref No\n" + Quotations.RefQNo);
string TotalAmountFormula = "H7";
int r = 49;
if (SubListout.Count > 0)
{
for (int sectionIndex = 0; sectionIndex < SubListout.Count; sectionIndex++)
{
IRow SectionRow = sheet.GetRow(15).CopyRowTo(r);
ICell SectionCellName = SectionRow.GetCell(0);
SectionCellName.SetCellValue(SubListout[sectionIndex].name);
if (SubListout[sectionIndex].GetQuotationProduct.Length > 0)
{
for (int p = 0; p < SubListout[sectionIndex].GetQuotationProduct.Length; p++)
{
IRow ProductRow = sheet.GetRow(16).CopyRowTo(p + (r + 1));
ProductRow.Height = sheet.GetRow(16).Height;
ICell ProductNo = ProductRow.GetCell(0);
ICell ProductDesp = ProductRow.GetCell(1);
ICell ProductQty = ProductRow.GetCell(3);
ICell ProductUP = ProductRow.GetCell(5);
ICell ProductAmount = ProductRow.GetCell(7);
var rootpath = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
Configuration = rootpath.Build();
var root = Configuration["App:ServerRootAddress"];
WebClient wc = new WebClient();
byte[] data = wc.DownloadData(root + "/" + SubListout[sectionIndex].GetQuotationProduct[p].ImageUrl);
int picInd = templateWorkbook.AddPicture(data, PictureType.PNG);
XSSFCreationHelper helper = templateWorkbook.GetCreationHelper() as XSSFCreationHelper;
XSSFDrawing drawing = sheet.CreateDrawingPatriarch() as XSSFDrawing;
XSSFClientAnchor anchor = helper.CreateClientAnchor() as XSSFClientAnchor;
anchor.Col1 = 2;
anchor.Row1 = p + (r - 33);
anchor.Dx1 = 400000;
anchor.Dy1 = 400000;
XSSFPicture ProductImg = drawing.CreatePicture(anchor, picInd) as XSSFPicture;
ProductImg.Resize(0.5, 0.5);
ProductNo.SetCellValue(p + 1);
string DecodedText = HttpUtility.HtmlDecode(SubListout[sectionIndex].GetQuotationProduct[p].Description);
string ProdDescription = Regex.Replace(Regex.Replace(DecodedText, "</p>", "\n"), "<.*?>", String.Empty);
ProductDesp.SetCellValue(ProdDescription);
ProductQty.SetCellValue((double)SubListout[sectionIndex].GetQuotationProduct[p].Quantity);
ProductUP.SetCellValue((double)SubListout[sectionIndex].GetQuotationProduct[p].UnitOfPrice);
ProductAmount.SetCellFormula("IF(OR(ISBLANK(G" + (p + r + 2) + ")),(D" + (p + r + 2) + "*F" + (p + r + 2) + "),(D" + (p + r + 2) + "*G" + (p + r + 2) + "))");
}
}
IRow SubTotalRow = sheet.GetRow(17).CopyRowTo(r + 1 + SubListout[sectionIndex].GetQuotationProduct.Length);
ICell SubTotalCell = SubTotalRow.GetCell(7);
SubTotalCell.SetCellFormula("SUM(H" + (r + 2) + ":H" + (r + 1 + SubListout[sectionIndex].GetQuotationProduct.Length) + ")");
TotalAmountFormula = TotalAmountFormula + ",H" + (r + 2 + SubListout[sectionIndex].GetQuotationProduct.Length);
r = (r + 2 + SubListout[sectionIndex].GetQuotationProduct.Length);
}
}
int startRow = 18;
for (int n = 0; n < 30; n++)
{
IRow SummaryRow = sheet.GetRow(startRow).CopyRowTo(n + r);
if (startRow == 21)
{
ICell TotalAmount = SummaryRow.GetCell(7);
TotalAmount.SetCellFormula("SUM(" + TotalAmountFormula + ")");
}
if (startRow == 22)
{
ICell TotalAmountWords = SummaryRow.GetCell(2);
decimal NetAmount = (from TNT in reg select (TNT.Quantity * TNT.UnitOfPrice)).Sum();
NumberToWordsConverter converter = new NumberToWordsConverter();
long daet = decimal.ToInt64(NetAmount);
string TotalString = converter.Convert(daet);
var decPlaces = (int)(((decimal)NetAmount % 1) * 100);
string fils = decPlaces > 0 ? decPlaces.ToString() : "0";
TotalAmountWords.SetCellValue("Dirhams " + TotalString + " and Fils " + fils + "/100 only");
}
startRow++;
}
for (int i = 0; i < 34; i++)
{
IRow DeleteRow = sheet.GetRow(15);
sheet.RemoveRow(DeleteRow);
sheet.ShiftRows(16, sheet.LastRowNum, -1);
}
templateWorkbook.SetSheetName(0, "StandardPreview_" + input.Id + "");
string newPathSource = _hostingEnvironment.WebRootPath + "\\Common\\Excel\\";
if (!Directory.Exists(newPathSource))
{
Directory.CreateDirectory(newPathSource);
}
string fileName = "StandardPreviewExcel_" + input.Id + ".xlsx";
if (System.IO.File.Exists(newPathSource + fileName))
{
System.IO.File.Delete(newPathSource + fileName);
}
using (FileStream fs = new FileStream(newPathSource + fileName, FileMode.Create, FileAccess.Write))
{
templateWorkbook.Write(fs);
}
//string Source = _webUrlService.GetServerRootAddress() + @"/Common/Excel/"+ fileName;
//using (var client = new WebClient())
//{
// client.DownloadFile(Source, fileName);
//}
}
public async Task QuotationRevaluation(QuotationRevaluationInput input)
{
ConnectionAppService db = new ConnectionAppService();
DataTable ds = new DataTable();
using (SqlConnection conn = new SqlConnection(db.ConnectionString()))
{
SqlCommand sqlComm = new SqlCommand("Quotation_Revaluation", conn);
sqlComm.Parameters.AddWithValue("@QuotationId", input.Id);
sqlComm.Parameters.AddWithValue("@Num", input.Type);
sqlComm.CommandType = CommandType.StoredProcedure;
conn.Open();
sqlComm.ExecuteNonQuery();
conn.Close();
}
}
public async Task SendLostMail(int id, int? CompatitorId, int? ReasonId, string ReasonRemark)
{
var cidd = "None";
var ridd = "None";
var rrk = "None";
var qut = (from r in _quotationRepository.GetAll()
where r.Id == id && r.Revised != true
select new LostEmailFirst
{
Id = r.Id,
EnquiryId = r.InquiryId,
SalesPersonId = r.SalesPersonId,
EnquiryRefNo = r.Inquiry.SubMmissionId,
QuotationRefNo = r.RefNo,
FirstName = r.SalesPerson.Name,
LastName = r.SalesPerson.Surname
}).FirstOrDefault();
var qutsal = _quotationRepository.GetAll().Where(p => p.Id == id && p.Revised != true).Select(p => p.SalesPerson.UserName).FirstOrDefault();
var com = _quotationRepository.GetAll().Where(p => p.Id == id && p.Revised != true).Select(p => p.NewCompanys.Name).FirstOrDefault();
if (CompatitorId != null)
{
cidd = _newCompanyRepository.GetAll().Where(p => p.Id == (int)CompatitorId).Select(p => p.Name).FirstOrDefault();
}
if (ReasonId != null)
{
ridd = _leadReasonTrackRepository.GetAll().Where(p => p.Id == (int)ReasonId).Select(p => p.LeadReasonName).FirstOrDefault();
}
if (ReasonRemark != null)
{
rrk = com;
}
try
{
await _userEmailer.LostEmailSendSalesManager(qut.Id, qut.EnquiryId, cidd, ridd, rrk, qut.SalesPersonId, qut.EnquiryRefNo, qut.QuotationRefNo, qut.FirstName + ' ' + qut.LastName);
}
catch (Exception ex)
{
throw;
}
}
}
public class DiscountEmailFirst
{
public int Id { get; set; }
public virtual string QuotationRefNo { get; set; }
public virtual long? SalesPersonId { get; set; }
public virtual string FirstName { get; set; }
public virtual string LastName { get; set; }
}
public class LostEmailFirst
{
public int Id { get; set; }
public virtual string EnquiryRefNo { get; set; }
public virtual string QuotationRefNo { get; set; }
public virtual long? SalesPersonId { get; set; }
public virtual string FirstName { get; set; }
public virtual string LastName { get; set; }
public virtual int? EnquiryId { get; set; }
}
public class ForecastDataList
{
public int Id { get; set; }
public string QuotationRefno { get; set; }
public decimal QuotationTotal { get; set; }
public decimal StagePercent { get; set; }
public string EnqStage { get; set; }
public int SalesPersonId { get; set; }
public int CoordinatorId { get; set; }
public int DesignerId { get; set; }
public int SalesManagerId { get; set; }
public int CreatorUserId { get; set; }
}
public class QuotationRevisionInput
{
public int Id { get; set; }
public int TypeId { get; set; }
public virtual DateTime NextActivity { get; set; }
}
public class QuotationRevaluationInput
{
public int Id { get; set; }
public int Type { get; set; }
}
public class NumberToWordsConverter
{
public static readonly string[] UnitsMap = { "Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" };
public static readonly string[] TensMap = { "Zero", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" };
public static readonly Dictionary<long, string> OrdinalExceptions = new Dictionary<long, string>
{
{1, "First"},
{2, "Second"},
{3, "Third"},
{4, "Fourth"},
{5, "Fifth"},
{8, "eighth"},
{9, "Ninth"},
{12, "Twelfth"},
};
public string Convert(long number)
{
return Convert(number, false);
}
public string ConvertToOrdinal(int number)
{
return Convert(number, true);
}
public string Convert(long number, bool isOrdinal)
{
if (number == 0)
return GetUnitValue(0, isOrdinal);
if (number < 0)
return string.Format("minus {0}", Convert(-number));
var parts = new List<string>();
if ((number / 1000000000000000000) > 0)
{
parts.Add(string.Format("{0} Quintillion", Convert(number / 1000000000000000000)));
number %= 1000000000000000000;
}
if ((number / 1000000000000000) > 0)
{
parts.Add(string.Format("{0} Quadrillion", Convert(number / 1000000000000000)));
number %= 1000000000000000;
}
if ((number / 1000000000000) > 0)
{
parts.Add(string.Format("{0} Trillion", Convert(number / 1000000000000)));
number %= 1000000000000;
}
if ((number / 1000000000) > 0)
{
parts.Add(string.Format("{0} Billion", Convert(number / 1000000000)));
number %= 1000000000;
}
if ((number / 1000000) > 0)
{
parts.Add(string.Format("{0} Million", Convert(number / 1000000)));
number %= 1000000;
}
if ((number / 1000) > 0)
{
parts.Add(string.Format("{0} Thousand", Convert(number / 1000)));
number %= 1000;
}
if ((number / 100) > 0)
{
parts.Add(string.Format("{0} Hundred", Convert(number / 100)));
number %= 100;
// parts.Add(" and ");
}
if (number > 0)
{
if (parts.Count != 0)
parts.Add(" ");
if (number < 20)
parts.Add(GetUnitValue(number, isOrdinal));
else
{
var lastPart = TensMap[number / 10];
if ((number % 10) > 0)
lastPart = lastPart + " " + string.Format("{0}", GetUnitValue(number % 10, isOrdinal));
else if (isOrdinal)
lastPart = lastPart.TrimEnd('y') + "ieth";
parts.Add(lastPart);
}
}
else if (isOrdinal)
parts[parts.Count - 1] += "th";
var toWords = string.Join(" ", parts.ToArray());
if (isOrdinal)
toWords = RemoveOnePrefix(toWords);
return toWords;
}
public static string GetUnitValue(long number, bool isOrdinal)
{
if (isOrdinal)
{
string exceptionString;
if (ExceptionNumbersToWords(number, out exceptionString))
return exceptionString;
else
return UnitsMap[number] + "th";
}
else
return UnitsMap[number];
}
public static string RemoveOnePrefix(string toWords)
{
// one hundred => hundredth
if (toWords.IndexOf("one", StringComparison.Ordinal) == 0)
toWords = toWords.Remove(0, 4);
return toWords;
}
public static bool ExceptionNumbersToWords(long number, out string words)
{
return OrdinalExceptions.TryGetValue(number, out words);
}
}
}
| 52.709837 | 380 | 0.488264 | [
"Apache-2.0"
] | realvino/Core-2.0 | src/tibs.stem.Application/Quotationss/QuotationAppService.cs | 191,286 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace GooddFoodd.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("GooddFoodd.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap bg_software {
get {
object obj = ResourceManager.GetObject("bg-software", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
}
}
| 43.648649 | 177 | 0.589164 | [
"Unlicense"
] | moshfiqrony/CookingManagementMRTeam | GooddFoodd/GooddFoodd/Properties/Resources.Designer.cs | 3,232 | C# |
using ShopCart.API.Entities;
using System.Threading.Tasks;
namespace ShopCart.API.Repositories.Interfaces
{
public interface IShopCartRepository
{
Task<ShoppingCart> GetShopCart(string userName);
Task<ShoppingCart> UpdateShopCart(ShoppingCart shopCart);
Task<bool> DeleteShopCart(string userName);
}
} | 28.25 | 65 | 0.743363 | [
"MIT"
] | thiagocruzrj/E-Commerce-Microservices | MSStore/src/ShopCart.API/Repositories/Interfaces/IShopCartRepository.cs | 341 | C# |
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Configuration;
using System.Collections.Generic;
using WebDataDemo.Dtos;
namespace WebDataDemo.Option_01_ADONET_SQL
{
[Route("api/v01/[controller]")]
[ApiController]
[ApiExplorerSettings(GroupName = "1. Authors - ADO.NET SQL")]
public class AuthorsController : ControllerBase
{
private readonly string _connString;
public AuthorsController(IConfiguration config)
{
_connString = config.GetConnectionString("DefaultConnection");
}
// GET: api/<AuthorsController>
[HttpGet]
public ActionResult<AuthorDTO> Get()
{
var authors = new List<AuthorDTO>();
using var conn = new SqlConnection(_connString);
var sql = "SELECT * FROM Authors";
var cmd = new SqlCommand(sql, conn);
conn.Open();
using var reader = cmd.ExecuteReader();
if(reader.HasRows)
{
while (reader.Read())
{
var author = new AuthorDTO();
author.Id = reader.GetInt32(0);
author.Name = reader.GetString(1);
authors.Add(author);
}
}
return Ok(authors);
}
// GET api/<AuthorsController>/5
[HttpGet("{id}")]
public ActionResult<AuthorWithCoursesDTO> Get(int id)
{
var author = new AuthorWithCoursesDTO();
using var conn = new SqlConnection(_connString);
var sql = @"SELECT a.Id, a.Name, ca.RoyaltyPercentage, ca.CourseId, ca.AuthorId, c.Title
FROM Authors a
LEFT JOIN CourseAuthor ca ON a.Id = ca.AuthorId
LEFT JOIN Courses c ON c.Id = ca.CourseId
WHERE a.Id = @AuthorId";
var cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@AuthorId", id);
conn.Open();
using var reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
author.Id = reader.GetInt32(0);
author.Name = reader.GetString(1);
if (!reader.IsDBNull(3))
{
author.Courses.Add(new CourseDTO
{
Id = reader.GetInt32(3),
AuthorId = reader.GetInt32(4),
RoyaltyPercentage = reader.GetInt32(2),
Title = reader.GetString(5)
});
}
}
}
return Ok(author);
}
// POST api/<AuthorsController>
[HttpPost]
public ActionResult<AuthorDTO> Post([FromBody] CreateAuthorRequest newAuthor)
{
using var conn = new SqlConnection(_connString);
var sql = "INSERT Authors (name) VALUES (@name);SELECT CAST(scope_identity() AS int)";
var cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@name", newAuthor.Name);
conn.Open();
int newId = (int)cmd.ExecuteScalar();
var authorDto = new AuthorDTO
{
Id = newId,
Name = newAuthor.Name
};
return Ok(authorDto);
}
// PUT api/<AuthorsController>/5
[HttpPut("{id}")]
public void Put(int id, [FromBody] string value)
{
}
// DELETE api/<AuthorsController>/5
[HttpDelete("{id}")]
public ActionResult Delete(int id)
{
using var conn = new SqlConnection(_connString);
var sql = "DELETE Authors WHERE Id = @AuthorId";
var cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@AuthorId", id);
conn.Open();
cmd.ExecuteNonQuery();
return NoContent();
}
}
}
| 32.910569 | 100 | 0.517292 | [
"MIT"
] | radekwojpl2/DotNetDataAccessTour | WebDataDemo/Option_01_ADONET_SQL/AuthorsController.cs | 4,050 | C# |
using System.Collections.Generic;
using DigitalRune.Windows.TextEditor.Document;
namespace DigitalRune.Windows.TextEditor.Highlighting
{
/// <summary>
/// A highlighting strategy for a buffer.
/// </summary>
public interface IHighlightingStrategy
{
/// <summary>
/// Gets the name of the highlighting strategy (must be unique).
/// </summary>
/// <value>The name of the highlighting strategy (must be unique).</value>
string Name { get; }
/// <summary>
/// Gets the file extensions on which this highlighting strategy gets used.
/// </summary>
/// <value>
/// The file extensions on which this highlighting strategy gets used.
/// </value>
string[] Extensions { get; }
/// <summary>
/// Gets the properties.
/// </summary>
/// <value>The properties.</value>
Dictionary<string, string> Properties { get; }
/// <summary>
/// Gets the color of an environment element.
/// </summary>
/// <param name="name">The name of the element.</param>
/// <returns>The color of an environment element.</returns>
HighlightColor GetColorFor(string name);
/// <summary>
/// Marks the tokens. Used internally, do not call.
/// </summary>
/// <param name="document">The document.</param>
/// <param name="lines">The lines.</param>
void MarkTokens(IDocument document, List<LineSegment> lines);
/// <summary>
/// Marks the tokens. Used internally, do not call.
/// </summary>
/// <param name="document">The document.</param>
/// <remarks>
/// Used internally, do not call.
/// </remarks>
void MarkTokens(IDocument document);
}
/// <summary>
/// A highlighting strategy that is based on rule sets.
/// </summary>
public interface IHighlightingStrategyUsingRuleSets : IHighlightingStrategy
{
/// <summary>
/// Gets the rule set for the given span.
/// </summary>
/// <param name="span">The span.</param>
/// <returns>The rule set.</returns>
/// <remarks>
/// Used internally, do not call
/// </remarks>
HighlightRuleSet GetRuleSet(Span span);
/// <summary>
/// Gets the highlighting color for the specified text.
/// </summary>
/// <param name="document">The document.</param>
/// <param name="line">The line.</param>
/// <param name="index">The index.</param>
/// <param name="length">The length.</param>
/// <returns>The highlighting color for the specified text.</returns>
/// <remarks>
/// Used internally, do not call
/// </remarks>
HighlightColor GetColor(IDocument document, LineSegment line, int index, int length);
}
}
| 29.086957 | 89 | 0.626308 | [
"MIT"
] | sparql-studio/sparql-studio | Code/Src/Libs/DigitalRune-TextEditor-1.3.1/DigitalRune.Windows.TextEditor/Document/Highlighting/IHighlightingStrategy.cs | 2,678 | C# |
// <copyright file="BytePadder.cs" company="Microsoft Corporation">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//----------------------------------------------------------------------------------------------
namespace BluetoothLEExplorer.Services.Other
{
/// <summary>
/// Helper class used to pad bytes
/// </summary>
public static class BytePadder
{
/// <summary>
/// Takes an input array of bytes and returns an array with more zeros in the front
/// </summary>
/// <param name="input"></param>
/// <param name="length"></param>
/// <returns>A byte array with more zeros in front"/></returns>
public static byte[] GetBytes(byte[] input, int length)
{
byte[] ret = new byte[length];
if (input.Length >= length)
{
return input;
}
for (int i = 0; i < input.Length; i++)
{
ret[i] = input[i];
}
return ret;
}
}
}
| 30.351351 | 97 | 0.45236 | [
"MIT"
] | Bhaskers-Blu-Org2/BluetoothLEExplorer | BluetoothLEExplorer/BluetoothLEExplorer/Services/Other/BytePadder.cs | 1,125 | C# |
using Clean.Architecture.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
namespace Clean.Architecture.Infrastructure;
public static class StartupSetup
{
public static void AddDbContext(this IServiceCollection services, string connectionString)
{
services.AddDbContext<AppDbContext>(options =>
options.UseSqlite(connectionString));
// will be created in web project root
}
}
| 28.4375 | 92 | 0.802198 | [
"MIT"
] | skinnystick22/CleanArchitecture | src/Clean.Architecture.Infrastructure/StartupSetup.cs | 457 | C# |
using System.Collections.Generic;
namespace Calliope
{
// https://enterprisecraftsmanship.com/posts/new-online-course-ddd-and-ef-core/
// implementation based upon Vladimir Khorikov's solution
public abstract class AggregateRoot : Entity
{
private readonly List<DomainEvent> _domainEvents = new List<DomainEvent>();
public IReadOnlyList<DomainEvent> DomainEvents => _domainEvents;
protected void RaiseDomainEvent(DomainEvent domainEvent) => _domainEvents.Add(domainEvent);
public void ClearDomainEvents() => _domainEvents.Clear();
}
} | 39.2 | 99 | 0.738095 | [
"MIT"
] | JTOne123/Calliope | src/Calliope/AggregateRoot.cs | 588 | C# |
using System;
using Newtonsoft.Json;
namespace PayrollProcessor.Data.Persistence.Infrastructure.Records;
/// <summary>
/// https://github.com/Azure/azure-cosmos-dotnet-v3/issues/165#issuecomment-489112642
/// </summary>
public abstract class CosmosDBRecord
{
/// <summary>
/// The unique identifier of the record
/// </summary>
/// <value></value>
public Guid Id { get; set; }
/// <summary>
/// The partition key of the record in its collection
/// </summary>
/// <value></value>
public string PartitionKey { get; set; } = string.Empty;
/// <summary>
/// The 'Version' of the record auto-managed by Cosmos and used
/// for optimistic concurrency
/// </summary>
/// <value></value>
[JsonProperty(PropertyName = "_etag")]
public string ETag { internal get; set; } = string.Empty;
/// <summary>
/// The type discrimniator of the record, used when multiple
/// different record types are stored in the same collection
/// This is the name of the Record class.
/// </summary>
/// <value></value>
public string Type { get; set; } = string.Empty;
}
| 29.307692 | 85 | 0.63867 | [
"MIT"
] | KurnakovMaksim/payroll-processor | api/PayrollProcessor.Data.Persistence/Infrastructure/Records/CosmosDbRecord.cs | 1,143 | C# |
using System.Threading.Tasks;
using CSharpWars.ScriptProcessor.Helpers;
namespace CSharpWars.ScriptProcessor.Middleware.Interfaces
{
public interface IPostprocessor
{
Task Go(ProcessingContext context);
}
} | 22.8 | 58 | 0.767544 | [
"Unlicense"
] | Djohnnie/CSharpWars-DotNetDeveloperDays-2019 | src/backend/CSharpWars/CSharpWars.ScriptProcessor/Middleware/Interfaces/IPostprocessor.cs | 230 | C# |
using System;
using System.ComponentModel;
using System.Threading;
using System.Threading.Tasks;
using Android;
using Android.App;
using Android.Content;
using Android.Media;
using Android.Views;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
using eliteKit.AndroidCore.eliteVideo;
using eliteKit.AndroidCore.Enums;
using eliteKit.AndroidCore.Renderers;
using eliteKit.Diagnostics;
using eliteKit.eliteEnums;
using eliteKit.eliteEventArgs;
using eliteKit.Infrastructure.eliteVideo;
using eliteKit.Interfaces;
using Math = System.Math;
using Timer = System.Timers.Timer;
using VideoView = eliteKit.AndroidCore.eliteVideo.VideoView;
[assembly: ExportRenderer(typeof(VideoPlayer), typeof(VideoPlayerRenderer))]
[assembly: UsesPermission(Name = Manifest.Permission.Internet)]
[assembly: UsesPermission(Name = Manifest.Permission.WakeLock)]
namespace eliteKit.AndroidCore.Renderers
{
/// <summary>
/// A custom renderer for the native platform video player.
/// </summary>
internal class VideoPlayerRenderer : ViewRenderer<VideoPlayer, VideoView>, IVideoPlayerRenderer
{
#region Fields
/// <summary>
/// Tracks the playback time so we can update CurrentTime in the Xamarin Forms video player.
/// </summary>
private Timer _currentPositionTimer;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="VideoPlayerRenderer"/> class.
/// </summary>
/// <param name="context">The context.</param>
public VideoPlayerRenderer(Context context) : base(context)
{
}
#endregion
#region IVideoPlayerRenderer
/// <summary>
/// Plays the video.
/// </summary>
public virtual void Play()
{
if (CanPlay())
Control?.Start();
}
/// <summary>
/// Determines if the video player instance can play.
/// </summary>
/// <returns></returns>
/// <c>true</c> if this instance can play; otherwise, <c>false</c>.
public virtual bool CanPlay()
{
var control = Control;
return control != null && (control.Status == MediaPlayerStatus.Prepared
|| control.Status == MediaPlayerStatus.Paused);
}
/// <summary>
/// Pauses the video.
/// </summary>
public virtual void Pause()
{
if (CanPause())
Control?.Pause();
}
/// <summary>
/// Determines if the video player instance can pause.
/// </summary>
/// <returns></returns>
/// <c>true</c> if this instance can pause; otherwise, <c>false</c>.
public virtual bool CanPause()
{
var control = Control;
return control != null && control.CanPause();
}
/// <summary>
/// Stops the video.
/// </summary>
public virtual void Stop()
{
if (CanStop())
Control?.StopPlayback();
}
/// <summary>
/// Determines if the video player instance can stop.
/// </summary>
/// <returns></returns>
/// <c>true</c> if this instance can stop; otherwise, <c>false</c>.
public virtual bool CanStop()
{
var control = Control;
return control != null
&& (control.IsPlaying
|| control.Status == MediaPlayerStatus.Playing
|| control.Status == MediaPlayerStatus.Prepared
|| control.Status == MediaPlayerStatus.PlaybackCompleted);
}
/// <summary>
/// Seeks a specific number of seconds into the playback stream.
/// </summary>
/// <param name="time">The time in seconds.</param>
public virtual void Seek(int time)
{
if (CanSeek(time))
{
var control = Control;
if (control != null)
{
var currentTime = control.CurrentPosition;
var targetTime = currentTime + TimeSpan.FromSeconds(time).TotalMilliseconds;
Log.Info($"SEEK: CurrentTime={currentTime}; NewTime={targetTime}");
control.SeekTo((int)targetTime);
Element.SetValue(VideoPlayer.CurrentTimePropertyKey,
TimeSpan.FromMilliseconds(control.CurrentPosition));
}
}
}
/// <summary>
/// Determines if the video player instance can seek.
/// </summary>
/// <param name="time">The time in seconds.</param>
/// <returns></returns>
/// <c>true</c> if this instance can stop; otherwise, <c>false</c>.
public virtual bool CanSeek(int time)
{
var control = Control;
return control != null && ((time > 0 && Control.CanSeekForward() && (Control.CurrentPosition + time) <= Control.Duration)
|| (time < 0 && Control.CanSeekBackward() && (Control.CurrentPosition + time) >= 0));
}
#endregion
#region ViewRenderer Overrides
/// <summary>
/// Raises the <see cref="E:ElementChanged" /> event.
/// </summary>
/// <param name="e">The <see cref="ElementChangedEventArgs{VideoPlayer}"/> instance containing the event data.</param>
protected override async void OnElementChanged(ElementChangedEventArgs<VideoPlayer> e)
{
base.OnElementChanged(e);
if (Control == null)
{
SetNativeControl(new VideoView(Context)
{
LayoutParameters = new LayoutParams(LayoutParams.MatchParent, LayoutParams.MatchParent)
});
}
if (e.OldElement != null)
{
// Unsubscribe
Element.NativeRenderer = null;
}
if (e.NewElement != null)
{
// Subscribe
UpdateVisibility();
RegisterEvents();
await UpdateSource(e.OldElement);
Element.NativeRenderer = this;
}
}
/// <summary>
/// Called when [element property changed].
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="PropertyChangedEventArgs"/> instance containing the event data.</param>
protected override async void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (Element == null || Control == null) return;
if (e.PropertyName == VideoPlayer.DisplayControlsProperty.PropertyName)
{
UpdateDisplayControls();
}
else if (e.PropertyName == VideoPlayer.FillModeProperty.PropertyName)
{
UpdateFillMode();
}
else if (e.PropertyName == VideoPlayer.TimeElapsedIntervalProperty.PropertyName)
{
UpdateTimeElapsedInterval();
}
else if (e.PropertyName == VideoPlayer.SourceProperty.PropertyName)
{
await UpdateSource();
}
else if (e.PropertyName == VideoPlayer.VolumeProperty.PropertyName)
{
UpdateVolume();
}
else if (e.PropertyName == VideoPlayer.RepeatProperty.PropertyName)
{
UpdateRepeat();
}
else if (e.PropertyName == VisualElement.IsVisibleProperty.PropertyName)
{
UpdateVisibility();
}
else if (e.PropertyName == "IsLoading")
{
if(Element.IsLoading)
Element.OnBuffering(CreateVideoPlayerEventArgs());
else
Element.OnFinishedBuffering(CreateVideoPlayerEventArgs());
}
}
#endregion
#region Events
/// <summary>
/// Registers this renderer with native events.
/// </summary>
private void RegisterEvents()
{
// CurrentTime Setup
_currentPositionTimer = new Timer(1000);
_currentPositionTimer.Elapsed += (source, eventArgs) =>
{
if (_currentPositionTimer.Enabled && Control.Player != null)
Element.SetValue(VideoPlayer.CurrentTimePropertyKey, TimeSpan.FromMilliseconds(Control.CurrentPosition));
};
// Prepared
Control.Prepared += OnPrepared;
// Time Elapsed
Control.TimeElapsed += (sender, args) => Element.OnTimeElapsed(CreateVideoPlayerEventArgs());
// Completion
Control.Completion += (sender, args) =>
{
_currentPositionTimer.Stop();
Element.OnCompleted(CreateVideoPlayerEventArgs());
};
// Error
Control.Error += (sender, args) =>
{
_currentPositionTimer.Stop();
Element.OnFailed(CreateVideoPlayerErrorEventArgs(args.What));
};
// Play
Control.Started += (sender, args) =>
{
_currentPositionTimer.Start();
Element.OnPlaying(CreateVideoPlayerEventArgs());
};
// Paused
Control.Paused += (sender, args) =>
{
_currentPositionTimer.Stop();
Element.OnPaused(CreateVideoPlayerEventArgs());
};
// Stopped
Control.Stopped += (sender, args) =>
{
_currentPositionTimer.Stop();
Element.OnPaused(CreateVideoPlayerEventArgs());
};
}
/// <summary>
/// Called when the video player has been prepared for playback.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="eventArgs">The <see cref="EventArgs"/> instance containing the event data.</param>
private void OnPrepared(object sender, EventArgs eventArgs)
{
Element.SetValue(VideoPlayer.IsLoadingProperty, false);
Element.OnPlayerStateChanged(CreateVideoPlayerStateChangedEventArgs(elitePlayerState.Prepared));
Element.SetValue(VideoPlayer.VideoDurationPropertyKey, TimeSpan.FromMilliseconds(Control.Duration));
// Player Setup
UpdateDisplayControls();
UpdateVolume();
UpdateFillMode();
UpdateTimeElapsedInterval();
UpdateRepeat();
if (Element.AutoPlay)
Play();
Control.Player.Info += (s, a) =>
{
switch (a.What)
{
case Android.Media.MediaInfo.BufferingStart:
//AppLog.showLogE(TAG,"Buffering...");
Element.IsLoading = true;
break;
case Android.Media.MediaInfo.BufferingEnd:
//AppLog.showLogE(TAG,"Buffering End");
Element.IsLoading = false;
break;
}
};
}
#endregion
#region Methods
/// <summary>
/// Updates the display controls property on the native player.
/// </summary>
private void UpdateDisplayControls()
{
Control.MediaController.Visibility = Element.DisplayControls ? ViewStates.Visible : ViewStates.Gone;
}
/// <summary>
/// Updates the volume level.
/// </summary>
private void UpdateVolume()
{
var volume = Element.Volume;
if (volume != int.MinValue)
{
var nativeVolume = (float)Math.Min(100, Math.Max(0, volume)) / 100;
Control.Player?.SetVolume(nativeVolume, nativeVolume);
}
}
/// <summary>
/// Updates the video source property on the native player.
/// </summary>
/// <param name="oldElement">The old element.</param>
private async Task UpdateSource(VideoPlayer oldElement = null)
{
try
{
var newSource = Element?.Source;
if (oldElement != null)
{
var oldSource = oldElement.Source;
if (!oldSource.Equals(newSource))
return;
}
Element.SetValue(VideoPlayer.IsLoadingProperty, true);
var videoSourceHandler = VideoSourceHandler.Create(newSource);
var path = await videoSourceHandler.LoadVideoAsync(newSource, new CancellationToken());
Log.Info($"Video Source: {path}");
if (!string.IsNullOrEmpty(path))
{
Element.SetValue(VideoPlayer.CurrentTimePropertyKey, TimeSpan.Zero);
Control.SetVideoPath(path);
Element.OnPlayerStateChanged(CreateVideoPlayerStateChangedEventArgs(elitePlayerState.Initialized));
}
}
catch (Exception ex)
{
Log.Error(ex);
Element.SetValue(VideoPlayer.IsLoadingProperty, false);
}
}
/// <summary>
/// Updates the time elapsed interval of the video player.
/// </summary>
private void UpdateTimeElapsedInterval()
{
Control.TimeElapsedInterval = Element.TimeElapsedInterval;
}
/// <summary>
/// Updates the fill mode property on the native player.
/// </summary>
private void UpdateFillMode()
{
Control.FillMode = Element.FillMode;
}
/// <summary>
/// Updates the repeat property on the native player.
/// </summary>
private void UpdateRepeat()
{
Control.Player.Looping = Element.Repeat;
}
/// <summary>
/// Updates the visibility of the video player.
/// </summary>
private void UpdateVisibility()
{
Control.Visibility = Element.IsVisible ? ViewStates.Visible : ViewStates.Gone;
}
/// <summary>
/// Creates the video player event arguments.
/// </summary>
/// <returns>VideoPlayerEventArgs with information populated.</returns>
private EventArgsVideoPlayer CreateVideoPlayerEventArgs()
{
var mediaPlayer = Control;
if (mediaPlayer != null)
{
//var audioManager = Context.GetSystemService("audio") as AudioManager;
//audioManager.GetStreamVolume(Stream.Music)
return new EventArgsVideoPlayer(
TimeSpan.FromMilliseconds(Control.CurrentPosition),
TimeSpan.FromMilliseconds(Control.Duration),
1
);
}
return null;
}
/// <summary>
/// Creates the video player state changed event arguments.
/// </summary>
/// <param name="state">The current state.</param>
/// <returns></returns>
private EventArgsVideoPlayerStateChanged CreateVideoPlayerStateChangedEventArgs(elitePlayerState state)
{
var videoPlayerEventArgs = CreateVideoPlayerEventArgs();
return videoPlayerEventArgs == null
? new EventArgsVideoPlayerStateChanged(state)
: new EventArgsVideoPlayerStateChanged(videoPlayerEventArgs, state);
}
/// <summary>
/// Creates the video player error event arguments.
/// </summary>
/// <param name="errorCode">The error code.</param>
/// <param name="extra">The extra.</param>
/// <returns>
/// VideoPlayerErrorEventArgs with information populated.
/// </returns>
private EventArgsVideoPlayerError CreateVideoPlayerErrorEventArgs(MediaError errorCode)
{
var videoPlayerEventArgs = CreateVideoPlayerEventArgs();
return videoPlayerEventArgs == null
? new EventArgsVideoPlayerError(errorCode.ToString())
: new EventArgsVideoPlayerError(videoPlayerEventArgs, errorCode.ToString(), null);
}
#endregion
}
} | 33.613682 | 133 | 0.546151 | [
"MIT"
] | arqueror/eliteK | src/Forms/eliteKit.AndroidCore/Renderers/VideoPlayerRenderer.cs | 16,708 | C# |
// ----------------------------------------------------------------------------
// The MIT License
// LeopotamGroupLibrary https://github.com/Leopotam/LeopotamGroupLibraryUnity
// Copyright (c) 2012-2017 Leopotam <leopotam@gmail.com>
// ----------------------------------------------------------------------------
using LeopotamGroup.Math;
using LeopotamGroup.Serialization;
using LeopotamGroup.SystemUi.Actions;
using LeopotamGroup.SystemUi.Widgets;
using UnityEngine;
using UnityEngine.UI;
namespace LeopotamGroup.SystemUi.Markup.Generators {
static class ToggleNode {
public const string BackgroundImageName = "background";
public const string ForegroundImageName = "foreground";
public const string ContentName = "content";
static readonly int HashedGroup = "group".GetStableHashCode ();
static readonly int HashedCheck = "check".GetStableHashCode ();
static readonly int HashedOnChange = "onChange".GetStableHashCode ();
/// <summary>
/// Create "toggle" node. If children supported - GameObject container for them should be returned.
/// </summary>
/// <param name="widget">Ui widget.</param>
/// <param name="node">Xml node.</param>
/// <param name="container">Markup container.</param>
public static RectTransform Create (RectTransform widget, XmlNode node, MarkupContainer container) {
#if UNITY_EDITOR
widget.name = "toggle";
#endif
var tr = widget.transform;
Image img;
RectTransform rt;
Vector2 size;
string attrValue;
var toggle = widget.gameObject.AddComponent<Toggle> ();
var theme = MarkupUtils.GetTheme (node, container);
var isInteractive = false;
// background.
rt = MarkupUtils.CreateUiObject (BackgroundImageName, tr);
img = rt.gameObject.AddComponent<Image> ();
img.sprite = theme.GetToggleSprite (MarkupTheme.ToggleState.Background);
img.type = Image.Type.Sliced;
img.raycastTarget = false;
size = theme.GetToggleSize (MarkupTheme.ToggleState.Background);
rt.anchorMin = new Vector2 (0f, 0.5f);
rt.anchorMax = new Vector2 (0f, 0.5f);
rt.offsetMin = new Vector2 (0f, -size.y * 0.5f);
rt.offsetMax = new Vector2 (size.x, size.y * 0.5f);
toggle.targetGraphic = img;
// foreground.
rt = MarkupUtils.CreateUiObject (ForegroundImageName, rt);
img = rt.gameObject.AddComponent<Image> ();
rt.anchorMin = new Vector2 (0.5f, 0.5f);
rt.anchorMax = new Vector2 (0.5f, 0.5f);
rt.sizeDelta = theme.GetToggleSize (MarkupTheme.ToggleState.Foreground);
img.sprite = theme.GetToggleSprite (MarkupTheme.ToggleState.Foreground);
img.type = Image.Type.Sliced;
img.raycastTarget = false;
toggle.graphic = img;
// content.
rt = MarkupUtils.CreateUiObject (ContentName, tr);
rt.anchorMin = Vector2.zero;
rt.anchorMax = Vector2.one;
rt.offsetMin = Vector2.right * size.x;
rt.offsetMax = Vector2.zero;
attrValue = node.GetAttribute (HashedGroup);
if (!string.IsNullOrEmpty (attrValue)) {
var groupGo = container.GetNamedNode (attrValue);
if ((object) groupGo != null) {
toggle.group = groupGo.GetComponent<ToggleGroup> ();
}
}
attrValue = node.GetAttribute (HashedCheck);
if (string.CompareOrdinal (attrValue, "true") == 0) {
toggle.isOn = true;
}
attrValue = node.GetAttribute (HashedOnChange);
if (!string.IsNullOrEmpty (attrValue)) {
widget.gameObject.AddComponent<NonVisualWidget> ();
widget.gameObject.AddComponent<UiToggleAction> ().SetGroup (attrValue);
isInteractive = true;
}
toggle.transition = Selectable.Transition.None;
toggle.interactable = isInteractive;
MarkupUtils.SetSize (widget, node);
MarkupUtils.SetRotation (widget, node);
MarkupUtils.SetOffset (widget, node);
MarkupUtils.SetHidden (widget, node);
MarkupUtils.SetNav (toggle, node, container.UseNavigation);
return rt;
}
}
} | 40.303571 | 108 | 0.584847 | [
"MIT"
] | caxapexac/Jams | !Source!/Ludum Dare/ScreenCrifice/Assets/Libs/LeopotamGroupLibraryUnity-develop/SystemUi/Markup/Generators/Toggle.cs | 4,514 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using AGS.Engine;
namespace AGS.Editor
{
public static class ReflectionCache
{
private static Dictionary<Type, List<Type>> _implementors;
public static List<Type> AllTypes { get; private set; }
public static List<Type> AllImplementations(this Type baseType)
{
return _implementors.GetOrAdd(baseType, type => AllTypes.Where(p => baseType.IsAssignableFrom(p)).ToList());
}
public static void Refresh()
{
AllTypes = AppDomain.CurrentDomain.GetAssemblies().SelectMany(s => s.GetTypes()).ToList();
_implementors = new Dictionary<Type, List<Type>>();
}
}
} | 29.36 | 120 | 0.648501 | [
"Artistic-2.0"
] | tzachshabtay/MonoAGS | Source/Editor/AGS.Editor/ReflectionCache.cs | 736 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#region Using Statements
// We will need several different libraries in this sample.
// Here, we expose these libraries to our program using the
// C# "using" statement, similar to the Q# "open" statement.
// We will use the data model implemented by the Quantum Development Kit chemistry
// libraries. This model defines what a fermionic Hamiltonian is, and how to
// represent Hamiltonians on disk.
using Microsoft.Quantum.Chemistry.OrbitalIntegrals;
using Microsoft.Quantum.Chemistry.Fermion;
using Microsoft.Quantum.Chemistry.QSharpFormat;
// To count gates, we'll use the trace simulator provided with
// the Quantum Development Kit.
using Microsoft.Quantum.Simulation.Simulators;
// The System namespace provides a number of useful built-in
// types and methods that we'll use throughout this sample.
using System;
// The System.Diagnostics namespace provides us with the
// Stopwatch class, which is quite useful for measuring
// how long each gate counting run takes.
using System.Diagnostics;
// The System.Collections.Generic library provides many different
// utilities for working with collections such as lists and dictionaries.
using System.Collections.Generic;
// We use the logging library provided with .NET Core to handle output
// in a robust way that makes it easy to turn on and off different messages.
using Microsoft.Extensions.Logging;
// We use this for convenience methods for manipulating arrays.
using System.Linq;
#endregion
namespace Microsoft.Quantum.Chemistry.Samples.Hydrogen
{
class Program
{
static void Main(string[] args)
{
//////////////////////////////////////////////////////////////////////////
// Introduction //////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
// In this example, we will create a spin-orbital representation of the molecular
// Hydrogen Hamiltonian `H`, given ovelap coefficients for its one- and
// two - electron integrals.
// We when perform quantum phase estimation to obtain an estimate of
// the molecular Hydrogen ground state energy.
#region Building the Hydrogen Hamiltonian through orbital integrals
// One of the simplest representations of Hydrogen uses only two
// molecular orbitals indexed by `0` and `1`.
var nOrbitals = 2;
// This representation also has two occupied spin-orbitals.
var nElectrons = 2;
// The Coulomb repulsion energy between nuclei is
var energyOffset = 0.713776188;
// One-electron integrals are listed below
// <0|H|0> = -1.252477495
// <1|H|1> = -0.475934275
// Two-electron integrals are listed below
// <00|H|00> = 0.674493166
// <01|H|01> = 0.181287518
// <01|H|10> = 0.663472101
// <11|H|11> = 0.697398010
// Note that orbitals are assumed to be real. Moreover, indistinguishability
// of electrons means that the following integrals are equal.
// <PQ|H|RS> = <PR|H|QS> = <SQ|H|RP> = <SR|H|QP>
// = <QP|H|SR> = <RP|H|SQ> = <QS|H|PR> = <RS|H|PQ>
// Thus it sufficies to specify just any one of these terms from each symmetry
// group.
// These orbital integrals are represented using the OrbitalIntegral
// data structure.
var orbitalIntegrals = new OrbitalIntegral[]
{
new OrbitalIntegral(new[] { 0,0 }, -1.252477495),
new OrbitalIntegral(new[] { 1,1 }, -0.475934275),
new OrbitalIntegral(new[] { 0,0,0,0 }, 0.674493166),
new OrbitalIntegral(new[] { 0,1,0,1 }, 0.181287518),
new OrbitalIntegral(new[] { 0,1,1,0 }, 0.663472101),
new OrbitalIntegral(new[] { 1,1,1,1 }, 0.697398010),
// Add the identity term
new OrbitalIntegral(new int[] { }, energyOffset)
};
// We initialize a fermion Hamiltonian data structure and add terms to it
var fermionHamiltonian = new OrbitalIntegralHamiltonian(orbitalIntegrals).ToFermionHamiltonian();
// These orbital integral terms are automatically expanded into
// spin-orbitals. We may print the Hamiltonian to see verify what it contains.
Console.WriteLine("----- Print Hamiltonian");
Console.Write(fermionHamiltonian);
Console.WriteLine("----- End Print Hamiltonian \n");
// We also need to create an input quantum state to this Hamiltonian.
// Let us use the Hartree–Fock state.
var fermionWavefunction = fermionHamiltonian.CreateHartreeFockState(nElectrons);
#endregion
#region Jordan–Wigner representation
// The Jordan–Wigner encoding converts the fermion Hamiltonian,
// expressed in terms of Fermionic operators, to a qubit Hamiltonian,
// expressed in terms of Pauli matrices. This is an essential step
// for simulating our constructed Hamiltonians on a qubit quantum
// computer.
Console.WriteLine("----- Creating Jordan–Wigner encoding");
var jordanWignerEncoding = fermionHamiltonian.ToPauliHamiltonian(Paulis.QubitEncoding.JordanWigner);
Console.WriteLine("----- End Creating Jordan–Wigner encoding \n");
// Print the Jordan–Wigner encoded Hamiltonian to see verify what it contains.
Console.WriteLine("----- Print Hamiltonian");
Console.Write(jordanWignerEncoding);
Console.WriteLine("----- End Print Hamiltonian \n");
#endregion
#region Performing the simulation
// We are now ready to run a quantum simulation of molecular Hydrogen.
// We will use this to obtain an estimate of its ground state energy.
// Here, we make an instance of the simulator used to run our Q# code.
using (var qsim = new QuantumSimulator())
{
// This Jordan–Wigner data structure also contains a representation
// of the Hamiltonian and wavefunction made for consumption by the Q# algorithms.
var qSharpHamiltonianData = jordanWignerEncoding.ToQSharpFormat();
var qSharpWavefunctionData = fermionWavefunction.ToQSharpFormat();
var qSharpData = QSharpFormat.Convert.ToQSharpFormat(qSharpHamiltonianData, qSharpWavefunctionData);
// We specify the bits of precision desired in the phase estimation
// algorithm
var bits = 7;
// We specify the step-size of the simulated time-evolution
var trotterStep = 0.4;
// Choose the Trotter integrator order
Int64 trotterOrder = 1;
// As the quantum algorithm is probabilistic, let us run a few trials.
// This may be compared to true value of
Console.WriteLine("Exact molecular Hydrogen ground state energy: -1.137260278.\n");
Console.WriteLine("----- Performing quantum energy estimation by Trotter simulation algorithm");
for (int i = 0; i < 5; i++)
{
// EstimateEnergyByTrotterization
// Name shold make clear that it does it by trotterized
var (phaseEst, energyEst) = GetEnergyByTrotterization.Run(qsim, qSharpData, bits, trotterStep, trotterOrder).Result;
Console.WriteLine($"Rep #{i+1}/5: Energy estimate: {energyEst}; Phase estimate: {phaseEst}");
}
Console.WriteLine("----- End Performing quantum energy estimation by Trotter simulation algorithm\n");
Console.WriteLine("----- Performing quantum energy estimation by Qubitization simulation algorithm");
for (int i = 0; i < 1; i++)
{
// EstimateEnergyByTrotterization
// Name shold make clear that it does it by trotterized
var (phaseEst, energyEst) = GetEnergyByQubitization.Run(qsim, qSharpData, bits).Result;
Console.WriteLine($"Rep #{i+1}/1: Energy estimate: {energyEst}; Phase estimate: {phaseEst}");
}
Console.WriteLine("----- End Performing quantum energy estimation by Qubitization simulation algorithm\n");
}
Console.WriteLine("Press Enter to continue...");
if (System.Diagnostics.Debugger.IsAttached)
{
Console.ReadLine();
}
#endregion
}
}
}
| 47.384211 | 136 | 0.60802 | [
"MIT"
] | AzureMentor/Quantum | samples/chemistry/MolecularHydrogen/Program.cs | 9,019 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("RansomwareDetectionSystemTray")]
[assembly: AssemblyDescription("HESD's Ransomware Detection Service from http://www.questiondriven.com, Download updates from http://ransomwaredetectionservice.codeplex.com/. On a schedule this service will compare files (Detect Ransomware) on local directories or windows file shares. If the example files go missing or are changed then an event log entry will be written and an email can be sent. 'Find Ransomware Files' tab to find files created by ransomware for cleanup and weekly detection in all files shares to know what shares have been compromised. Audit Files tab will compare files vs known file signatures for file extensions and create lists of unverified (Bad Files) and unknown files.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("RansomwareDetectionSystemTray")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("23987f89-4718-426d-9f2e-ea63eb7d086f")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.0.4.6")]
[assembly: AssemblyFileVersion("2.0.4.6")]
| 57.72973 | 705 | 0.758895 | [
"Apache-2.0"
] | prestoncooper/RansomwareDetectionService | RansomwareDetectionSystemTray/Properties/AssemblyInfo.cs | 2,139 | C# |
using TMPro;
using UnityEngine;
public class UIObjects : MonoBehaviour {
public static UIObjects Instance { get; private set; }
private void Awake() {
//Singleton code
if (Instance != null && Instance != this) Debug.LogError("Trying to instantiate a second singleton", gameObject);
else Instance = this;
}
public Canvas UICanvas;
public TextMeshProUGUI debugText;
//Menus
[Header("Menus")]
public MainMenu mainMenu;
private void Start() {
SetupButtonEvents();
}
private void SetupButtonEvents() {
//Main Menu
mainMenu.playGame.onClick.AddListener(() => {
mainMenu.gameObject.SetActive(false);
InputManager.Instance.GameStart();
});
mainMenu.quitGame.onClick.AddListener(() => {
mainMenu.gameObject.SetActive(false);
InputManager.Instance.Quit();
});
}
} | 26.514286 | 121 | 0.616379 | [
"CC0-1.0"
] | Fogsight/Quickstart2DWithExtendedFlexibleUI | Assets/!ProjectName/Scripts/Mono/Singleton/UIObjects.cs | 930 | C# |
using API.Attributes;
using API.Models;
using API.Services;
using API.Utils;
using Microsoft.AspNetCore.Mvc;
using System.Net;
using System.Security.Claims;
namespace API.Controllers
{
[Route("api/user")]
[ApiController]
public class UserController : ControllerBase
{
private readonly IUserService _userService;
private readonly IConfiguration _configuration;
public UserController(IUserService userService, IConfiguration configuration)
{
this._userService = userService;
this._configuration = configuration;
}
[HttpPost]
[Route("login")]
public async Task<ActionResult<object>> GetToken([FromBody] string username)
{
User user = await this._userService.GetUser(username);
if (user == null)
{
return NotFound("User does not exist");
}
List<Claim> claims = new List<Claim>();
claims.Add(new Claim(Claims.User, user.Username));
claims.Add(new Claim(Claims.Roles, string.Join(",", user.Roles)));
return new { Token = Token.IssueToken(claims, this._configuration).ToString() };
}
[HttpGet]
[Route("admin")]
[Authorize(UserRoles.Admin)]
public async Task<ActionResult<string>> DoAdminAction()
{
return "Performed Admin Action";
}
[HttpGet]
[Route("dev-or-admin")]
[Authorize(UserRoles.Admin, UserRoles.Developer)]
public async Task<ActionResult<string>> DoAdminOrDevAction()
{
return "Performed Admin or Developer Action";
}
[HttpGet]
[Route("accountant")]
[Authorize(UserRoles.Accountant)]
public async Task<ActionResult<string>> DoAccountantAction()
{
return "Performed Accountant Action";
}
[HttpGet]
[Route("any-role")]
[Authorize]
public async Task<ActionResult<string>> DoAnyAction()
{
return "Performed Action Without Role Restrictions";
}
}
}
| 29.315068 | 92 | 0.595327 | [
"MIT"
] | dsvictorh/jwt-sample | API/Controllers/UserController.cs | 2,142 | C# |
using System;
using System.Net;
using System.Windows.Forms;
namespace Mtf.Network.Host
{
public class ComputerNameProvider
{
public string GetMachineName()
{
return Environment.MachineName;
}
public string GetComputerName()
{
return SystemInformation.ComputerName;
}
public string GetHostName()
{
return Dns.GetHostName();
}
public string GetEnvironmentVariableComputerName()
{
return Environment.GetEnvironmentVariable("ComputerName");
}
}
} | 20.793103 | 70 | 0.593698 | [
"MIT"
] | Mortens4444/MortensTechnologyFramework | Mtf.Network/Host/ComputerNameProvider.cs | 605 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace Microsoft.Azure.WebJobs.Extensions.WebPubSub
{
/// <summary>
/// Operation to add a user to group.
/// </summary>
[JsonObject(NamingStrategyType = typeof(CamelCaseNamingStrategy))]
public class AddUserToGroup : WebPubSubOperation
{
/// <summary>
/// Target userId.
/// </summary>
public string UserId { get; set; }
/// <summary>
/// Target group name.
/// </summary>
public string Group { get; set; }
}
}
| 25.653846 | 70 | 0.622189 | [
"MIT"
] | daniellezhang/azure-sdk-for-net | sdk/webpubsub/Microsoft.Azure.WebJobs.Extensions.WebPubSub/src/Bindings/Output/AddUserToGroup.cs | 669 | C# |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
/* ================================================================
* About NPOI
* Author: Tony Qu
* Author's email: tonyqus (at) gmail.com
* Author's Blog: tonyqus.wordpress.com.cn (wp.tonyqus.cn)
* HomePage: http://www.codeplex.com/npoi
* Contributors:
*
* ==============================================================*/
using System;
using System.IO;
namespace Ams.Utils.NPOI.Util
{
internal class CloseIgnoringInputStream : Stream
{
private Stream _is;
public CloseIgnoringInputStream(Stream stream)
{
_is = stream;
}
public int Read()
{
return (int)_is.ReadByte();
}
public override int Read(byte[] b, int off, int len)
{
return _is.Read(b, off, len);
}
public override void Close()
{
// do nothing
}
public override void Flush()
{
}
public override long Seek(long offset, SeekOrigin origin)
{
return 0L;
}
public override void SetLength(long value)
{
}
// Properties
public override bool CanRead
{
get
{
return true;
}
}
public override bool CanSeek
{
get
{
return true;
}
}
public override bool CanWrite
{
get
{
return false;
}
}
public override long Length
{
get
{
return this._is.Length;
}
}
public override long Position
{
get
{
return this._is.Position;
}
set
{
this._is.Position = value;
}
}
public override void Write(byte[] buffer, int offset, int count)
{
}
}
}
| 25.850877 | 75 | 0.486597 | [
"MIT"
] | SkyGrass/hippos_api_vm | Ams.Utils/Document/Excel/NPOI/Util/CloseIgnoringInputStream.cs | 2,949 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/ShObjIdl_core.h in the Windows SDK for Windows 10.0.22000.0
// Original source is Copyright © Microsoft. All rights reserved.
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace TerraFX.Interop.Windows;
/// <include file='IDelegateFolder.xml' path='doc/member[@name="IDelegateFolder"]/*' />
[Guid("ADD8BA80-002B-11D0-8F0F-00C04FD7D062")]
[NativeTypeName("struct IDelegateFolder : IUnknown")]
[NativeInheritance("IUnknown")]
public unsafe partial struct IDelegateFolder : IDelegateFolder.Interface
{
public void** lpVtbl;
/// <inheritdoc cref="IUnknown.QueryInterface" />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(0)]
public HRESULT QueryInterface([NativeTypeName("const IID &")] Guid* riid, void** ppvObject)
{
return ((delegate* unmanaged<IDelegateFolder*, Guid*, void**, int>)(lpVtbl[0]))((IDelegateFolder*)Unsafe.AsPointer(ref this), riid, ppvObject);
}
/// <inheritdoc cref="IUnknown.AddRef" />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(1)]
[return: NativeTypeName("ULONG")]
public uint AddRef()
{
return ((delegate* unmanaged<IDelegateFolder*, uint>)(lpVtbl[1]))((IDelegateFolder*)Unsafe.AsPointer(ref this));
}
/// <inheritdoc cref="IUnknown.Release" />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(2)]
[return: NativeTypeName("ULONG")]
public uint Release()
{
return ((delegate* unmanaged<IDelegateFolder*, uint>)(lpVtbl[2]))((IDelegateFolder*)Unsafe.AsPointer(ref this));
}
/// <include file='IDelegateFolder.xml' path='doc/member[@name="IDelegateFolder.SetItemAlloc"]/*' />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(3)]
public HRESULT SetItemAlloc(IMalloc* pmalloc)
{
return ((delegate* unmanaged<IDelegateFolder*, IMalloc*, int>)(lpVtbl[3]))((IDelegateFolder*)Unsafe.AsPointer(ref this), pmalloc);
}
public interface Interface : IUnknown.Interface
{
[VtblIndex(3)]
HRESULT SetItemAlloc(IMalloc* pmalloc);
}
public partial struct Vtbl<TSelf>
where TSelf : unmanaged, Interface
{
[NativeTypeName("HRESULT (const IID &, void **) __attribute__((stdcall))")]
public delegate* unmanaged<TSelf*, Guid*, void**, int> QueryInterface;
[NativeTypeName("ULONG () __attribute__((stdcall))")]
public delegate* unmanaged<TSelf*, uint> AddRef;
[NativeTypeName("ULONG () __attribute__((stdcall))")]
public delegate* unmanaged<TSelf*, uint> Release;
[NativeTypeName("HRESULT (IMalloc *) __attribute__((stdcall))")]
public delegate* unmanaged<TSelf*, IMalloc*, int> SetItemAlloc;
}
}
| 38.552632 | 151 | 0.693857 | [
"MIT"
] | reflectronic/terrafx.interop.windows | sources/Interop/Windows/Windows/um/ShObjIdl_core/IDelegateFolder.cs | 2,932 | C# |
using System;
namespace YggdrAshill.Nuadha
{
/// <summary>
/// Threshold to convert <see cref="Signals.Tilt"/> into <see cref="Transformation.Pulse"/>.
/// </summary>
public sealed class TiltThreshold
{
/// <summary>
/// <see cref="HysteresisThreshold"/> for <see cref="Signals.Tilt.Distance"/>.
/// </summary>
public HysteresisThreshold Distance { get; }
/// <summary>
/// <see cref="HysteresisThreshold"/> for <see cref="Signals.Tilt.Left"/>.
/// </summary>
public HysteresisThreshold Left { get; }
/// <summary>
/// <see cref="HysteresisThreshold"/> for <see cref="Signals.Tilt.Right"/>.
/// </summary>
public HysteresisThreshold Right { get; }
/// <summary>
/// <see cref="HysteresisThreshold"/> for <see cref="Signals.Tilt.Forward"/>.
/// </summary>
public HysteresisThreshold Forward { get; }
/// <summary>
/// <see cref="HysteresisThreshold"/> for <see cref="Signals.Tilt.Backward"/>.
/// </summary>
public HysteresisThreshold Backward { get; }
#region Constructor
/// <summary>
/// Constructs instance.
/// </summary>
/// <param name="distance">
/// <see cref="HysteresisThreshold"/> for <see cref="Signals.Tilt.Distance"/>.
/// </param>
/// <param name="left">
/// <see cref="HysteresisThreshold"/> for <see cref="Signals.Tilt.Left"/>.
/// </param>
/// <param name="right">
/// <see cref="HysteresisThreshold"/> for <see cref="Signals.Tilt.Right"/>.
/// </param>
/// <param name="forward">
/// <see cref="HysteresisThreshold"/> for <see cref="Signals.Tilt.Forward"/>.
/// </param>
/// <param name="backward">
/// <see cref="HysteresisThreshold"/> for <see cref="Signals.Tilt.Backward"/>.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown if <paramref name="distance"/> is null.
/// </exception>
/// <exception cref="ArgumentNullException">
/// Thrown if <paramref name="left"/> is null.
/// </exception>
/// <exception cref="ArgumentNullException">
/// Thrown if <paramref name="right"/> is null.
/// </exception>
/// <exception cref="ArgumentNullException">
/// Thrown if <paramref name="forward"/> is null.
/// </exception>
/// <exception cref="ArgumentNullException">
/// Thrown if <paramref name="backward"/> is null.
/// </exception>
public TiltThreshold(
HysteresisThreshold distance,
HysteresisThreshold left, HysteresisThreshold right,
HysteresisThreshold forward, HysteresisThreshold backward)
{
if (distance == null)
{
throw new ArgumentNullException(nameof(distance));
}
if (left == null)
{
throw new ArgumentNullException(nameof(left));
}
if (right == null)
{
throw new ArgumentNullException(nameof(right));
}
if (forward == null)
{
throw new ArgumentNullException(nameof(forward));
}
if (backward == null)
{
throw new ArgumentNullException(nameof(backward));
}
Distance = distance;
Left = left;
Right = right;
Forward = forward;
Backward = backward;
}
/// <summary>
/// Constructs instance.
/// </summary>
/// <param name="threshold">
/// <see cref="HysteresisThreshold"/> for all.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown if <paramref name="threshold"/> is null.
/// </exception>
public TiltThreshold(HysteresisThreshold threshold)
{
if (threshold == null)
{
throw new ArgumentNullException(nameof(threshold));
}
Distance = threshold;
Left = threshold;
Right = threshold;
Forward = threshold;
Backward = threshold;
}
#endregion
}
}
| 33.837209 | 96 | 0.52394 | [
"MIT"
] | do-i-know-it/YggdrAshill.Nuadha | YggdrAshill.Nuadha/Units/Signals/TiltThreshold.cs | 4,365 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the config-2014-11-12.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.ConfigService.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.ConfigService.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for NoSuchRemediationExceptionException Object
/// </summary>
public class NoSuchRemediationExceptionExceptionUnmarshaller : IErrorResponseUnmarshaller<NoSuchRemediationExceptionException, JsonUnmarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public NoSuchRemediationExceptionException Unmarshall(JsonUnmarshallerContext context)
{
return this.Unmarshall(context, new Amazon.Runtime.Internal.ErrorResponse());
}
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <param name="errorResponse"></param>
/// <returns></returns>
public NoSuchRemediationExceptionException Unmarshall(JsonUnmarshallerContext context, Amazon.Runtime.Internal.ErrorResponse errorResponse)
{
context.Read();
NoSuchRemediationExceptionException unmarshalledObject = new NoSuchRemediationExceptionException(errorResponse.Message, errorResponse.InnerException,
errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode);
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
}
return unmarshalledObject;
}
private static NoSuchRemediationExceptionExceptionUnmarshaller _instance = new NoSuchRemediationExceptionExceptionUnmarshaller();
/// <summary>
/// Gets the singleton.
/// </summary>
public static NoSuchRemediationExceptionExceptionUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 36.764706 | 161 | 0.68608 | [
"Apache-2.0"
] | EbstaLimited/aws-sdk-net | sdk/src/Services/ConfigService/Generated/Model/Internal/MarshallTransformations/NoSuchRemediationExceptionExceptionUnmarshaller.cs | 3,125 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Data.Common;
using System.Data.OleDb;
using Accounting.Core;
using Accounting.Core.Sales;
using Accounting.Db;
using Accounting.Db.Elements;
namespace Accounting.Db.Im
{
public sealed class DbCreditRefundManager : CreditRefundManager
{
public DbCreditRefundManager(DbManager mgr)
: base(mgr)
{
}
protected override void CreateTableCommands() //CreditRefunds()
{
Dictionary<string, DbManager.FIELDTYPE> fields = new Dictionary<string, DbManager.FIELDTYPE>();
Dictionary<string, string> foreignKeys = new Dictionary<string, string>();
fields["CreditRefundID"] = DbManager.FIELDTYPE.INTEGER_INDEXED;
fields["ChequeNumber"] = DbManager.FIELDTYPE.VARCHAR_10;
fields["Date"] = DbManager.FIELDTYPE.DATETIME;
fields["TransactionDate"] = DbManager.FIELDTYPE.DATETIME;
fields["IsThirteenthPeriod"] = DbManager.FIELDTYPE.VARCHAR_1;
fields["IssuingAccountID"] = DbManager.FIELDTYPE.INTEGER;
fields["AmountRefunded"] = DbManager.FIELDTYPE.DOUBLE;
fields["CreditNoteID"] = DbManager.FIELDTYPE.INTEGER;
fields["ExchangeGainLoss"] = DbManager.FIELDTYPE.DOUBLE;
fields["CardRecordID"] = DbManager.FIELDTYPE.INTEGER;
fields["Payee"] = DbManager.FIELDTYPE.VARCHAR_255;
fields["Memo"] = DbManager.FIELDTYPE.VARCHAR_255;
fields["IsTaxInclusive"] = DbManager.FIELDTYPE.VARCHAR_1;
fields["IsPrinted"] = DbManager.FIELDTYPE.VARCHAR_1;
fields["PaymentDeliveryID"] = DbManager.FIELDTYPE.VARCHAR_1;
fields["CurrencyID"] = DbManager.FIELDTYPE.INTEGER;
fields["TransactionExchangeRate"] = DbManager.FIELDTYPE.DOUBLE;
/*
foreignKeys["IssuingAccountID"] = "Accounts(IssuingAccountID)";
foreignKeys["CreditNoteID"] = "Sales(CreditNoteID)";
foreignKeys["CardRecordID"] = "Cards(CardRecordID)";
foreignKeys["PaymentDeliveryID"] = "InvoiceDelivery(PaymentDeliveryID)";
foreignKeys["CurrencyID"] = "Currency(CurrencyID)";
* */
TableCommands["CreditRefunds"] = DbMgr.CreateTableCommand("CreditRefunds", fields, "CreditRefundID", foreignKeys);
}
private DbInsertStatement GetQuery_InsertQuery(CreditRefund _obj)
{
Dictionary<string, DbFieldEntry> fields = GetFields(_obj);
return DbMgr.CreateInsertClause("CreditRefunds", fields);
}
private DbUpdateStatement GetQuery_UpdateQuery(CreditRefund _obj)
{
return DbMgr.CreateUpdateClause("CreditRefunds", GetFields(_obj), "CreditRefundID", _obj.CreditRefundID);
}
protected override OpResult _Store(CreditRefund _obj)
{
if (_obj == null)
{
return OpResult.NotifyStoreAction(OpResult.ResultStatus.ObjectIsNull, _obj, "CreditRefund object cannot be created as it is null");
}
if (Exists(_obj))
{
ExecuteNonQuery(GetQuery_UpdateQuery(_obj));
return OpResult.NotifyStoreAction(OpResult.ResultStatus.Updated, _obj);
}
ExecuteNonQuery(GetQuery_InsertQuery(_obj));
if (_obj.CreditRefundID == null)
{
_obj.CreditRefundID = DbMgr.GetLastInsertID();
}
_obj.FromDb = true;
return OpResult.NotifyStoreAction(OpResult.ResultStatus.Created, _obj);
}
}
}
| 38.694737 | 147 | 0.637922 | [
"MIT"
] | cschen1205/myob-accounting-plugin | Accounting.Db.Im/DbCreditRefundManager.cs | 3,676 | C# |
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Example.BusinessApp.ItAdmin")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Example.BusinessApp.ItAdmin")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly:ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 42.446429 | 96 | 0.718973 | [
"MIT"
] | JTOne123/matisco | Example.BusinessApp.ItAdmin/Properties/AssemblyInfo.cs | 2,380 | C# |
// <auto-generated />
using System;
using Issue12PostgreSql.DataLayer;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace Issue12PostgreSql.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("20220106090629_V2022_01_06_1235")]
partial class V2022_01_06_1235
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "6.0.1")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("Issue12PostgreSql.Entities.Address", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Name")
.HasColumnType("text");
b.Property<int>("PersonId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("PersonId");
b.ToTable("Addresses");
});
modelBuilder.Entity("Issue12PostgreSql.Entities.Book", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Name")
.HasColumnType("text");
b.Property<int>("PersonId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("PersonId");
b.ToTable("Books");
});
modelBuilder.Entity("Issue12PostgreSql.Entities.Entity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
b.Property<int[]>("Array")
.HasColumnType("integer[]");
b.HasKey("Id");
b.ToTable("Entities");
});
modelBuilder.Entity("Issue12PostgreSql.Entities.Person", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<DateTime>("AddDate")
.HasColumnType("timestamp with time zone");
b.Property<byte[]>("ByteArrayValue")
.HasColumnType("bytea");
b.Property<byte>("ByteValue")
.HasColumnType("smallint");
b.Property<char>("CharValue")
.HasColumnType("character(1)");
b.Property<DateOnly>("Date1")
.HasColumnType("date");
b.Property<DateOnly?>("Date2")
.HasColumnType("date");
b.Property<DateTime>("DateTimeOffsetValue")
.HasColumnType("timestamp with time zone");
b.Property<decimal>("DecimalValue")
.HasColumnType("numeric");
b.Property<double>("DoubleValue")
.HasColumnType("double precision");
b.Property<float>("FloatValue")
.HasColumnType("real");
b.Property<Guid>("GuidValue")
.HasColumnType("uuid");
b.Property<bool>("IsActive")
.HasColumnType("boolean");
b.Property<string>("Name")
.HasColumnType("text");
b.Property<string>("OptionDefinitions")
.HasColumnType("jsonb");
b.Property<long>("Points")
.HasColumnType("bigint");
b.Property<short>("ShortValue")
.HasColumnType("smallint");
b.Property<TimeOnly>("Time1")
.HasColumnType("time without time zone");
b.Property<TimeOnly?>("Time2")
.HasColumnType("time without time zone");
b.Property<TimeSpan>("TimeSpanValue")
.HasColumnType("interval");
b.Property<long>("UintValue")
.HasColumnType("bigint");
b.Property<decimal>("UlongValue")
.HasColumnType("numeric(20,0)");
b.Property<DateTime?>("UpdateDate")
.HasColumnType("timestamp with time zone");
b.Property<decimal>("UshortValue")
.HasColumnType("numeric(20,0)");
b.HasKey("Id");
b.ToTable("People");
});
modelBuilder.Entity("Issue12PostgreSql.Entities.Address", b =>
{
b.HasOne("Issue12PostgreSql.Entities.Person", "Person")
.WithMany("Addresses")
.HasForeignKey("PersonId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Person");
});
modelBuilder.Entity("Issue12PostgreSql.Entities.Book", b =>
{
b.HasOne("Issue12PostgreSql.Entities.Person", "Person")
.WithMany("Books")
.HasForeignKey("PersonId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Person");
});
modelBuilder.Entity("Issue12PostgreSql.Entities.Person", b =>
{
b.Navigation("Addresses");
b.Navigation("Books");
});
#pragma warning restore 612, 618
}
}
}
| 34.266332 | 103 | 0.478663 | [
"Apache-2.0"
] | dante2130/EFCoreSecondLevelCacheInterceptor | src/Tests/Issues/Issue12PostgreSql/Migrations/20220106090629_V2022_01_06_1235.Designer.cs | 6,821 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the personalize-2018-05-22.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.Personalize.Model
{
/// <summary>
/// Provides feature transformation information. Feature transformation is the process
/// of modifying raw input data into a form more suitable for model training.
/// </summary>
public partial class FeatureTransformation
{
private DateTime? _creationDateTime;
private Dictionary<string, string> _defaultParameters = new Dictionary<string, string>();
private string _featureTransformationArn;
private DateTime? _lastUpdatedDateTime;
private string _name;
private string _status;
/// <summary>
/// Gets and sets the property CreationDateTime.
/// <para>
/// The creation date and time (in Unix time) of the feature transformation.
/// </para>
/// </summary>
public DateTime CreationDateTime
{
get { return this._creationDateTime.GetValueOrDefault(); }
set { this._creationDateTime = value; }
}
// Check to see if CreationDateTime property is set
internal bool IsSetCreationDateTime()
{
return this._creationDateTime.HasValue;
}
/// <summary>
/// Gets and sets the property DefaultParameters.
/// <para>
/// Provides the default parameters for feature transformation.
/// </para>
/// </summary>
[AWSProperty(Max=100)]
public Dictionary<string, string> DefaultParameters
{
get { return this._defaultParameters; }
set { this._defaultParameters = value; }
}
// Check to see if DefaultParameters property is set
internal bool IsSetDefaultParameters()
{
return this._defaultParameters != null && this._defaultParameters.Count > 0;
}
/// <summary>
/// Gets and sets the property FeatureTransformationArn.
/// <para>
/// The Amazon Resource Name (ARN) of the FeatureTransformation object.
/// </para>
/// </summary>
[AWSProperty(Max=256)]
public string FeatureTransformationArn
{
get { return this._featureTransformationArn; }
set { this._featureTransformationArn = value; }
}
// Check to see if FeatureTransformationArn property is set
internal bool IsSetFeatureTransformationArn()
{
return this._featureTransformationArn != null;
}
/// <summary>
/// Gets and sets the property LastUpdatedDateTime.
/// <para>
/// The last update date and time (in Unix time) of the feature transformation.
/// </para>
/// </summary>
public DateTime LastUpdatedDateTime
{
get { return this._lastUpdatedDateTime.GetValueOrDefault(); }
set { this._lastUpdatedDateTime = value; }
}
// Check to see if LastUpdatedDateTime property is set
internal bool IsSetLastUpdatedDateTime()
{
return this._lastUpdatedDateTime.HasValue;
}
/// <summary>
/// Gets and sets the property Name.
/// <para>
/// The name of the feature transformation.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=63)]
public string Name
{
get { return this._name; }
set { this._name = value; }
}
// Check to see if Name property is set
internal bool IsSetName()
{
return this._name != null;
}
/// <summary>
/// Gets and sets the property Status.
/// <para>
/// The status of the feature transformation.
/// </para>
///
/// <para>
/// A feature transformation can be in one of the following states:
/// </para>
/// <ul> <li>
/// <para>
/// CREATE PENDING > CREATE IN_PROGRESS > ACTIVE -or- CREATE FAILED
/// </para>
/// </li> </ul>
/// </summary>
[AWSProperty(Max=256)]
public string Status
{
get { return this._status; }
set { this._status = value; }
}
// Check to see if Status property is set
internal bool IsSetStatus()
{
return this._status != null;
}
}
} | 32.861446 | 110 | 0.571769 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/Personalize/Generated/Model/FeatureTransformation.cs | 5,455 | C# |
using System;
using UltimaOnline;
using UltimaOnline.Gumps;
using UltimaOnline.Network;
namespace UltimaOnline.Items
{
public class CustomHueGroup
{
private int m_Name;
private string m_NameString;
private int[] m_Hues;
public int Name{ get{ return m_Name; } }
public string NameString{ get{ return m_NameString; } }
public int[] Hues{ get{ return m_Hues; } }
public CustomHueGroup( int name, int[] hues )
{
m_Name = name;
m_Hues = hues;
}
public CustomHueGroup( string name, int[] hues )
{
m_NameString = name;
m_Hues = hues;
}
}
public class CustomHuePicker
{
private CustomHueGroup[] m_Groups;
private bool m_DefaultSupported;
private int m_Title;
private string m_TitleString;
public bool DefaultSupported{ get{ return m_DefaultSupported; } }
public CustomHueGroup[] Groups{ get{ return m_Groups; } }
public int Title{ get{ return m_Title; } }
public string TitleString{ get{ return m_TitleString; } }
public CustomHuePicker( CustomHueGroup[] groups, bool defaultSupported )
{
m_Groups = groups;
m_DefaultSupported = defaultSupported;
}
public CustomHuePicker( CustomHueGroup[] groups, bool defaultSupported, int title )
{
m_Groups = groups;
m_DefaultSupported = defaultSupported;
m_Title = title;
}
public CustomHuePicker( CustomHueGroup[] groups, bool defaultSupported, string title )
{
m_Groups = groups;
m_DefaultSupported = defaultSupported;
m_TitleString = title;
}
public static readonly CustomHuePicker SpecialDyeTub = new CustomHuePicker( new CustomHueGroup[]
{
/* Violet */
new CustomHueGroup( 1018345, new int[]{ 1230, 1231, 1232, 1233, 1234, 1235 } ),
/* Tan */
new CustomHueGroup( 1018346, new int[]{ 1501, 1502, 1503, 1504, 1505, 1506, 1507, 1508 } ),
/* Brown */
new CustomHueGroup( 1018347, new int[]{ 2012, 2013, 2014, 2015, 2016, 2017 } ),
/* Dark Blue */
new CustomHueGroup( 1018348, new int[]{ 1303, 1304, 1305, 1306, 1307, 1308 } ),
/* Forest Green */
new CustomHueGroup( 1018349, new int[]{ 1420, 1421, 1422, 1423, 1424, 1425, 1426 } ),
/* Pink */
new CustomHueGroup( 1018350, new int[]{ 1619, 1620, 1621, 1622, 1623, 1624, 1625, 1626 } ),
/* Red */
new CustomHueGroup( 1018351, new int[]{ 1640, 1641, 1642, 1643, 1644 } ),
/* Olive */
new CustomHueGroup( 1018352, new int[]{ 2001, 2002, 2003, 2004, 2005 } )
}, false, 1018344 );
public static readonly CustomHuePicker LeatherDyeTub = new CustomHuePicker( new CustomHueGroup[]
{
/* Dull Copper */
new CustomHueGroup( 1018332, new int[]{ 2419, 2420, 2421, 2422, 2423, 2424 } ),
/* Shadow Iron */
new CustomHueGroup( 1018333, new int[]{ 2406, 2407, 2408, 2409, 2410, 2411, 2412 } ),
/* Copper */
new CustomHueGroup( 1018334, new int[]{ 2413, 2414, 2415, 2416, 2417, 2418 } ),
/* Bronze */
new CustomHueGroup( 1018335, new int[]{ 2414, 2415, 2416, 2417, 2418 } ),
/* Glden */
new CustomHueGroup( 1018336, new int[]{ 2213, 2214, 2215, 2216, 2217, 2218 } ),
/* Agapite */
new CustomHueGroup( 1018337, new int[]{ 2425, 2426, 2427, 2428, 2429, 2430 } ),
/* Verite */
new CustomHueGroup( 1018338, new int[]{ 2207, 2208, 2209, 2210, 2211, 2212 } ),
/* Valorite */
new CustomHueGroup( 1018339, new int[]{ 2219, 2220, 2221, 2222, 2223, 2224 } ),
/* Reds */
new CustomHueGroup( 1018340, new int[]{ 2113, 2114, 2115, 2116, 2117, 2118 } ),
/* Blues */
new CustomHueGroup( 1018341, new int[]{ 2119, 2120, 2121, 2122, 2123, 2124 } ),
/* Greens */
new CustomHueGroup( 1018342, new int[]{ 2126, 2127, 2128, 2129, 2130 } ),
/* Yellows */
new CustomHueGroup( 1018343, new int[]{ 2213, 2214, 2215, 2216, 2217, 2218 } )
}, true );
}
public delegate void CustomHuePickerCallback( Mobile from, object state, int hue );
public class CustomHuePickerGump : Gump
{
private Mobile m_From;
private CustomHuePicker m_Definition;
private CustomHuePickerCallback m_Callback;
private object m_State;
private int GetRadioID( int group, int index )
{
return (index * m_Definition.Groups.Length) + group;
}
private void RenderBackground()
{
AddPage( 0 );
AddBackground( 0, 0, 450, 450, 5054 );
AddBackground( 10, 10, 430, 430, 3000 );
if ( m_Definition.TitleString != null )
AddHtml( 20, 30, 400, 25, m_Definition.TitleString, false, false );
else if ( m_Definition.Title > 0 )
AddHtmlLocalized( 20, 30, 400, 25, m_Definition.Title, false, false );
AddButton( 20, 400, 4005, 4007, 1, GumpButtonType.Reply, 0 );
AddHtmlLocalized( 55, 400, 200, 25, 1011036, false, false ); // OKAY
if ( m_Definition.DefaultSupported )
{
AddButton( 200, 400, 4005, 4007, 2, GumpButtonType.Reply, 0 );
AddLabel( 235, 400, 0, "DEFAULT" );
}
}
private void RenderCategories()
{
CustomHueGroup[] groups = m_Definition.Groups;
for ( int i = 0; i < groups.Length; ++i )
{
AddButton( 30, 85 + (i * 25), 5224, 5224, 0, GumpButtonType.Page, 1 + i );
if ( groups[i].NameString != null )
AddHtml( 55, 85 + (i * 25), 200, 25, groups[i].NameString, false, false );
else
AddHtmlLocalized( 55, 85 + (i * 25), 200, 25, groups[i].Name, false, false );
}
for ( int i = 0; i < groups.Length; ++i )
{
AddPage( 1 + i );
int[] hues = groups[i].Hues;
for ( int j = 0; j < hues.Length; ++j )
{
AddRadio( 260, 90 + (j * 25), 210, 211, false, GetRadioID( i, j ) );
AddLabel( 278, 90 + (j * 25), hues[j] - 1, "*****" );
}
}
}
public CustomHuePickerGump( Mobile from, CustomHuePicker definition, CustomHuePickerCallback callback, object state ) : base( 50, 50 )
{
m_From = from;
m_Definition = definition;
m_Callback = callback;
m_State = state;
RenderBackground();
RenderCategories();
}
public override void OnResponse( NetState sender, RelayInfo info )
{
switch ( info.ButtonID )
{
case 1: // Okay
{
int[] switches = info.Switches;
if ( switches.Length > 0 )
{
int index = switches[0];
int group = index % m_Definition.Groups.Length;
index /= m_Definition.Groups.Length;
if ( group >= 0 && group < m_Definition.Groups.Length )
{
int[] hues = m_Definition.Groups[group].Hues;
if ( index >= 0 && index < hues.Length )
m_Callback( m_From, m_State, hues[index] );
}
}
break;
}
case 2: // Default
{
if ( m_Definition.DefaultSupported )
m_Callback( m_From, m_State, 0 );
break;
}
}
}
}
} | 30.459821 | 137 | 0.612634 | [
"MIT"
] | netcode-gamer/game.ultimaonline.io | UltimaOnline.Data/Items/Skill Items/Tailor Items/Dyetubs/CustomHuePicker.cs | 6,823 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("PhanMemXuong")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("PhanMemXuong")]
[assembly: AssemblyCopyright("Copyright © 2021")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("16b48305-3911-43bd-abed-f9a0c988e448")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.555556 | 84 | 0.751479 | [
"MIT"
] | cdcnguyensinh/phanmemxuong | PhanMemXuong/Properties/AssemblyInfo.cs | 1,355 | C# |
using System;
using System.Net;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Rug.Osc.Tests
{
/// <summary>
///This is a test class for OscSenderTest and is intended
///to contain all OscSenderTest Unit Tests
///</summary>
[TestClass()]
public class OscSenderTest
{
private TestContext testContextInstance;
/// <summary>
///Gets or sets the test context which provides
///information about and functionality for the current test run.
///</summary>
public TestContext TestContext
{
get
{
return testContextInstance;
}
set
{
testContextInstance = value;
}
}
#region Additional test attributes
//
//You can use the following additional attributes as you write your tests:
//
//Use ClassInitialize to run code before running the first test in the class
//[ClassInitialize()]
//public static void MyClassInitialize(TestContext testContext)
//{
//}
//
//Use ClassCleanup to run code after all tests in a class have run
//[ClassCleanup()]
//public static void MyClassCleanup()
//{
//}
//
//Use TestInitialize to run code before running each test
//[TestInitialize()]
//public void MyTestInitialize()
//{
//}
//
//Use TestCleanup to run code after each test has run
//[TestCleanup()]
//public void MyTestCleanup()
//{
//}
//
#endregion
/// <summary>
///A test for Send
///</summary>
[TestMethod()]
public void SendTest()
{
try
{
// This is the ip address we are going to send to
IPAddress address = IPAddress.Loopback;
// This is the port we are going to send to
int port = 12345;
// Create a new sender instance
using (OscSender sender = new OscSender(address, port))
{
// Connect the sender socket
sender.Connect();
// Send a new message
sender.Send(new OscMessage("/test", 1, 2, 3, 4));
}
}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}
}
}
}
| 21.12766 | 78 | 0.644512 | [
"MIT"
] | barjonas/StarDust.RugOsc.netstandard | src/Rug.Osc.Tests/Rug.Osc.Tests/OscSenderTest.cs | 1,988 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace CSharpMath.Interfaces {
public interface IStringValue {
///<summary>Not the LaTeX form.</summary>
string StringValue { get; }
}
}
| 21 | 46 | 0.692641 | [
"MIT"
] | hflexgrig/CSharpMath | CSharpMath/Interfaces/IStringValue.cs | 233 | C# |
namespace AnnoSavegameViewer.Structures.Savegame.Generated {
using AnnoSavegameViewer.Serialization.Core;
public class TreeMap {
[BinaryContent(Name = "x", NodeType = BinaryContentTypes.Attribute)]
public object X { get; set; }
[BinaryContent(Name = "y", NodeType = BinaryContentTypes.Attribute)]
public object Y { get; set; }
[BinaryContent(Name = "bits", NodeType = BinaryContentTypes.Attribute)]
public object Bits { get; set; }
}
} | 29.375 | 75 | 0.710638 | [
"MIT"
] | Veraatversus/AnnoSavegameViewer | src/AnnoSavegameViewer/GeneratedA7s/Structures/Savegame2/Generated/Content/TreeMap.cs | 470 | C# |
using System;
namespace healthbook
{
public enum AppMode
{
Patient,
Doctor
}
}
| 7.416667 | 20 | 0.674157 | [
"MIT"
] | atabaksahraei/ifn661 | healthbook/healthbook/Model/BL/Entity/AppMode.cs | 91 | C# |
using System;
using System.Text;
namespace Village
{
public class Peasant : Person
{
private const int maxAge = 110;
private int productivity;
public Peasant(string name, int age, int productivity)
: base(name, age)
{
this.Productivity = productivity;
}
public override int Age
{
get { return base.Age; }
protected set
{
base.Age = value;
if (value > maxAge)
{
throw new ArgumentException("Age cannot be greater than 110!");
}
}
}
public int Productivity
{
get { return this.productivity; }
private set
{
if (value <= 0)
{
throw new ArgumentException("Productivity cannot be less or equal to 0!");
}
this.productivity = value;
}
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.AppendLine(base.ToString());
sb.AppendLine($"Productivity: {this.Productivity}");
return sb.ToString().TrimEnd();
}
}
}
| 23.618182 | 94 | 0.468052 | [
"MIT"
] | Iceto04/SoftUni | C# OOP/14. Exam Preparations/OOPExam-24.10.2021/Village/Peasant.cs | 1,301 | C# |
using System.Collections.Generic;
using SqExpress.QueryBuilders.Merge;
using SqExpress.QueryBuilders.Merge.Internal;
using SqExpress.QueryBuilders.RecordSetter;
using SqExpress.QueryBuilders.RecordSetter.Internal;
using SqExpress.Syntax.Boolean;
using SqExpress.Syntax.Names;
using SqExpress.Syntax.Select;
using SqExpress.Syntax.Update;
using SqExpress.Utils;
namespace SqExpress.QueryBuilders.Update.Internal
{
internal class UpdateDataBuilder<TTable, TItem> : IUpdateDataBuilder<TTable, TItem>
where TTable : ExprTable
{
private readonly TTable _table;
private readonly IEnumerable<TItem> _data;
private readonly ExprTableAlias _sourceTableAlias;
private DataMapping<TTable, TItem>? _dataMapKeys;
private DataMapping<TTable, TItem>? _dataMap;
private MergeUpdateMapping<TTable>? _alsoSet;
public UpdateDataBuilder(TTable table, IEnumerable<TItem> data, IExprAlias sourceTableAlias)
{
this._table = table;
this._data = data;
this._sourceTableAlias = new ExprTableAlias(sourceTableAlias);
}
public IUpdateDataBuilderMapData<TTable, TItem> MapDataKeys(DataMapping<TTable, TItem> mapping)
{
this._dataMapKeys = mapping.AssertArgumentNotNull(nameof(mapping));
return this;
}
public IUpdateDataBuilderAlsoSet<TTable> MapData(DataMapping<TTable, TItem> mapping)
{
this._dataMap = mapping.AssertArgumentNotNull(nameof(mapping));
return this;
}
public IUpdateDataBuilderFinal AlsoSet(MergeUpdateMapping<TTable> mapping)
{
this._alsoSet = mapping.AssertArgumentNotNull(nameof(mapping));
return this;
}
public ExprUpdate Done()
{
var (keys, allColumns, exprValuesTable) = Helpers.AnalyzeUpdateData(
data: this._data,
targetTable: this._table,
dataMapKeys: this._dataMapKeys.AssertNotNull("DataMapKeys should be initialized"),
dataMap: this._dataMap.AssertNotNull("DataMap should be initialized"),
extraDataMap: null,
sourceTableAlias: this._sourceTableAlias);
var source = new ExprJoinedTable(this._table,
ExprJoinedTable.ExprJoinType.Inner,
exprValuesTable,
this.GetWhere(keys));
return new ExprUpdate(
target: this._table,
setClause: this.GetSets(allColumns: allColumns, keys: keys),
source: source,
filter: null);
}
private ExprColumnSetClause[] GetSets(IReadOnlyList<ExprColumnName> allColumns, List<ExprColumnName> keys)
{
IReadOnlyList<ColumnValueUpdateMap>? extraMaps = null;
if (this._alsoSet != null)
{
var mergeUpdateSetter = new MergerUpdateSetter<TTable>(this._table, this._sourceTableAlias);
this._alsoSet.Invoke(mergeUpdateSetter);
extraMaps = mergeUpdateSetter.Maps;
}
var updateColNum = allColumns.Count - keys.Count;
ExprColumnSetClause[] sets = new ExprColumnSetClause[updateColNum + (extraMaps?.Count ?? 0)];
for (int i = keys.Count; i < allColumns.Count; i++)
{
sets[i - keys.Count] = new ExprColumnSetClause(allColumns[i].WithSource(this._table.Alias),
allColumns[i].WithSource(this._sourceTableAlias));
}
if (extraMaps != null && extraMaps.Count > 0)
{
for (int i = updateColNum; i < sets.Length; i++)
{
var extraMap = extraMaps[i - updateColNum];
sets[i] = new ExprColumnSetClause(extraMap.Column.WithSource(this._table.Alias), extraMap.Value);
}
}
HashSet<ExprColumn> duplicateChecker = new HashSet<ExprColumn>();
for (int i = 0; i < sets.Length; i++)
{
if (!duplicateChecker.Add(sets[i].Column))
{
throw new SqExpressException(
$"The column name '{sets[i].Column.ColumnName.Name}' is specified more than once in the SET clause");
}
}
return sets;
}
private ExprBoolean GetWhere(IReadOnlyList<ExprColumnName> keys)
{
ExprBoolean? result = null;
foreach (var key in keys)
{
result = result & key.WithSource(this._table.Alias) == key.WithSource(this._sourceTableAlias);
}
return result.AssertNotNull("Update condition cannot be null");
}
}
} | 37.310078 | 125 | 0.605236 | [
"MIT"
] | 0x1000000/SqExpress | SqExpress/QueryBuilders/Update/Internal/UpdateDataBuilder.cs | 4,815 | C# |
namespace dueltank.core.Models.Db
{
public class AspNetUserTokens
{
public string UserId { get; set; }
public string LoginProvider { get; set; }
public string Name { get; set; }
public string Value { get; set; }
public AspNetUsers User { get; set; }
}
} | 25.583333 | 49 | 0.596091 | [
"MIT"
] | fablecode/dueltank | src/Api/src/dueltank.core/Models/Db/AspNetUserTokens.cs | 309 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.ResourceManager.AppService.Models;
using Azure.ResourceManager.Core;
namespace Azure.ResourceManager.AppService
{
/// <summary> A class representing collection of SiteExtensionInfo and their operations over its parent. </summary>
public partial class SiteSiteextensionCollection : ArmCollection, IEnumerable<SiteSiteextension>, IAsyncEnumerable<SiteSiteextension>
{
private readonly ClientDiagnostics _siteSiteextensionWebAppsClientDiagnostics;
private readonly WebAppsRestOperations _siteSiteextensionWebAppsRestClient;
/// <summary> Initializes a new instance of the <see cref="SiteSiteextensionCollection"/> class for mocking. </summary>
protected SiteSiteextensionCollection()
{
}
/// <summary> Initializes a new instance of the <see cref="SiteSiteextensionCollection"/> class. </summary>
/// <param name="parent"> The resource representing the parent resource. </param>
internal SiteSiteextensionCollection(ArmResource parent) : base(parent)
{
_siteSiteextensionWebAppsClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.AppService", SiteSiteextension.ResourceType.Namespace, DiagnosticOptions);
ArmClient.TryGetApiVersion(SiteSiteextension.ResourceType, out string siteSiteextensionWebAppsApiVersion);
_siteSiteextensionWebAppsRestClient = new WebAppsRestOperations(_siteSiteextensionWebAppsClientDiagnostics, Pipeline, DiagnosticOptions.ApplicationId, BaseUri, siteSiteextensionWebAppsApiVersion);
#if DEBUG
ValidateResourceId(Id);
#endif
}
internal static void ValidateResourceId(ResourceIdentifier id)
{
if (id.ResourceType != WebSite.ResourceType)
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, WebSite.ResourceType), nameof(id));
}
// Collection level operations.
/// RequestPath: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}/siteextensions/{siteExtensionId}
/// ContextualPath: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}
/// OperationId: WebApps_InstallSiteExtension
/// <summary> Description for Install site extension on a web site, or a deployment slot. </summary>
/// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param>
/// <param name="siteExtensionId"> Site extension name. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="siteExtensionId"/> is empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="siteExtensionId"/> is null. </exception>
public virtual SiteSiteextensionCreateOrUpdateOperation CreateOrUpdate(bool waitForCompletion, string siteExtensionId, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(siteExtensionId, nameof(siteExtensionId));
using var scope = _siteSiteextensionWebAppsClientDiagnostics.CreateScope("SiteSiteextensionCollection.CreateOrUpdate");
scope.Start();
try
{
var response = _siteSiteextensionWebAppsRestClient.InstallSiteExtension(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, siteExtensionId, cancellationToken);
var operation = new SiteSiteextensionCreateOrUpdateOperation(ArmClient, _siteSiteextensionWebAppsClientDiagnostics, Pipeline, _siteSiteextensionWebAppsRestClient.CreateInstallSiteExtensionRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, siteExtensionId).Request, response);
if (waitForCompletion)
operation.WaitForCompletion(cancellationToken);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// RequestPath: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}/siteextensions/{siteExtensionId}
/// ContextualPath: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}
/// OperationId: WebApps_InstallSiteExtension
/// <summary> Description for Install site extension on a web site, or a deployment slot. </summary>
/// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param>
/// <param name="siteExtensionId"> Site extension name. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="siteExtensionId"/> is empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="siteExtensionId"/> is null. </exception>
public async virtual Task<SiteSiteextensionCreateOrUpdateOperation> CreateOrUpdateAsync(bool waitForCompletion, string siteExtensionId, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(siteExtensionId, nameof(siteExtensionId));
using var scope = _siteSiteextensionWebAppsClientDiagnostics.CreateScope("SiteSiteextensionCollection.CreateOrUpdate");
scope.Start();
try
{
var response = await _siteSiteextensionWebAppsRestClient.InstallSiteExtensionAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, siteExtensionId, cancellationToken).ConfigureAwait(false);
var operation = new SiteSiteextensionCreateOrUpdateOperation(ArmClient, _siteSiteextensionWebAppsClientDiagnostics, Pipeline, _siteSiteextensionWebAppsRestClient.CreateInstallSiteExtensionRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, siteExtensionId).Request, response);
if (waitForCompletion)
await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// RequestPath: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}/siteextensions/{siteExtensionId}
/// ContextualPath: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}
/// OperationId: WebApps_GetSiteExtension
/// <summary> Description for Get site extension information by its ID for a web site, or a deployment slot. </summary>
/// <param name="siteExtensionId"> Site extension name. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="siteExtensionId"/> is empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="siteExtensionId"/> is null. </exception>
public virtual Response<SiteSiteextension> Get(string siteExtensionId, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(siteExtensionId, nameof(siteExtensionId));
using var scope = _siteSiteextensionWebAppsClientDiagnostics.CreateScope("SiteSiteextensionCollection.Get");
scope.Start();
try
{
var response = _siteSiteextensionWebAppsRestClient.GetSiteExtension(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, siteExtensionId, cancellationToken);
if (response.Value == null)
throw _siteSiteextensionWebAppsClientDiagnostics.CreateRequestFailedException(response.GetRawResponse());
return Response.FromValue(new SiteSiteextension(ArmClient, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// RequestPath: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}/siteextensions/{siteExtensionId}
/// ContextualPath: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}
/// OperationId: WebApps_GetSiteExtension
/// <summary> Description for Get site extension information by its ID for a web site, or a deployment slot. </summary>
/// <param name="siteExtensionId"> Site extension name. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="siteExtensionId"/> is empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="siteExtensionId"/> is null. </exception>
public async virtual Task<Response<SiteSiteextension>> GetAsync(string siteExtensionId, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(siteExtensionId, nameof(siteExtensionId));
using var scope = _siteSiteextensionWebAppsClientDiagnostics.CreateScope("SiteSiteextensionCollection.Get");
scope.Start();
try
{
var response = await _siteSiteextensionWebAppsRestClient.GetSiteExtensionAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, siteExtensionId, cancellationToken).ConfigureAwait(false);
if (response.Value == null)
throw await _siteSiteextensionWebAppsClientDiagnostics.CreateRequestFailedExceptionAsync(response.GetRawResponse()).ConfigureAwait(false);
return Response.FromValue(new SiteSiteextension(ArmClient, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Tries to get details for this resource from the service. </summary>
/// <param name="siteExtensionId"> Site extension name. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="siteExtensionId"/> is empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="siteExtensionId"/> is null. </exception>
public virtual Response<SiteSiteextension> GetIfExists(string siteExtensionId, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(siteExtensionId, nameof(siteExtensionId));
using var scope = _siteSiteextensionWebAppsClientDiagnostics.CreateScope("SiteSiteextensionCollection.GetIfExists");
scope.Start();
try
{
var response = _siteSiteextensionWebAppsRestClient.GetSiteExtension(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, siteExtensionId, cancellationToken: cancellationToken);
if (response.Value == null)
return Response.FromValue<SiteSiteextension>(null, response.GetRawResponse());
return Response.FromValue(new SiteSiteextension(ArmClient, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Tries to get details for this resource from the service. </summary>
/// <param name="siteExtensionId"> Site extension name. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="siteExtensionId"/> is empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="siteExtensionId"/> is null. </exception>
public async virtual Task<Response<SiteSiteextension>> GetIfExistsAsync(string siteExtensionId, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(siteExtensionId, nameof(siteExtensionId));
using var scope = _siteSiteextensionWebAppsClientDiagnostics.CreateScope("SiteSiteextensionCollection.GetIfExists");
scope.Start();
try
{
var response = await _siteSiteextensionWebAppsRestClient.GetSiteExtensionAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, siteExtensionId, cancellationToken: cancellationToken).ConfigureAwait(false);
if (response.Value == null)
return Response.FromValue<SiteSiteextension>(null, response.GetRawResponse());
return Response.FromValue(new SiteSiteextension(ArmClient, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Tries to get details for this resource from the service. </summary>
/// <param name="siteExtensionId"> Site extension name. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="siteExtensionId"/> is empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="siteExtensionId"/> is null. </exception>
public virtual Response<bool> Exists(string siteExtensionId, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(siteExtensionId, nameof(siteExtensionId));
using var scope = _siteSiteextensionWebAppsClientDiagnostics.CreateScope("SiteSiteextensionCollection.Exists");
scope.Start();
try
{
var response = GetIfExists(siteExtensionId, cancellationToken: cancellationToken);
return Response.FromValue(response.Value != null, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Tries to get details for this resource from the service. </summary>
/// <param name="siteExtensionId"> Site extension name. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="siteExtensionId"/> is empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="siteExtensionId"/> is null. </exception>
public async virtual Task<Response<bool>> ExistsAsync(string siteExtensionId, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(siteExtensionId, nameof(siteExtensionId));
using var scope = _siteSiteextensionWebAppsClientDiagnostics.CreateScope("SiteSiteextensionCollection.Exists");
scope.Start();
try
{
var response = await GetIfExistsAsync(siteExtensionId, cancellationToken: cancellationToken).ConfigureAwait(false);
return Response.FromValue(response.Value != null, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// RequestPath: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}/siteextensions
/// ContextualPath: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}
/// OperationId: WebApps_ListSiteExtensions
/// <summary> Description for Get list of siteextensions for a web site, or a deployment slot. </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <returns> A collection of <see cref="SiteSiteextension" /> that may take multiple service requests to iterate over. </returns>
public virtual Pageable<SiteSiteextension> GetAll(CancellationToken cancellationToken = default)
{
Page<SiteSiteextension> FirstPageFunc(int? pageSizeHint)
{
using var scope = _siteSiteextensionWebAppsClientDiagnostics.CreateScope("SiteSiteextensionCollection.GetAll");
scope.Start();
try
{
var response = _siteSiteextensionWebAppsRestClient.ListSiteExtensions(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken: cancellationToken);
return Page.FromValues(response.Value.Value.Select(value => new SiteSiteextension(ArmClient, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
Page<SiteSiteextension> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = _siteSiteextensionWebAppsClientDiagnostics.CreateScope("SiteSiteextensionCollection.GetAll");
scope.Start();
try
{
var response = _siteSiteextensionWebAppsRestClient.ListSiteExtensionsNextPage(nextLink, Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken: cancellationToken);
return Page.FromValues(response.Value.Value.Select(value => new SiteSiteextension(ArmClient, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc);
}
/// RequestPath: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}/siteextensions
/// ContextualPath: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}
/// OperationId: WebApps_ListSiteExtensions
/// <summary> Description for Get list of siteextensions for a web site, or a deployment slot. </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <returns> An async collection of <see cref="SiteSiteextension" /> that may take multiple service requests to iterate over. </returns>
public virtual AsyncPageable<SiteSiteextension> GetAllAsync(CancellationToken cancellationToken = default)
{
async Task<Page<SiteSiteextension>> FirstPageFunc(int? pageSizeHint)
{
using var scope = _siteSiteextensionWebAppsClientDiagnostics.CreateScope("SiteSiteextensionCollection.GetAll");
scope.Start();
try
{
var response = await _siteSiteextensionWebAppsRestClient.ListSiteExtensionsAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken: cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value.Select(value => new SiteSiteextension(ArmClient, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
async Task<Page<SiteSiteextension>> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = _siteSiteextensionWebAppsClientDiagnostics.CreateScope("SiteSiteextensionCollection.GetAll");
scope.Start();
try
{
var response = await _siteSiteextensionWebAppsRestClient.ListSiteExtensionsNextPageAsync(nextLink, Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken: cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value.Select(value => new SiteSiteextension(ArmClient, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc);
}
IEnumerator<SiteSiteextension> IEnumerable<SiteSiteextension>.GetEnumerator()
{
return GetAll().GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetAll().GetEnumerator();
}
IAsyncEnumerator<SiteSiteextension> IAsyncEnumerable<SiteSiteextension>.GetAsyncEnumerator(CancellationToken cancellationToken)
{
return GetAllAsync(cancellationToken: cancellationToken).GetAsyncEnumerator(cancellationToken);
}
}
}
| 59.467033 | 298 | 0.672595 | [
"MIT"
] | git-thomasdolan/azure-sdk-for-net | sdk/websites/Azure.ResourceManager.AppService/src/Generated/SiteSiteextensionCollection.cs | 21,646 | C# |
using GameArchiveSync.App.Helpers;
using System;
using System.Windows.Forms;
namespace GameArchiveSync.App
{
internal static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
private static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.ThreadException += Application_ThreadException;
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
Application.Run(new MainFrm());
}
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
WinFormsUtil.Alert(e.ExceptionObject.ToString());
}
private static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
{
WinFormsUtil.Alert(e.Exception.Message);
}
}
} | 31.28125 | 115 | 0.656344 | [
"MIT"
] | hstarorg/GameArchiveSync | GameArchiveSync.App/Program.cs | 1,023 | C# |
namespace ArtTrail.DomainEntities.ModelMapping
{
using System.Data.Entity.ModelConfiguration;
public class VenueConfiguration : EntityTypeConfiguration<Venue>
{
#region Constructors and Destructors
public VenueConfiguration()
{
this.Property(x => x.VenueName).HasMaxLength(50).IsRequired();
this.HasMany(x => x.Artists).WithMany(x => x.Venues);
this.HasMany(c => c.Categories).WithMany(p => p.VenueCategories).Map(
m =>
{
m.MapLeftKey("VenueId");
m.MapRightKey("CategoryId");
m.ToTable("VenueCategories");
});
}
#endregion
}
}
| 30.04 | 81 | 0.535286 | [
"Apache-2.0"
] | zebslc/ArtTrail | ArtTrail.DomainEntities/ModelMapping/VenueConfiguration.cs | 753 | C# |
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using Urbanice.Data;
using Urbanice.Maniplulators;
using Urbanice.Utils;
namespace Urbanice.Generators._2D.Grid
{
public class Raster
{
private RasterGenerator _rasterGenerator;
private List<List<Vector2>> _gridPoints;
private List<ShapeRelaxManipulator> _manipulators;
private Polygon OutSideShape;
public List<Polygon> ClosedCells;
public List<Vertex> ControlPoints;
public Raster(IValueGenerator<float> random, RasterGenerator parameters, List<ShapeRelaxManipulator> manipulators)
{
_rasterGenerator = parameters;
_manipulators = manipulators;
}
public List<Polygon> Generate(List<Vector2> additionalControlPoints, Polygon outsideShape, bool connectToOutsideShape)
{
_gridPoints = new List<List<Vector2>>();
ClosedCells = new List<Polygon>();
OutSideShape = outsideShape;
ControlPoints = new List<Vertex>();
GenerateGridPoints();
GenerateCells();
if (_manipulators != null)
{
foreach (var manipluator in _manipulators)
{
manipluator.Manipluate(ClosedCells);
}
}
ClosedCells = GeometryUtils.RemoveOutsidePolygons(ClosedCells, OutSideShape);
if (connectToOutsideShape)
{
var borderCells = GeometryUtils.CreateBorderPolygons(ClosedCells, outsideShape);
ClosedCells.AddRange(borderCells);
}
return ClosedCells;
}
private void GenerateCells()
{
for (var x = 0; x < _gridPoints.Count - 1; x++)
{
for (var y = 0; y < _gridPoints[x].Count - 1; y++)
{
var px0 = _gridPoints[x][y];
var py0 = _gridPoints[x][y+1];
var py1 = _gridPoints[x+1][y+1];
var px1 = _gridPoints[x+1][y];
var edgeList = new List<HalfEdge>(4);
var vx0 = Vertex.Factory.Create(px0);
var vx1 = Vertex.Factory.Create(px1);
var vy0 = Vertex.Factory.Create(py0);
var vy1 = Vertex.Factory.Create(py1);
var e1 = new HalfEdge(vx0, vy0);
var e2 = new HalfEdge(vy0, vy1);
var e3 = new HalfEdge(vy1, vx1);
var e4 = new HalfEdge(vx1, vx0);
e1.NextEdge = e3.PreviousEdge = e2;
e2.NextEdge = e4.PreviousEdge = e3;
e3.NextEdge = e1.PreviousEdge = e4;
e4.NextEdge = e2.PreviousEdge = e1;
edgeList.AddMultiple(e1, e2, e3, e4);
var p = new Polygon(edgeList);
ClosedCells.Add(p);
ControlPoints.AddMultiple(vx0, vx1, vy0, vy1);
}
}
ControlPoints = ControlPoints.Distinct().ToList();
}
private void GenerateGridPoints()
{
float segmentLength = OutSideShape.BoundingBox.size.y / _rasterGenerator.GridSegments.x;
for (int i = 0; i < _rasterGenerator.GridSegments.x+1; i++)
{
Vector2 ps = new Vector2(OutSideShape.BoundingBox.min.x, OutSideShape.BoundingBox.min.y + segmentLength * i ) ;
Vector2 pe = new Vector2(OutSideShape.BoundingBox.max.x, y: OutSideShape.BoundingBox.min.y + segmentLength * i ) ;
var h = GeometryUtils.SubdivideLineSegment(ps,pe, _rasterGenerator.GridSegments.y - 1);
_gridPoints.Add(h);
}
}
}
} | 36.25 | 130 | 0.533844 | [
"MIT"
] | Cxyda/Urbanice | Assets/Scripts/Urbanice/Generators/2D/Grid/Raster.cs | 3,915 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
namespace KerbalLaunchVehicles.klvGUI
{
class GUITextBox : IGUIControl
{
private string LabelLeft;
private string LabelRight;
private string Text;
private string NewText;
private int TextWidth;
private int TotalWidth;
internal bool isEditing { get; private set; }
public IGUIControl Parent { get; set; }
private DoButtonPress EnterPressedAction;
internal GUITextBox(string _labelLft = "", string _text = "", string _labelRt = "", int _textWidth = 100, int _totalWidth = 200,
DoButtonPress _enter = null)
{
LabelLeft = _labelLft;
LabelRight = _labelRt;
Text = _text;
NewText = _text;
TextWidth = _textWidth;
TotalWidth = _totalWidth;
EnterPressedAction = _enter;
}
public object DoLayout(GUIStyle style = null, object newValue = null, object input = null)
{
Text = NewText;
GUILayout.BeginHorizontal(GUILayout.Width(TotalWidth), GUILayout.ExpandWidth(true));
GUILayout.Label(LabelLeft, style?? klvGUIStyles.StandardLabel, GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(false));
if(Event.current.Equals(Event.KeyboardEvent("return")))
{
EnterPressedAction(null, Text.Trim());
}
NewText = GUILayout.TextField(Text, klvGUIStyles.StandardTextBox, GUILayout.Width(TextWidth));
GUILayout.Label(LabelRight, style ?? klvGUIStyles.StandardLabel, GUILayout.ExpandWidth(false));
GUILayout.EndHorizontal();
// Return null if text hasn't changed
if(Text != NewText)
{
isEditing = true;
}
return isEditing ? NewText : "";
}
internal void SetEditing(bool _edit)
{
isEditing = _edit;
}
internal void SetText(string _text)
{
Text = _text;
NewText = _text;
}
internal string GetText()
{
return NewText;
}
}
}
| 31.931507 | 138 | 0.566281 | [
"MIT"
] | JCoil/KerbalLaunchVehicles | KerbalLaunchVehicles/klvGUI/GUITextBox.cs | 2,333 | C# |
// FILE AUTOGENERATED. DO NOT MODIFY
using System;
namespace Starfield.Core.Block.Blocks {
[Block("minecraft:stripped_birch_log", 42, 94, 96, 95)]
public class BlockStrippedBirchLog : BlockBase {
public override ushort State {
get {
if(Axis == "x") {
return 94;
}
if(Axis == "y") {
return 95;
}
if(Axis == "z") {
return 96;
}
return DefaultState;
}
set {
if(value == 94) {
Axis = "x";
}
if(value == 95) {
Axis = "y";
}
if(value == 96) {
Axis = "z";
}
}
}
public string Axis { get; set; } = "y";
public BlockStrippedBirchLog() {
State = DefaultState;
}
public BlockStrippedBirchLog(ushort state) : base(state) {
if(state < MinimumState || state > MaximumState) {
throw new ArgumentOutOfRangeException("state");
}
State = state;
}
public BlockStrippedBirchLog(string axis) {
Axis = axis;
}
}
} | 23.35 | 67 | 0.381156 | [
"MIT"
] | StarfieldMC/Starfield | Starfield.Core/Block/Blocks/BlockStrippedBirchLog.cs | 1,401 | C# |
namespace AgileObjects.AgileMapper.UnitTests.Orms.EfCore2
{
using Infrastructure;
public class WhenViewingProjectionPlans : WhenViewingProjectionPlans<EfCore2TestDbContext>
{
public WhenViewingProjectionPlans(InMemoryEfCore2TestContext context)
: base(context)
{
}
}
}
| 24.846154 | 94 | 0.712074 | [
"MIT"
] | WeiiWang/AgileMapper | AgileMapper.UnitTests.Orms.EfCore2/WhenViewingProjectionPlans.cs | 325 | C# |
using GalaxyGen.Model;
using GalaxyGenCore;
using GalaxyGenCore.Resources;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GalaxyGen.Engine.Messages
{
public class MessageProducedResources
{
public MessageProducedResources(List<ResourceQuantity> resources, Agent owner)
{
Resources = resources;
Owner = owner;
}
public List<ResourceQuantity> Resources { get; set; }
public Agent Owner { get; set; }
}
}
| 23.333333 | 86 | 0.689286 | [
"MIT"
] | AshRolls/GalaxyGen | GalaxyGen/Engine/Messages/MessageProducedResources.cs | 562 | C# |
#region Apache License Version 2.0
/*----------------------------------------------------------------
Copyright 2022 Jeffrey Su & Suzhou Senparc Network Technology Co.,Ltd.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the
License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
either express or implied. See the License for the specific language governing permissions
and limitations under the License.
Detail: https://github.com/JeffreySu/WeiXinMPSDK/blob/master/license.md
----------------------------------------------------------------*/
#endregion Apache License Version 2.0
/*----------------------------------------------------------------
Copyright (C) 2022 Senparc
文件名:TenPayV3Util.cs
文件功能描述:微信支付V3配置文件
创建标识:Senparc - 20150211
修改标识:Senparc - 20150303
修改描述:整理接口
修改标识:Senparc - 20161014
修改描述:修改TenPayUtil.BuildRandomStr()方法
修改标识:Senparc - 20170516
修改描述:v14.4.8 1、完善TenPayLibV3.GetNoncestr()方法
2、优化BuildRandomStr()方法
修改标识:Senparc - 20170522
修改描述:v14.4.9 修改TenPayUtil.GetNoncestr()方法,将编码由GBK改为UTF8
修改标识:Senparc - 20180331
修改描述:v14.4.9 修改TenPayUtil.GetNoncestr()方法,将编码由GBK改为UTF8
----------------------------------------------------------------*/
using System;
using System.Text;
using System.Net;
using Senparc.Weixin.Helpers;
using Senparc.CO2NET.Helpers;
namespace Senparc.Weixin.TenPay.V3
{
/// <summary>
/// 微信支付工具类
/// </summary>
public class TenPayV3Util
{
public static Random random = new Random();
/// <summary>
/// 随机生成Noncestr
/// </summary>
/// <returns></returns>
public static string GetNoncestr()
{
return EncryptHelper.GetMD5(Guid.NewGuid().ToString(), "UTF-8");
}
/// <summary>
/// 获取微信时间格式
/// </summary>
/// <returns></returns>
public static string GetTimestamp()
{
TimeSpan ts = SystemTime.Now - new DateTimeOffset(1970, 1, 1, 0, 0, 0, 0, TimeSpan.Zero);
return Convert.ToInt64(ts.TotalSeconds).ToString();
}
/// <summary>
/// 对字符串进行URL编码
/// </summary>
/// <param name="instr"></param>
/// <param name="charset"></param>
/// <returns></returns>
public static string UrlEncode(string instr, string charset)
{
//return instr;
if (instr == null || instr.Trim() == "")
return "";
else
{
//string res;
try
{
#if NET462
return System.Web.HttpUtility.UrlEncode(instr, Encoding.GetEncoding(charset));
#else
return WebUtility.UrlEncode(instr);
#endif
}
catch (Exception ex)
{
#if NET462
return System.Web.HttpUtility.UrlEncode(instr, Encoding.GetEncoding("GB2312"));
#else
return WebUtility.UrlEncode(instr);
#endif
}
//return res;
}
}
/// <summary>
/// 对字符串进行URL解码
/// </summary>
/// <param name="instr"></param>
/// <param name="charset"></param>
/// <returns></returns>
public static string UrlDecode(string instr, string charset)
{
if (instr == null || instr.Trim() == "")
return "";
else
{
//string res;
try
{
#if NET462
return System.Web.HttpUtility.UrlDecode(instr, Encoding.GetEncoding(charset));
#else
return WebUtility.UrlDecode(instr);
#endif
}
catch (Exception ex)
{
#if NET462
return System.Web.HttpUtility.UrlDecode(instr, Encoding.GetEncoding("GB2312"));
#else
return WebUtility.UrlDecode(instr);
#endif
}
//return res;
}
}
/// <summary>
/// 取时间戳生成随即数,替换交易单号中的后10位流水号
/// </summary>
/// <returns></returns>
public static UInt32 UnixStamp()
{
//#if NET462
// TimeSpan ts = DateTime.Now - TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
//#else
TimeSpan ts = SystemTime.Now - new DateTimeOffset(1970, 1, 1, 0, 0, 0, 0, TimeSpan.Zero);
//#endif
return Convert.ToUInt32(ts.TotalSeconds);
}
/// <summary>
/// 取随机数
/// </summary>
/// <param name="length"></param>
/// <returns></returns>
public static string BuildRandomStr(int length)
{
int num;
lock (random)
{
num = random.Next();
}
string str = num.ToString();
if (str.Length > length)
{
str = str.Substring(0, length);
}
else if (str.Length < length)
{
int n = length - str.Length;
while (n > 0)
{
str = str.Insert(0, "0");
n--;
}
}
return str;
}
/// <summary>
/// 创建当天内不会重复的数字
/// </summary>
/// <param name="length"></param>
/// <returns></returns>
public static string BuildDailyRandomStr(int length)
{
var stringFormat = SystemTime.Now.ToString("HHmmss0000");//共10位
return stringFormat;
}
/// <summary>
/// 对退款通知消息进行解密
/// </summary>
/// <param name="reqInfo"></param>
/// <param name="mchKey"></param>
/// <returns></returns>
public static string DecodeRefundReqInfo(string reqInfo, string mchKey)
{
//参考文档:https://pay.weixin.qq.com/wiki/doc/api/native.php?chapter=9_16&index=11
/*
解密步骤如下:
(1)对加密串A做base64解码,得到加密串B
(2)对商户key做md5,得到32位小写key* ( key设置路径:微信商户平台(pay.weixin.qq.com)-->账户设置-->API安全-->密钥设置 )
(3)用key*对加密串B做AES-256-ECB解密(PKCS7Padding)
*/
//var base64Encode = Encoding.UTF8.GetString(Convert.FromBase64String(reqInfo));//(1)
var base64Encode = reqInfo;//(1) EncryptHelper.AESDecrypt 方法内部会进行一次base64解码,因此这里不再需要解码
var md5Str = EncryptHelper.GetLowerMD5(mchKey, Encoding.UTF8);//(2)
var result = EncryptHelper.AESDecrypt(base64Encode, md5Str);//(3)
return result;
}
}
}
| 29.168067 | 106 | 0.512388 | [
"Apache-2.0"
] | AaronWu666/WeiXinMPSDK | src/Senparc.Weixin.TenPay/Senparc.Weixin.TenPay/V3/TenPayV3Util.cs | 7,532 | C# |
/**
* Copyright 2015 Canada Health Infoway, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Author: $LastChangedBy: jmis $
* Last modified: $LastChangedDate: 2015-09-15 11:07:32 -0400 (Tue, 15 Sep 2015) $
* Revision: $LastChangedRevision: 9795 $
*/
/* This class was auto-generated by the message builder generator tools. */
namespace Ca.Infoway.Messagebuilder.Model.Pcs_mr2009_r02_04_02.Interaction {
using Ca.Infoway.Messagebuilder.Annotation;
using Ca.Infoway.Messagebuilder.Model;
using Ca.Infoway.Messagebuilder.Model.Pcs_mr2009_r02_04_02.Claims.Qucr_mt820201ca;
using Ca.Infoway.Messagebuilder.Model.Pcs_mr2009_r02_04_02.Claims.Qucr_mt830201ca;
using Ca.Infoway.Messagebuilder.Model.Pcs_mr2009_r02_04_02.Common.Mcci_mt002300ca;
using Ca.Infoway.Messagebuilder.Model.Pcs_mr2009_r02_04_02.Common.Quqi_mt120008ca;
/**
* <summary>Business Name: QUCR_IN830102CA: SOFA Detail Query
* Results, Rx</summary>
*
* <p>The sender sends a SOFA (Statement of Financial Activity)
* Detail Query Response message for Pharmacy services and/or
* products.The response is for detailed account activity
* information, including references to previously adjudicated
* Invoices.</p> Message: MCCI_MT002300CA.Message Control Act:
* QUQI_MT120008CA.ControlActEvent --> Payload:
* QUCR_MT830201CA.AdjudResultsGroup --> Payload:
* QUCR_MT820201CA.ParameterList
*/
[Hl7PartTypeMappingAttribute(new string[] {"QUCR_IN830102CA"})]
public class SOFADetailQueryResultsRx : HL7Message<Ca.Infoway.Messagebuilder.Model.Pcs_mr2009_r02_04_02.Common.Quqi_mt120008ca.TriggerEvent<Ca.Infoway.Messagebuilder.Model.Pcs_mr2009_r02_04_02.Claims.Qucr_mt830201ca.TypeOfSummary,Ca.Infoway.Messagebuilder.Model.Pcs_mr2009_r02_04_02.Claims.Qucr_mt820201ca.ParameterList>>, IInteraction {
public SOFADetailQueryResultsRx() {
}
}
} | 49.156863 | 342 | 0.73913 | [
"ECL-2.0",
"Apache-2.0"
] | CanadaHealthInfoway/message-builder-dotnet | message-builder-release-r02_04_02/Main/Ca/Infoway/Messagebuilder/Model/Pcs_mr2009_r02_04_02/Interaction/SOFADetailQueryResultsRx.cs | 2,507 | C# |
// ------------------------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------------------------------------------
using System;
namespace Microsoft.CoyoteActors.IO
{
/// <summary>
/// Interface of the runtime logger.
/// </summary>
public interface ILogger : IDisposable
{
/// <summary>
/// If true, then messages are logged.
/// </summary>
bool IsVerbose { get; set; }
/// <summary>
/// Writes the specified string value.
/// </summary>
void Write(string value);
/// <summary>
/// Writes the text representation of the specified argument.
/// </summary>
void Write(string format, object arg0);
/// <summary>
/// Writes the text representation of the specified arguments.
/// </summary>
void Write(string format, object arg0, object arg1);
/// <summary>
/// Writes the text representation of the specified arguments.
/// </summary>
void Write(string format, object arg0, object arg1, object arg2);
/// <summary>
/// Writes the text representation of the specified array of objects.
/// </summary>
void Write(string format, params object[] args);
/// <summary>
/// Writes the specified string value, followed by the
/// current line terminator.
/// </summary>
void WriteLine(string value);
/// <summary>
/// Writes the text representation of the specified argument, followed by the
/// current line terminator.
/// </summary>
void WriteLine(string format, object arg0);
/// <summary>
/// Writes the text representation of the specified arguments, followed by the
/// current line terminator.
/// </summary>
void WriteLine(string format, object arg0, object arg1);
/// <summary>
/// Writes the text representation of the specified arguments, followed by the
/// current line terminator.
/// </summary>
void WriteLine(string format, object arg0, object arg1, object arg2);
/// <summary>
/// Writes the text representation of the specified array of objects,
/// followed by the current line terminator.
/// </summary>
void WriteLine(string format, params object[] args);
}
}
| 34.815789 | 100 | 0.550265 | [
"MIT"
] | pdeligia/nekara-artifact | CoyoteActors/Framework/Coyote/Source/Core/IO/Logging/ILogger.cs | 2,648 | C# |
using Microsoft.AspNetCore.Identity;
namespace Skoruba.IdentityServer4.Admin.EntityFramework.Shared.Entities.Identity
{
public class UserIdentityUserLogin : IdentityUserLogin<string>
{
}
} | 23.444444 | 80 | 0.758294 | [
"MIT"
] | 1n5an1ty/IdentityServer4.Admin | src/Skoruba.IdentityServer4.Admin.EntityFramework.Shared/Entities/Identity/UserIdentityUserLogin.cs | 213 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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 GamesPortal.Client.Interfaces.Services;
using GamesPortal.Client.ViewModels.Workspace;
using Microsoft.Practices.ServiceLocation;
using Microsoft.Reporting.WinForms;
namespace GamesPortal.Client.Views.Wpf.Reports
{
/// <summary>
/// Interaction logic for LatestApprovedVersionForEachGameUserControl.xaml
/// </summary>
public partial class ReportHost : UserControl
{
public ReportHost()
{
InitializeComponent();
reportViewer.Load += reportViewer_Load;
}
public static readonly DependencyProperty ReportFullNameProperty = DependencyProperty.Register("ReportFullName", typeof(string), typeof(ReportHost));
public static readonly DependencyProperty DataSourceNameProperty = DependencyProperty.Register("DataSourceName", typeof(string), typeof(ReportHost), new PropertyMetadata("DataSource"));
public static readonly DependencyProperty ItemsSourceProperty = DependencyProperty.Register("ItemsSource", typeof(object), typeof(ReportHost), new PropertyMetadata(null, ItemsSourcePropertyChangedCallback));
public static readonly DependencyProperty ReportParametersProperty = DependencyProperty.Register("ReportParameters", typeof(IList<ReportViewerParameter>), typeof(ReportHost), new PropertyMetadata(new ReportViewerParameter[0], ReportParametersPropertyChangedCallback));
private static void ReportParametersPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var reportHost = d as ReportHost;
if (reportHost != null)
{
reportHost.RefreshReport();
}
}
public string ReportFullName
{
get { return (string)GetValue(ReportFullNameProperty); }
set { SetValue(ReportFullNameProperty, value); }
}
public string DataSourceName
{
get { return (string)GetValue(DataSourceNameProperty); }
set { SetValue(DataSourceNameProperty, value); }
}
public object ItemsSource
{
get { return GetValue(ItemsSourceProperty); }
set { SetValue(ItemsSourceProperty, value); }
}
public IList<ReportViewerParameter> ReportParameters
{
get { return (IList<ReportViewerParameter>)GetValue(ReportParametersProperty); }
set { SetValue(ReportParametersProperty, value); }
}
private static void ItemsSourcePropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var reportHost = d as ReportHost;
if (reportHost != null)
{
reportHost.RefreshReport();
}
}
private bool _isReportViewerLoaded;
void reportViewer_Load(object sender, EventArgs e)
{
if (!_isReportViewerLoaded)
{
RefreshReport();
_isReportViewerLoaded = true;
}
}
private void RefreshReport()
{
RefreshReportDataSource();
RefreshReportParameters();
reportViewer.RefreshReport();
}
private void RefreshReportParameters()
{
var parameters = new List<ReportParameter>();
foreach (var p in this.ReportParameters ?? new ReportViewerParameter[0])
{
parameters.Add(new ReportParameter(p.Name, p.Value));
}
if (parameters.Any())
{
try
{
this.reportViewer.LocalReport.SetParameters(parameters);
}
catch(Exception ex)
{
#warning here is just a workaroud
Console.WriteLine(ex.ToString());
}
}
}
private void RefreshReportDataSource()
{
this.reportViewer.LocalReport.ReportEmbeddedResource = this.ReportFullName;
Microsoft.Reporting.WinForms.ReportDataSource reportDataSource1 = new Microsoft.Reporting.WinForms.ReportDataSource(this.DataSourceName, this.ItemsSource);
this.reportViewer.LocalReport.DataSources.Clear();
this.reportViewer.LocalReport.DataSources.Add(reportDataSource1);
}
}
}
| 34.398551 | 276 | 0.642932 | [
"MIT"
] | jackobo/jackobs-code | Portal/Client/Head/src/Views.Wpf/Reports/ReportHost.xaml.cs | 4,749 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Beer.DaAPI.Core.Common
{
public class IPv4Address : IPAddress<IPv4Address>, IComparable<IPv4Address>, IEquatable<IPv4Address>
{
#region Fields
private readonly Byte[] _addressBytes;
private static readonly UInt32[] _conversations = new UInt32[4]
{
256 * 256 * 256,
256 * 256,
256,
1
};
#endregion
#region Constructor and Factories
public static IPv4Address Empty => new IPv4Address(new Byte[] { 0, 0, 0, 0 });
public override Byte[] GetBytes()
{
return new byte[]
{
_addressBytes[0],
_addressBytes[1],
_addressBytes[2],
_addressBytes[3],
};
}
public static IPv4Address Broadcast => new IPv4Address(new Byte[] { 255, 255, 255, 255 });
private IPv4Address(UInt32 value)
{
UInt32 nextValue = value;
Byte[] addressBytes = new byte[4];
for (int i = 0; i < 4; i++)
{
Byte byteValue = (Byte)(nextValue / _conversations[i]);
nextValue -= (byteValue * _conversations[i]);
addressBytes[i] = byteValue;
}
_addressBytes = addressBytes;
}
private IPv4Address(Byte[] address)
{
_addressBytes = address;
}
public static IPv4Address FromBytes(Byte firstOctet, Byte secondOcet, Byte thirdOctet, Byte fourhtOctet)
{
return FromByteArray(new Byte[4] { firstOctet, secondOcet, thirdOctet, fourhtOctet });
}
public static IPv4Address FromByteArray(Byte[] address)
{
if (address == null || address.Length != 4)
{
throw new ArgumentException(nameof(address));
}
return new IPv4Address(new byte[4]
{
address[0],
address[1],
address[2],
address[3],
});
}
public static IPv4Address FromByteArray(Byte[] stream, Int32 start)
{
if (stream == null || stream.Length < start + 4)
{
throw new ArgumentException(nameof(stream));
}
return new IPv4Address(new byte[] { stream[start], stream[start + 1], stream[start + 2], stream[start + 3] });
}
public static IPv4Address FromString(String address)
{
if (String.IsNullOrEmpty(address) == true)
{
throw new ArgumentNullException(nameof(address));
}
String[] parts = address.Trim().Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
if(parts.Length != 4)
{
throw new ArgumentException("invalid address", nameof(address));
}
Byte[] parsedAddress = new byte[4];
for (int i = 0; i < parts.Length; i++)
{
String part = parts[i];
try
{
Byte addressByte = Convert.ToByte(part);
parsedAddress[i] = addressByte;
}
catch (Exception)
{
throw new ArgumentException(nameof(address));
}
}
return new IPv4Address(parsedAddress);
}
#endregion
#region Methods
public override string ToString()
{
return $"{_addressBytes[0]}.{_addressBytes[1]}.{_addressBytes[2]}.{_addressBytes[3]}";
}
public override bool Equals(object other)
{
if (other is null) return false;
if (ReferenceEquals(this, other)) return true;
if (other is IPv4Address == false) { return false; }
IPv4Address realOther = (IPv4Address)other;
return Equals(realOther);
}
public bool Equals(IPv4Address other)
{
if (other == null) { return false; }
for (int i = 0; i < 4; i++)
{
if (this._addressBytes[i] != other._addressBytes[i])
{
return false;
}
}
return true;
}
public UInt32 GetNumericValue()
{
UInt32 result =
(UInt32)(_addressBytes[3] * _conversations[3]) +
(UInt32)(_addressBytes[2] * _conversations[2]) +
(UInt32)(_addressBytes[1] * _conversations[1]) +
(UInt32)(_addressBytes[0] * _conversations[0]);
return result;
}
public override int GetHashCode()
{
UInt32 numericValue = GetNumericValue();
return (Int32)numericValue;
}
public int CompareTo(IPv4Address other)
{
UInt32 ownValue = GetNumericValue();
UInt32 otherValue = other.GetNumericValue();
Int64 diff = (Int64)ownValue - (Int64)otherValue;
if (diff == 0)
{
return 0;
}
if (diff > 0)
{
if (diff > Int32.MaxValue)
{
return Int32.MaxValue;
}
else
{
return (Int32)diff;
}
}
else
{
if (diff < Int32.MinValue)
{
return Int32.MinValue;
}
else
{
return (Int32)diff;
}
}
}
internal static IPv4Address FromAddress(IPv4Address address)
{
return new IPv4Address(new Byte[] {
address._addressBytes[0],
address._addressBytes[1],
address._addressBytes[2],
address._addressBytes[3]});
}
public override Boolean IsBetween(IPv4Address start, IPv4Address end)
{
UInt32 ownValue = GetNumericValue();
UInt32 startValue = start.GetNumericValue();
UInt32 endValue = end.GetNumericValue();
return ownValue >= startValue && ownValue <= endValue;
}
public override Boolean IsGreaterThan(IPv4Address other) => this > other;
#region Operators
public static bool operator ==(IPv4Address addr1, IPv4Address addr2) => Equals(addr1, addr2);
public static bool operator !=(IPv4Address addr1, IPv4Address addr2) => !Equals(addr1, addr2);
public static Int64 operator -(IPv4Address addr1, IPv4Address addr2)
{
return (Int64)addr1.GetNumericValue() - (Int64)addr2.GetNumericValue();
}
public static bool operator <(IPv4Address addr1, IPv4Address addr2)
{
UInt32 addr1Value = addr1.GetNumericValue();
UInt32 addr2Value = addr2.GetNumericValue();
return addr1Value < addr2Value;
}
public static bool operator <=(IPv4Address addr1, IPv4Address addr2)
{
UInt32 addr1Value = addr1.GetNumericValue();
UInt32 addr2Value = addr2.GetNumericValue();
return addr1Value <= addr2Value;
}
public static bool operator >=(IPv4Address addr1, IPv4Address addr2)
{
UInt32 addr1Value = addr1.GetNumericValue();
UInt32 addr2Value = addr2.GetNumericValue();
return addr1Value >= addr2Value;
}
public static bool operator >(IPv4Address addr1, IPv4Address addr2)
{
UInt32 addr1Value = addr1.GetNumericValue();
UInt32 addr2Value = addr2.GetNumericValue();
return addr1Value > addr2Value;
}
public static IPv4Address operator +(IPv4Address addr, Int32 value)
{
UInt32 ownvalue = addr.GetNumericValue();
if (value > ownvalue)
{
throw new InvalidOperationException();
}
UInt32 newValue = ownvalue + (UInt32)value;
return new IPv4Address(newValue);
}
public static IPv4Address operator -(IPv4Address addr, Int32 value)
{
return addr + (-value);
}
#endregion
#endregion
}
}
| 29.057823 | 122 | 0.508838 | [
"MIT"
] | just-the-benno/Beer | src/DaAPI/Service/Beer.DaAPI.Service.Core/Common/DHCPv4/IPv4Address.cs | 8,545 | C# |
// Copyright (c) 2019 Alachisoft
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License
using System;
using Alachisoft.NCache.ServiceControl;
using Alachisoft.NCache.Management.RPC;
namespace Alachisoft.NCache.Management.Management
{
class CacheRPCService: CacheService
{
public CacheRPCService(String address): base(address, true) { }
public CacheRPCService(String address, int port): base(address, port, true) { }
public override ICacheServer GetCacheServer(TimeSpan timeout)
{
RemoteCacheServer cacheServer = new RemoteCacheServer(ServerName, (int)Port);
cacheServer.Initialize(null);
return cacheServer;
}
}
}
| 36.058824 | 89 | 0.707993 | [
"Apache-2.0"
] | delsoft/NCache | Src/NCManagement/Management/CacheRPCService.cs | 1,228 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using CustomerAPI.Models;
namespace CustomerAPI.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class CustomersController : ControllerBase
{
private readonly CustomerAPIContext _context;
public CustomersController(CustomerAPIContext context)
{
_context = context;
}
// GET: api/Customers
[HttpGet]
public async Task<ActionResult<IEnumerable<Customer>>> GetCustomer()
{
return await _context.Customer.ToListAsync();
}
// GET: api/Customers/5
[HttpGet("{id}")]
public async Task<ActionResult<Customer>> GetCustomer(int id)
{
var customer = await _context.Customer.FindAsync(id);
if (customer == null)
{
return NotFound();
}
return customer;
}
// PUT: api/Customers/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://aka.ms/RazorPagesCRUD.
[HttpPut("{id}")]
public async Task<IActionResult> PutCustomer(int id, Customer customer)
{
if (id != customer.Id)
{
return BadRequest();
}
_context.Entry(customer).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!CustomerExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
// POST: api/Customers
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://aka.ms/RazorPagesCRUD.
[HttpPost]
public async Task<ActionResult<Customer>> PostCustomer(Customer customer)
{
_context.Customer.Add(customer);
await _context.SaveChangesAsync();
return CreatedAtAction("GetCustomer", new { id = customer.Id }, customer);
}
// DELETE: api/Customers/5
[HttpDelete("{id}")]
public async Task<ActionResult<Customer>> DeleteCustomer(int id)
{
var customer = await _context.Customer.FindAsync(id);
if (customer == null)
{
return NotFound();
}
_context.Customer.Remove(customer);
await _context.SaveChangesAsync();
return customer;
}
private bool CustomerExists(int id)
{
return _context.Customer.Any(e => e.Id == id);
}
}
}
| 27.972727 | 110 | 0.548911 | [
"MIT"
] | tomfrenzel/CustomerAPI-backend | CustomerAPI/Controllers/CustomersController.cs | 3,079 | C# |
using System;
namespace Geodex.Curves.Cyclic
{
public class Hypotrochoid : Curve
{
#region members
public double A = 5.0;
public double B = 2.0;
#endregion
#region constructors
public Hypotrochoid() : base()
{
}
public Hypotrochoid(double t) : base()
{
this.T = t;
}
public Hypotrochoid(double t, double a, double b) : base()
{
this.A = a;
this.B = b;
this.T = t;
}
#endregion
#region methods
protected override void Evaluate()
{
double s = t * Math.PI;
double u = (A + B);
double v = u/ B;
p.X = u * Math.Cos(s) + B * Math.Cos(v * s);
p.Y = u * Math.Sin(s) - B * Math.Sin(v * s);
}
#endregion
}
}
| 16.309091 | 66 | 0.432553 | [
"MIT"
] | interopxyz/GeoDex | Geodex/Curves/Cyclic/Hypotrochoid.cs | 899 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("GameLogic")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("GameLogic")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("293af738-598e-4f67-8210-2566d744f6f8")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.594595 | 84 | 0.744069 | [
"MIT"
] | marindraganov/BoardGameWithoutName | BoardGameWithoutName/GameLogic/Properties/AssemblyInfo.cs | 1,394 | C# |
// *****************************************************************************
// BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE)
// © Component Factory Pty Ltd, 2006 - 2016, All rights reserved.
// The software and associated documentation supplied hereunder are the
// proprietary information of Component Factory Pty Ltd, 13 Swallows Close,
// Mornington, Vic 3931, Australia and are supplied subject to license terms.
//
// Modifications by Peter Wagner(aka Wagnerp) & Simon Coghlan(aka Smurf-IV) 2017 - 2020. All rights reserved. (https://github.com/Wagnerp/Krypton-NET-5.462)
// Version 5.462.0.0 www.ComponentFactory.com
// *****************************************************************************
using ComponentFactory.Krypton.Toolkit;
namespace ComponentFactory.Krypton.Navigator
{
/// <summary>
/// Implements the NavigatorMode.BarRibbonTabOnly mode.
/// </summary>
internal class ViewBuilderBarRibbonTabOnly : ViewBuilderBarRibbonTabBase
{
#region Public
/// <summary>
/// Gets a value indicating if the mode is a tab strip style mode.
/// </summary>
public override bool IsTabStripMode => true;
/// <summary>
/// User has used the keyboard to select the currently selected page.
/// </summary>
public override void KeyPressedPageView()
{
// If there is a currently selected page
if (Navigator.SelectedPage != null)
{
// Grab the view for the page
INavCheckItem checkItem = _pageLookup[Navigator.SelectedPage];
// If the item also has the focus
if (checkItem.HasFocus)
{
// Then perform the click action for the button
checkItem.PerformClick();
}
}
}
#endregion
#region Protected
/// <summary>
/// Create the view hierarchy for this view mode.
/// </summary>
protected override void CreateCheckItemView()
{
// Create the view element that lays out the check buttons
_layoutBar = new ViewLayoutBar(Navigator.StateCommon.Bar,
PaletteMetricInt.RibbonTabGap,
Navigator.Bar.ItemSizing,
Navigator.Bar.ItemAlignment,
Navigator.Bar.BarMultiline,
Navigator.Bar.ItemMinimumSize,
Navigator.Bar.ItemMaximumSize,
Navigator.Bar.BarMinimumHeight,
Navigator.Bar.TabBorderStyle,
true);
// Create the scroll spacer that restricts display
_layoutBarViewport = new ViewLayoutViewport(Navigator.StateCommon.Bar,
PaletteMetricPadding.BarPaddingTabs,
PaletteMetricInt.RibbonTabGap,
Navigator.Bar.BarOrientation,
Navigator.Bar.ItemAlignment,
Navigator.Bar.BarAnimation)
{
_layoutBar
};
// Create the button bar area docker
_layoutBarDocker = new ViewLayoutDocker
{
{ _layoutBarViewport, ViewDockStyle.Fill }
};
// Add a separators for insetting items
_layoutBarSeparatorFirst = new ViewLayoutSeparator(0);
_layoutBarSeparatorLast = new ViewLayoutSeparator(0);
_layoutBarDocker.Add(_layoutBarSeparatorFirst, ViewDockStyle.Left);
_layoutBarDocker.Add(_layoutBarSeparatorLast, ViewDockStyle.Right);
// Create the docker used to layout contents of main panel and fill with group
_layoutPanelDocker = new ViewLayoutDocker
{
{ _layoutBarDocker, ViewDockStyle.Fill },
{ new ViewLayoutPageHide(Navigator), ViewDockStyle.Top }
};
// Create the top level panel and put a layout docker inside it
_drawPanel = new ViewDrawPanel(Navigator.StateNormal.Back)
{
_layoutPanelDocker
};
_newRoot = _drawPanel;
// Must call the base class to perform common actions
base.CreateCheckItemView();
}
#endregion
}
}
| 43.770642 | 157 | 0.525047 | [
"BSD-3-Clause"
] | Krypton-Suite-Legacy/Krypton-NET-5.462 | Source/Krypton Components/ComponentFactory.Krypton.Navigator/View Builder/ViewBuilderBarRibbonTabOnly.cs | 4,774 | C# |
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 LMS
{
public partial class splashScreen : Form
{
public splashScreen()
{
InitializeComponent();
timer1.Start();
}
private void Timer1_Tick(object sender, EventArgs e)
{
panel2.Width += 15;
if (panel2.Width >= 804)
{
timer1.Stop();
frmLogin frm = new frmLogin();
frm.Show();
this.Hide();
}
}
}
}
| 20.542857 | 60 | 0.54242 | [
"MIT"
] | heyclarisse/DBMS-Proj | LMS/LMS/splashScreen.cs | 721 | C# |
using System.Drawing.Drawing2D;
using Microsoft.VisualStudio.Modeling.Diagrams;
namespace NuPattern.Runtime.Schema
{
/// <summary>
/// A custom geometric shape, based upon the rounded rectangle that replaces the bottom corners with squared corners.
/// </summary>
internal class SquaredBottomShapeGeometry : GlowShadowRoundedRectangleShapeGeometry
{
/// <summary>
/// Gets the minimum allowable size of the shape.
/// </summary>
public override SizeD MinimumGeometrySize
{
get
{
double width = (2 * this.Radius);
double height = (2 * this.Radius);
return new SizeD(width, height);
}
}
/// <summary>
/// Gets the suggested connection points of this geometry.
/// </summary>
/// <value></value>
public override PointD[] GetGeometryConnectionPoints(IGeometryHost geometryHost)
{
return null;
}
/// <summary>
/// Returns the path of the shape.
/// </summary>
protected override GraphicsPath GetPath(RectangleD boundingBox)
{
GraphicsPath basePath = base.GetPath(boundingBox);
double radius = this.Radius;
// Ensure work to do.
if (radius <= (double)0)
{
return basePath;
}
// Starting at top left and going clockwise.
basePath.Reset();
basePath.StartFigure();
// Top Left corner arc
this.DrawRadiusedArc(basePath, boundingBox.Left, boundingBox.Top, 180f, 90f);
// Top side line
this.DrawLine(basePath, (boundingBox.Left + radius), boundingBox.Top,
(boundingBox.Right - radius), boundingBox.Top);
// Top Right corner arc
this.DrawRadiusedArc(basePath, boundingBox.Right - (2 * radius), boundingBox.Top, 270f, 90f);
// Right side line
this.DrawLine(basePath, boundingBox.Right, (boundingBox.Top + radius),
boundingBox.Right, boundingBox.Bottom);
// Bottom side line
this.DrawLine(basePath, boundingBox.Right, boundingBox.Bottom,
boundingBox.Left, boundingBox.Bottom);
// Left side line
this.DrawLine(basePath, boundingBox.Left, boundingBox.Bottom,
boundingBox.Left, (boundingBox.Top + radius));
basePath.CloseFigure();
return basePath;
}
}
}
| 33.620253 | 122 | 0.55384 | [
"Apache-2.0"
] | dbremner/nupattern | Src/Runtime/Source/Runtime.Schema/Diagram/Geometrics/SquaredBottomShapeGeometry.cs | 2,658 | C# |
using System;
using System.Net.Http;
namespace Avapi
{
public class AvapiConnection : IAvapiConnection
{
private const string m_avapiUrlDefault = "https://www.alphavantage.co";
private string m_avapiUrl;
private HttpClient m_restClient;
private static readonly Lazy<AvapiConnection> s_avapiConnection =
new Lazy<AvapiConnection>(() => new AvapiConnection());
public static AvapiConnection Instance
{
get
{
return s_avapiConnection.Value;
}
}
private AvapiConnection()
{
}
public string AvapiUrl
{
get
{
if (!string.IsNullOrEmpty(m_avapiUrl))
{
return m_avapiUrl;
}
return m_avapiUrlDefault;
}
set
{
m_avapiUrl = value;
}
}
public string AvapiUrlDefault
{
get
{
return m_avapiUrlDefault;
}
}
public string ApiKey
{
get;
set;
}
public void Connect(string apiKey)
{
m_restClient = new HttpClient();
ApiKey = apiKey;
}
public AvapiTIME_SERIES_INTRADAY.Int_TIME_SERIES_INTRADAY GetQueryObject_TIME_SERIES_INTRADAY()
{
AvapiTIME_SERIES_INTRADAY.Impl_TIME_SERIES_INTRADAY.ApiKey = ApiKey;
AvapiTIME_SERIES_INTRADAY.Impl_TIME_SERIES_INTRADAY.AvapiUrl = AvapiUrl;
AvapiTIME_SERIES_INTRADAY.Impl_TIME_SERIES_INTRADAY.RestClient = m_restClient;
return AvapiTIME_SERIES_INTRADAY.Impl_TIME_SERIES_INTRADAY.Instance;
}
public AvapiTIME_SERIES_DAILY.Int_TIME_SERIES_DAILY GetQueryObject_TIME_SERIES_DAILY()
{
AvapiTIME_SERIES_DAILY.Impl_TIME_SERIES_DAILY.ApiKey = ApiKey;
AvapiTIME_SERIES_DAILY.Impl_TIME_SERIES_DAILY.AvapiUrl = AvapiUrl;
AvapiTIME_SERIES_DAILY.Impl_TIME_SERIES_DAILY.RestClient = m_restClient;
return AvapiTIME_SERIES_DAILY.Impl_TIME_SERIES_DAILY.Instance;
}
public AvapiTIME_SERIES_DAILY_ADJUSTED.Int_TIME_SERIES_DAILY_ADJUSTED GetQueryObject_TIME_SERIES_DAILY_ADJUSTED()
{
AvapiTIME_SERIES_DAILY_ADJUSTED.Impl_TIME_SERIES_DAILY_ADJUSTED.ApiKey = ApiKey;
AvapiTIME_SERIES_DAILY_ADJUSTED.Impl_TIME_SERIES_DAILY_ADJUSTED.AvapiUrl = AvapiUrl;
AvapiTIME_SERIES_DAILY_ADJUSTED.Impl_TIME_SERIES_DAILY_ADJUSTED.RestClient = m_restClient;
return AvapiTIME_SERIES_DAILY_ADJUSTED.Impl_TIME_SERIES_DAILY_ADJUSTED.Instance;
}
public AvapiTIME_SERIES_WEEKLY.Int_TIME_SERIES_WEEKLY GetQueryObject_TIME_SERIES_WEEKLY()
{
AvapiTIME_SERIES_WEEKLY.Impl_TIME_SERIES_WEEKLY.ApiKey = ApiKey;
AvapiTIME_SERIES_WEEKLY.Impl_TIME_SERIES_WEEKLY.AvapiUrl = AvapiUrl;
AvapiTIME_SERIES_WEEKLY.Impl_TIME_SERIES_WEEKLY.RestClient = m_restClient;
return AvapiTIME_SERIES_WEEKLY.Impl_TIME_SERIES_WEEKLY.Instance;
}
public AvapiTIME_SERIES_WEEKLY_ADJUSTED.Int_TIME_SERIES_WEEKLY_ADJUSTED GetQueryObject_TIME_SERIES_WEEKLY_ADJUSTED()
{
AvapiTIME_SERIES_WEEKLY_ADJUSTED.Impl_TIME_SERIES_WEEKLY_ADJUSTED.ApiKey = ApiKey;
AvapiTIME_SERIES_WEEKLY_ADJUSTED.Impl_TIME_SERIES_WEEKLY_ADJUSTED.AvapiUrl = AvapiUrl;
AvapiTIME_SERIES_WEEKLY_ADJUSTED.Impl_TIME_SERIES_WEEKLY_ADJUSTED.RestClient = m_restClient;
return AvapiTIME_SERIES_WEEKLY_ADJUSTED.Impl_TIME_SERIES_WEEKLY_ADJUSTED.Instance;
}
public AvapiTIME_SERIES_MONTHLY.Int_TIME_SERIES_MONTHLY GetQueryObject_TIME_SERIES_MONTHLY()
{
AvapiTIME_SERIES_MONTHLY.Impl_TIME_SERIES_MONTHLY.ApiKey = ApiKey;
AvapiTIME_SERIES_MONTHLY.Impl_TIME_SERIES_MONTHLY.AvapiUrl = AvapiUrl;
AvapiTIME_SERIES_MONTHLY.Impl_TIME_SERIES_MONTHLY.RestClient = m_restClient;
return AvapiTIME_SERIES_MONTHLY.Impl_TIME_SERIES_MONTHLY.Instance;
}
public AvapiBATCH_STOCK_QUOTES.Int_BATCH_STOCK_QUOTES GetQueryObject_BATCH_STOCK_QUOTES()
{
AvapiBATCH_STOCK_QUOTES.Impl_BATCH_STOCK_QUOTES.ApiKey = ApiKey;
AvapiBATCH_STOCK_QUOTES.Impl_BATCH_STOCK_QUOTES.AvapiUrl = AvapiUrl;
AvapiBATCH_STOCK_QUOTES.Impl_BATCH_STOCK_QUOTES.RestClient = m_restClient;
return AvapiBATCH_STOCK_QUOTES.Impl_BATCH_STOCK_QUOTES.Instance;
}
public AvapiTIME_SERIES_MONTHLY_ADJUSTED.Int_TIME_SERIES_MONTHLY_ADJUSTED GetQueryObject_TIME_SERIES_MONTHLY_ADJUSTED()
{
AvapiTIME_SERIES_MONTHLY_ADJUSTED.Impl_TIME_SERIES_MONTHLY_ADJUSTED.ApiKey = ApiKey;
AvapiTIME_SERIES_MONTHLY_ADJUSTED.Impl_TIME_SERIES_MONTHLY_ADJUSTED.AvapiUrl = AvapiUrl;
AvapiTIME_SERIES_MONTHLY_ADJUSTED.Impl_TIME_SERIES_MONTHLY_ADJUSTED.RestClient = m_restClient;
return AvapiTIME_SERIES_MONTHLY_ADJUSTED.Impl_TIME_SERIES_MONTHLY_ADJUSTED.Instance;
}
public AvapiSMA.Int_SMA GetQueryObject_SMA()
{
AvapiSMA.Impl_SMA.ApiKey = ApiKey;
AvapiSMA.Impl_SMA.AvapiUrl = AvapiUrl;
AvapiSMA.Impl_SMA.RestClient = m_restClient;
return AvapiSMA.Impl_SMA.Instance;
}
public AvapiEMA.Int_EMA GetQueryObject_EMA()
{
AvapiEMA.Impl_EMA.ApiKey = ApiKey;
AvapiEMA.Impl_EMA.AvapiUrl = AvapiUrl;
AvapiEMA.Impl_EMA.RestClient = m_restClient;
return AvapiEMA.Impl_EMA.Instance;
}
public AvapiWMA.Int_WMA GetQueryObject_WMA()
{
AvapiWMA.Impl_WMA.ApiKey = ApiKey;
AvapiWMA.Impl_WMA.AvapiUrl = AvapiUrl;
AvapiWMA.Impl_WMA.RestClient = m_restClient;
return AvapiWMA.Impl_WMA.Instance;
}
public AvapiDEMA.Int_DEMA GetQueryObject_DEMA()
{
AvapiDEMA.Impl_DEMA.ApiKey = ApiKey;
AvapiDEMA.Impl_DEMA.AvapiUrl = AvapiUrl;
AvapiDEMA.Impl_DEMA.RestClient = m_restClient;
return AvapiDEMA.Impl_DEMA.Instance;
}
public AvapiTEMA.Int_TEMA GetQueryObject_TEMA()
{
AvapiTEMA.Impl_TEMA.ApiKey = ApiKey;
AvapiTEMA.Impl_TEMA.AvapiUrl = AvapiUrl;
AvapiTEMA.Impl_TEMA.RestClient = m_restClient;
return AvapiTEMA.Impl_TEMA.Instance;
}
public AvapiTRIMA.Int_TRIMA GetQueryObject_TRIMA()
{
AvapiTRIMA.Impl_TRIMA.ApiKey = ApiKey;
AvapiTRIMA.Impl_TRIMA.AvapiUrl = AvapiUrl;
AvapiTRIMA.Impl_TRIMA.RestClient = m_restClient;
return AvapiTRIMA.Impl_TRIMA.Instance;
}
public AvapiKAMA.Int_KAMA GetQueryObject_KAMA()
{
AvapiKAMA.Impl_KAMA.ApiKey = ApiKey;
AvapiKAMA.Impl_KAMA.AvapiUrl = AvapiUrl;
AvapiKAMA.Impl_KAMA.RestClient = m_restClient;
return AvapiKAMA.Impl_KAMA.Instance;
}
public AvapiMAMA.Int_MAMA GetQueryObject_MAMA()
{
AvapiMAMA.Impl_MAMA.ApiKey = ApiKey;
AvapiMAMA.Impl_MAMA.AvapiUrl = AvapiUrl;
AvapiMAMA.Impl_MAMA.RestClient = m_restClient;
return AvapiMAMA.Impl_MAMA.Instance;
}
public AvapiT3.Int_T3 GetQueryObject_T3()
{
AvapiT3.Impl_T3.ApiKey = ApiKey;
AvapiT3.Impl_T3.AvapiUrl = AvapiUrl;
AvapiT3.Impl_T3.RestClient = m_restClient;
return AvapiT3.Impl_T3.Instance;
}
public AvapiMACD.Int_MACD GetQueryObject_MACD()
{
AvapiMACD.Impl_MACD.ApiKey = ApiKey;
AvapiMACD.Impl_MACD.AvapiUrl = AvapiUrl;
AvapiMACD.Impl_MACD.RestClient = m_restClient;
return AvapiMACD.Impl_MACD.Instance;
}
public AvapiMACDEXT.Int_MACDEXT GetQueryObject_MACDEXT()
{
AvapiMACDEXT.Impl_MACDEXT.ApiKey = ApiKey;
AvapiMACDEXT.Impl_MACDEXT.AvapiUrl = AvapiUrl;
AvapiMACDEXT.Impl_MACDEXT.RestClient = m_restClient;
return AvapiMACDEXT.Impl_MACDEXT.Instance;
}
public AvapiSTOCH.Int_STOCH GetQueryObject_STOCH()
{
AvapiSTOCH.Impl_STOCH.ApiKey = ApiKey;
AvapiSTOCH.Impl_STOCH.AvapiUrl = AvapiUrl;
AvapiSTOCH.Impl_STOCH.RestClient = m_restClient;
return AvapiSTOCH.Impl_STOCH.Instance;
}
public AvapiSTOCHF.Int_STOCHF GetQueryObject_STOCHF()
{
AvapiSTOCHF.Impl_STOCHF.ApiKey = ApiKey;
AvapiSTOCHF.Impl_STOCHF.AvapiUrl = AvapiUrl;
AvapiSTOCHF.Impl_STOCHF.RestClient = m_restClient;
return AvapiSTOCHF.Impl_STOCHF.Instance;
}
public AvapiRSI.Int_RSI GetQueryObject_RSI()
{
AvapiRSI.Impl_RSI.ApiKey = ApiKey;
AvapiRSI.Impl_RSI.AvapiUrl = AvapiUrl;
AvapiRSI.Impl_RSI.RestClient = m_restClient;
return AvapiRSI.Impl_RSI.Instance;
}
public AvapiSTOCHRSI.Int_STOCHRSI GetQueryObject_STOCHRSI()
{
AvapiSTOCHRSI.Impl_STOCHRSI.ApiKey = ApiKey;
AvapiSTOCHRSI.Impl_STOCHRSI.AvapiUrl = AvapiUrl;
AvapiSTOCHRSI.Impl_STOCHRSI.RestClient = m_restClient;
return AvapiSTOCHRSI.Impl_STOCHRSI.Instance;
}
public AvapiWILLR.Int_WILLR GetQueryObject_WILLR()
{
AvapiWILLR.Impl_WILLR.ApiKey = ApiKey;
AvapiWILLR.Impl_WILLR.AvapiUrl = AvapiUrl;
AvapiWILLR.Impl_WILLR.RestClient = m_restClient;
return AvapiWILLR.Impl_WILLR.Instance;
}
public AvapiADX.Int_ADX GetQueryObject_ADX()
{
AvapiADX.Impl_ADX.ApiKey = ApiKey;
AvapiADX.Impl_ADX.AvapiUrl = AvapiUrl;
AvapiADX.Impl_ADX.RestClient = m_restClient;
return AvapiADX.Impl_ADX.Instance;
}
public AvapiADXR.Int_ADXR GetQueryObject_ADXR()
{
AvapiADXR.Impl_ADXR.ApiKey = ApiKey;
AvapiADXR.Impl_ADXR.AvapiUrl = AvapiUrl;
AvapiADXR.Impl_ADXR.RestClient = m_restClient;
return AvapiADXR.Impl_ADXR.Instance;
}
public AvapiAPO.Int_APO GetQueryObject_APO()
{
AvapiAPO.Impl_APO.ApiKey = ApiKey;
AvapiAPO.Impl_APO.AvapiUrl = AvapiUrl;
AvapiAPO.Impl_APO.RestClient = m_restClient;
return AvapiAPO.Impl_APO.Instance;
}
public AvapiPPO.Int_PPO GetQueryObject_PPO()
{
AvapiPPO.Impl_PPO.ApiKey = ApiKey;
AvapiPPO.Impl_PPO.AvapiUrl = AvapiUrl;
AvapiPPO.Impl_PPO.RestClient = m_restClient;
return AvapiPPO.Impl_PPO.Instance;
}
public AvapiMOM.Int_MOM GetQueryObject_MOM()
{
AvapiMOM.Impl_MOM.ApiKey = ApiKey;
AvapiMOM.Impl_MOM.AvapiUrl = AvapiUrl;
AvapiMOM.Impl_MOM.RestClient = m_restClient;
return AvapiMOM.Impl_MOM.Instance;
}
public AvapiBOP.Int_BOP GetQueryObject_BOP()
{
AvapiBOP.Impl_BOP.ApiKey = ApiKey;
AvapiBOP.Impl_BOP.AvapiUrl = AvapiUrl;
AvapiBOP.Impl_BOP.RestClient = m_restClient;
return AvapiBOP.Impl_BOP.Instance;
}
public AvapiCCI.Int_CCI GetQueryObject_CCI()
{
AvapiCCI.Impl_CCI.ApiKey = ApiKey;
AvapiCCI.Impl_CCI.AvapiUrl = AvapiUrl;
AvapiCCI.Impl_CCI.RestClient = m_restClient;
return AvapiCCI.Impl_CCI.Instance;
}
public AvapiCMO.Int_CMO GetQueryObject_CMO()
{
AvapiCMO.Impl_CMO.ApiKey = ApiKey;
AvapiCMO.Impl_CMO.AvapiUrl = AvapiUrl;
AvapiCMO.Impl_CMO.RestClient = m_restClient;
return AvapiCMO.Impl_CMO.Instance;
}
public AvapiROC.Int_ROC GetQueryObject_ROC()
{
AvapiROC.Impl_ROC.ApiKey = ApiKey;
AvapiROC.Impl_ROC.AvapiUrl = AvapiUrl;
AvapiROC.Impl_ROC.RestClient = m_restClient;
return AvapiROC.Impl_ROC.Instance;
}
public AvapiROCR.Int_ROCR GetQueryObject_ROCR()
{
AvapiROCR.Impl_ROCR.ApiKey = ApiKey;
AvapiROCR.Impl_ROCR.AvapiUrl = AvapiUrl;
AvapiROCR.Impl_ROCR.RestClient = m_restClient;
return AvapiROCR.Impl_ROCR.Instance;
}
public AvapiAROON.Int_AROON GetQueryObject_AROON()
{
AvapiAROON.Impl_AROON.ApiKey = ApiKey;
AvapiAROON.Impl_AROON.AvapiUrl = AvapiUrl;
AvapiAROON.Impl_AROON.RestClient = m_restClient;
return AvapiAROON.Impl_AROON.Instance;
}
public AvapiAROONOSC.Int_AROONOSC GetQueryObject_AROONOSC()
{
AvapiAROONOSC.Impl_AROONOSC.ApiKey = ApiKey;
AvapiAROONOSC.Impl_AROONOSC.AvapiUrl = AvapiUrl;
AvapiAROONOSC.Impl_AROONOSC.RestClient = m_restClient;
return AvapiAROONOSC.Impl_AROONOSC.Instance;
}
public AvapiMFI.Int_MFI GetQueryObject_MFI()
{
AvapiMFI.Impl_MFI.ApiKey = ApiKey;
AvapiMFI.Impl_MFI.AvapiUrl = AvapiUrl;
AvapiMFI.Impl_MFI.RestClient = m_restClient;
return AvapiMFI.Impl_MFI.Instance;
}
public AvapiTRIX.Int_TRIX GetQueryObject_TRIX()
{
AvapiTRIX.Impl_TRIX.ApiKey = ApiKey;
AvapiTRIX.Impl_TRIX.AvapiUrl = AvapiUrl;
AvapiTRIX.Impl_TRIX.RestClient = m_restClient;
return AvapiTRIX.Impl_TRIX.Instance;
}
public AvapiULTOSC.Int_ULTOSC GetQueryObject_ULTOSC()
{
AvapiULTOSC.Impl_ULTOSC.ApiKey = ApiKey;
AvapiULTOSC.Impl_ULTOSC.AvapiUrl = AvapiUrl;
AvapiULTOSC.Impl_ULTOSC.RestClient = m_restClient;
return AvapiULTOSC.Impl_ULTOSC.Instance;
}
public AvapiDX.Int_DX GetQueryObject_DX()
{
AvapiDX.Impl_DX.ApiKey = ApiKey;
AvapiDX.Impl_DX.AvapiUrl = AvapiUrl;
AvapiDX.Impl_DX.RestClient = m_restClient;
return AvapiDX.Impl_DX.Instance;
}
public AvapiMINUS_DI.Int_MINUS_DI GetQueryObject_MINUS_DI()
{
AvapiMINUS_DI.Impl_MINUS_DI.ApiKey = ApiKey;
AvapiMINUS_DI.Impl_MINUS_DI.AvapiUrl = AvapiUrl;
AvapiMINUS_DI.Impl_MINUS_DI.RestClient = m_restClient;
return AvapiMINUS_DI.Impl_MINUS_DI.Instance;
}
public AvapiPLUS_DI.Int_PLUS_DI GetQueryObject_PLUS_DI()
{
AvapiPLUS_DI.Impl_PLUS_DI.ApiKey = ApiKey;
AvapiPLUS_DI.Impl_PLUS_DI.AvapiUrl = AvapiUrl;
AvapiPLUS_DI.Impl_PLUS_DI.RestClient = m_restClient;
return AvapiPLUS_DI.Impl_PLUS_DI.Instance;
}
public AvapiMINUS_DM.Int_MINUS_DM GetQueryObject_MINUS_DM()
{
AvapiMINUS_DM.Impl_MINUS_DM.ApiKey = ApiKey;
AvapiMINUS_DM.Impl_MINUS_DM.AvapiUrl = AvapiUrl;
AvapiMINUS_DM.Impl_MINUS_DM.RestClient = m_restClient;
return AvapiMINUS_DM.Impl_MINUS_DM.Instance;
}
public AvapiPLUS_DM.Int_PLUS_DM GetQueryObject_PLUS_DM()
{
AvapiPLUS_DM.Impl_PLUS_DM.ApiKey = ApiKey;
AvapiPLUS_DM.Impl_PLUS_DM.AvapiUrl = AvapiUrl;
AvapiPLUS_DM.Impl_PLUS_DM.RestClient = m_restClient;
return AvapiPLUS_DM.Impl_PLUS_DM.Instance;
}
public AvapiBBANDS.Int_BBANDS GetQueryObject_BBANDS()
{
AvapiBBANDS.Impl_BBANDS.ApiKey = ApiKey;
AvapiBBANDS.Impl_BBANDS.AvapiUrl = AvapiUrl;
AvapiBBANDS.Impl_BBANDS.RestClient = m_restClient;
return AvapiBBANDS.Impl_BBANDS.Instance;
}
public AvapiMIDPOINT.Int_MIDPOINT GetQueryObject_MIDPOINT()
{
AvapiMIDPOINT.Impl_MIDPOINT.ApiKey = ApiKey;
AvapiMIDPOINT.Impl_MIDPOINT.AvapiUrl = AvapiUrl;
AvapiMIDPOINT.Impl_MIDPOINT.RestClient = m_restClient;
return AvapiMIDPOINT.Impl_MIDPOINT.Instance;
}
public AvapiMIDPRICE.Int_MIDPRICE GetQueryObject_MIDPRICE()
{
AvapiMIDPRICE.Impl_MIDPRICE.ApiKey = ApiKey;
AvapiMIDPRICE.Impl_MIDPRICE.AvapiUrl = AvapiUrl;
AvapiMIDPRICE.Impl_MIDPRICE.RestClient = m_restClient;
return AvapiMIDPRICE.Impl_MIDPRICE.Instance;
}
public AvapiSAR.Int_SAR GetQueryObject_SAR()
{
AvapiSAR.Impl_SAR.ApiKey = ApiKey;
AvapiSAR.Impl_SAR.AvapiUrl = AvapiUrl;
AvapiSAR.Impl_SAR.RestClient = m_restClient;
return AvapiSAR.Impl_SAR.Instance;
}
public AvapiTRANGE.Int_TRANGE GetQueryObject_TRANGE()
{
AvapiTRANGE.Impl_TRANGE.ApiKey = ApiKey;
AvapiTRANGE.Impl_TRANGE.AvapiUrl = AvapiUrl;
AvapiTRANGE.Impl_TRANGE.RestClient = m_restClient;
return AvapiTRANGE.Impl_TRANGE.Instance;
}
public AvapiATR.Int_ATR GetQueryObject_ATR()
{
AvapiATR.Impl_ATR.ApiKey = ApiKey;
AvapiATR.Impl_ATR.AvapiUrl = AvapiUrl;
AvapiATR.Impl_ATR.RestClient = m_restClient;
return AvapiATR.Impl_ATR.Instance;
}
public AvapiNATR.Int_NATR GetQueryObject_NATR()
{
AvapiNATR.Impl_NATR.ApiKey = ApiKey;
AvapiNATR.Impl_NATR.AvapiUrl = AvapiUrl;
AvapiNATR.Impl_NATR.RestClient = m_restClient;
return AvapiNATR.Impl_NATR.Instance;
}
public AvapiAD.Int_AD GetQueryObject_AD()
{
AvapiAD.Impl_AD.ApiKey = ApiKey;
AvapiAD.Impl_AD.AvapiUrl = AvapiUrl;
AvapiAD.Impl_AD.RestClient = m_restClient;
return AvapiAD.Impl_AD.Instance;
}
public AvapiADOSC.Int_ADOSC GetQueryObject_ADOSC()
{
AvapiADOSC.Impl_ADOSC.ApiKey = ApiKey;
AvapiADOSC.Impl_ADOSC.AvapiUrl = AvapiUrl;
AvapiADOSC.Impl_ADOSC.RestClient = m_restClient;
return AvapiADOSC.Impl_ADOSC.Instance;
}
public AvapiOBV.Int_OBV GetQueryObject_OBV()
{
AvapiOBV.Impl_OBV.ApiKey = ApiKey;
AvapiOBV.Impl_OBV.AvapiUrl = AvapiUrl;
AvapiOBV.Impl_OBV.RestClient = m_restClient;
return AvapiOBV.Impl_OBV.Instance;
}
public AvapiHT_TRENDLINE.Int_HT_TRENDLINE GetQueryObject_HT_TRENDLINE()
{
AvapiHT_TRENDLINE.Impl_HT_TRENDLINE.ApiKey = ApiKey;
AvapiHT_TRENDLINE.Impl_HT_TRENDLINE.AvapiUrl = AvapiUrl;
AvapiHT_TRENDLINE.Impl_HT_TRENDLINE.RestClient = m_restClient;
return AvapiHT_TRENDLINE.Impl_HT_TRENDLINE.Instance;
}
public AvapiHT_SINE.Int_HT_SINE GetQueryObject_HT_SINE()
{
AvapiHT_SINE.Impl_HT_SINE.ApiKey = ApiKey;
AvapiHT_SINE.Impl_HT_SINE.AvapiUrl = AvapiUrl;
AvapiHT_SINE.Impl_HT_SINE.RestClient = m_restClient;
return AvapiHT_SINE.Impl_HT_SINE.Instance;
}
public AvapiHT_TRENDMODE.Int_HT_TRENDMODE GetQueryObject_HT_TRENDMODE()
{
AvapiHT_TRENDMODE.Impl_HT_TRENDMODE.ApiKey = ApiKey;
AvapiHT_TRENDMODE.Impl_HT_TRENDMODE.AvapiUrl = AvapiUrl;
AvapiHT_TRENDMODE.Impl_HT_TRENDMODE.RestClient = m_restClient;
return AvapiHT_TRENDMODE.Impl_HT_TRENDMODE.Instance;
}
public AvapiHT_DCPERIOD.Int_HT_DCPERIOD GetQueryObject_HT_DCPERIOD()
{
AvapiHT_DCPERIOD.Impl_HT_DCPERIOD.ApiKey = ApiKey;
AvapiHT_DCPERIOD.Impl_HT_DCPERIOD.AvapiUrl = AvapiUrl;
AvapiHT_DCPERIOD.Impl_HT_DCPERIOD.RestClient = m_restClient;
return AvapiHT_DCPERIOD.Impl_HT_DCPERIOD.Instance;
}
public AvapiHT_DCPHASE.Int_HT_DCPHASE GetQueryObject_HT_DCPHASE()
{
AvapiHT_DCPHASE.Impl_HT_DCPHASE.ApiKey = ApiKey;
AvapiHT_DCPHASE.Impl_HT_DCPHASE.AvapiUrl = AvapiUrl;
AvapiHT_DCPHASE.Impl_HT_DCPHASE.RestClient = m_restClient;
return AvapiHT_DCPHASE.Impl_HT_DCPHASE.Instance;
}
public AvapiHT_PHASOR.Int_HT_PHASOR GetQueryObject_HT_PHASOR()
{
AvapiHT_PHASOR.Impl_HT_PHASOR.ApiKey = ApiKey;
AvapiHT_PHASOR.Impl_HT_PHASOR.AvapiUrl = AvapiUrl;
AvapiHT_PHASOR.Impl_HT_PHASOR.RestClient = m_restClient;
return AvapiHT_PHASOR.Impl_HT_PHASOR.Instance;
}
public AvapiSECTOR.Int_SECTOR GetQueryObject_SECTOR()
{
AvapiSECTOR.Impl_SECTOR.ApiKey = ApiKey;
AvapiSECTOR.Impl_SECTOR.AvapiUrl = AvapiUrl;
AvapiSECTOR.Impl_SECTOR.RestClient = m_restClient;
return AvapiSECTOR.Impl_SECTOR.Instance;
}
public AvapiCURRENCY_EXCHANGE_RATE.Int_CURRENCY_EXCHANGE_RATE GetQueryObject_CURRENCY_EXCHANGE_RATE()
{
AvapiCURRENCY_EXCHANGE_RATE.Impl_CURRENCY_EXCHANGE_RATE.ApiKey = ApiKey;
AvapiCURRENCY_EXCHANGE_RATE.Impl_CURRENCY_EXCHANGE_RATE.AvapiUrl = AvapiUrl;
AvapiCURRENCY_EXCHANGE_RATE.Impl_CURRENCY_EXCHANGE_RATE.RestClient = m_restClient;
return AvapiCURRENCY_EXCHANGE_RATE.Impl_CURRENCY_EXCHANGE_RATE.Instance;
}
public AvapiDIGITAL_CURRENCY_INTRADAY.Int_DIGITAL_CURRENCY_INTRADAY GetQueryObject_DIGITAL_CURRENCY_INTRADAY()
{
AvapiDIGITAL_CURRENCY_INTRADAY.Impl_DIGITAL_CURRENCY_INTRADAY.ApiKey = ApiKey;
AvapiDIGITAL_CURRENCY_INTRADAY.Impl_DIGITAL_CURRENCY_INTRADAY.AvapiUrl = AvapiUrl;
AvapiDIGITAL_CURRENCY_INTRADAY.Impl_DIGITAL_CURRENCY_INTRADAY.RestClient = m_restClient;
return AvapiDIGITAL_CURRENCY_INTRADAY.Impl_DIGITAL_CURRENCY_INTRADAY.Instance;
}
public AvapiDIGITAL_CURRENCY_DAILY.Int_DIGITAL_CURRENCY_DAILY GetQueryObject_DIGITAL_CURRENCY_DAILY()
{
AvapiDIGITAL_CURRENCY_DAILY.Impl_DIGITAL_CURRENCY_DAILY.ApiKey = ApiKey;
AvapiDIGITAL_CURRENCY_DAILY.Impl_DIGITAL_CURRENCY_DAILY.AvapiUrl = AvapiUrl;
AvapiDIGITAL_CURRENCY_DAILY.Impl_DIGITAL_CURRENCY_DAILY.RestClient = m_restClient;
return AvapiDIGITAL_CURRENCY_DAILY.Impl_DIGITAL_CURRENCY_DAILY.Instance;
}
public AvapiDIGITAL_CURRENCY_WEEKLY.Int_DIGITAL_CURRENCY_WEEKLY GetQueryObject_DIGITAL_CURRENCY_WEEKLY()
{
AvapiDIGITAL_CURRENCY_WEEKLY.Impl_DIGITAL_CURRENCY_WEEKLY.ApiKey = ApiKey;
AvapiDIGITAL_CURRENCY_WEEKLY.Impl_DIGITAL_CURRENCY_WEEKLY.AvapiUrl = AvapiUrl;
AvapiDIGITAL_CURRENCY_WEEKLY.Impl_DIGITAL_CURRENCY_WEEKLY.RestClient = m_restClient;
return AvapiDIGITAL_CURRENCY_WEEKLY.Impl_DIGITAL_CURRENCY_WEEKLY.Instance;
}
public AvapiDIGITAL_CURRENCY_MONTHLY.Int_DIGITAL_CURRENCY_MONTHLY GetQueryObject_DIGITAL_CURRENCY_MONTHLY()
{
AvapiDIGITAL_CURRENCY_MONTHLY.Impl_DIGITAL_CURRENCY_MONTHLY.ApiKey = ApiKey;
AvapiDIGITAL_CURRENCY_MONTHLY.Impl_DIGITAL_CURRENCY_MONTHLY.AvapiUrl = AvapiUrl;
AvapiDIGITAL_CURRENCY_MONTHLY.Impl_DIGITAL_CURRENCY_MONTHLY.RestClient = m_restClient;
return AvapiDIGITAL_CURRENCY_MONTHLY.Impl_DIGITAL_CURRENCY_MONTHLY.Instance;
}
}
}
| 37.766409 | 121 | 0.801564 | [
"MIT"
] | AvapiDotNet/Avapi | Avapi/AvapiConnection.cs | 19,563 | C# |
using EshopManager.Application.Configurations;
using EshopManager.Application.Interfaces.Services;
using EshopManager.Application.Requests.Mail;
using MailKit.Net.Smtp;
using MailKit.Security;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MimeKit;
using System.Threading.Tasks;
namespace EshopManager.Infrastructure.Shared.Services
{
public class SMTPMailService : IMailService
{
private readonly MailConfiguration _config;
private readonly ILogger<SMTPMailService> _logger;
public SMTPMailService(IOptions<MailConfiguration> config, ILogger<SMTPMailService> logger)
{
_config = config.Value;
_logger = logger;
}
public async Task SendAsync(MailRequest request)
{
try
{
var email = new MimeMessage
{
Sender = new MailboxAddress(_config.DisplayName, request.From ?? _config.From),
Subject = request.Subject,
Body = new BodyBuilder
{
HtmlBody = request.Body
}.ToMessageBody()
};
using var smtp = new SmtpClient();
await smtp.ConnectAsync(_config.Host, _config.Port, SecureSocketOptions.StartTls);
await smtp.AuthenticateAsync(_config.UserName, _config.Password);
await smtp.SendAsync(email);
await smtp.DisconnectAsync(true);
}
catch (System.Exception ex)
{
_logger.LogError(ex.Message, ex);
}
}
}
} | 34.142857 | 99 | 0.596533 | [
"MIT"
] | tarafdarmansour/EShopManager | src/Infrastructure.Shared/Services/SMTPMailService.cs | 1,675 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace HamroDokan.Models
{
public class Category
{
public int CategoryId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public List<Item> Items { get; set; }
}
} | 19.823529 | 47 | 0.635015 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | krazyyplayer/HamroDokan | HamroDokan/Models/Category.cs | 339 | C# |
using System;
namespace DotnetModelFuzzer.Fuzzer.Models
{
/// <summary>
/// Provides fuzzing for a provider key-value pair, based on a separated percentage chance
/// of fuzzing a key vs fuzzing a value.
/// </summary>
public class KeyValuePairModel<TValueModel, TValueStrategy, TValue> : Model<KeyValuePairStrategy<TValueStrategy>, Tuple<string, TValue>, string>
where TValueModel : Model<TValueStrategy, TValue, TValue>
where TValue : class, new()
where TValueStrategy : Strategy, new()
{
public KeyValuePairModel() : base() { }
public KeyValuePairModel(KeyValuePairStrategy<TValueStrategy> strat, int randomSeed)
: base(strat, randomSeed) { }
public TValueModel ValueModel { get; set; }
public override Tuple<string, TValue> Fuzz(Tuple<string, TValue> input = null)
{
string newKey = input?.Item1;
if (Random.RollPercentage(Strategy.Key.Probability))
{
newKey = DoFuzzingWork(LoadedManipulations, newKey);
}
TValue newValue = input?.Item2;
if (ValueModel != null)
newValue = ValueModel.Fuzz(newValue);
return new Tuple<string, TValue>(newKey, newValue);
}
}
}
| 35.081081 | 148 | 0.627889 | [
"MIT"
] | queen-of-code/DotnetModelFuzzing | ModelFuzzer/Fuzzer/Models/KeyValuePairModel.cs | 1,300 | C# |
#pragma warning disable 108 // new keyword hiding
#pragma warning disable 114 // new keyword hiding
namespace Windows.Networking.Sockets
{
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
#endif
public partial class MessageWebSocketMessageReceivedEventArgs
{
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public global::Windows.Networking.Sockets.SocketMessageType MessageType
{
get
{
throw new global::System.NotImplementedException("The member SocketMessageType MessageWebSocketMessageReceivedEventArgs.MessageType is not implemented in Uno.");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public bool IsMessageComplete
{
get
{
throw new global::System.NotImplementedException("The member bool MessageWebSocketMessageReceivedEventArgs.IsMessageComplete is not implemented in Uno.");
}
}
#endif
// Forced skipping of method Windows.Networking.Sockets.MessageWebSocketMessageReceivedEventArgs.MessageType.get
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public global::Windows.Storage.Streams.DataReader GetDataReader()
{
throw new global::System.NotImplementedException("The member DataReader MessageWebSocketMessageReceivedEventArgs.GetDataReader() is not implemented in Uno.");
}
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public global::Windows.Storage.Streams.IInputStream GetDataStream()
{
throw new global::System.NotImplementedException("The member IInputStream MessageWebSocketMessageReceivedEventArgs.GetDataStream() is not implemented in Uno.");
}
#endif
// Forced skipping of method Windows.Networking.Sockets.MessageWebSocketMessageReceivedEventArgs.IsMessageComplete.get
}
}
| 40.104167 | 165 | 0.771429 | [
"Apache-2.0"
] | AlexTrepanier/Uno | src/Uno.UWP/Generated/3.0.0.0/Windows.Networking.Sockets/MessageWebSocketMessageReceivedEventArgs.cs | 1,925 | C# |
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Data;
using System.Configuration;
using System.Data.SQLite;
namespace ZY.Framework.Data.Helper
{
/// <summary>
/// Copyright (C) 2011 Maticsoft
/// 数据访问基础类(基于SQLite)
/// 可以用户可以修改满足自己项目的需要。
/// </summary>
public abstract class DbHelperSQLite
{
//数据库连接字符串(web.config来配置),可以动态更改connectionString支持多数据库.
public static string connectionString = PubConstant.ConnectionString;
public DbHelperSQLite()
{
}
#region 公用方法
public static int GetMaxID(string FieldName, string TableName)
{
string strsql = "select max(" + FieldName + ")+1 from " + TableName;
object obj = GetSingle(strsql);
if (obj == null)
{
return 1;
}
else
{
return int.Parse(obj.ToString());
}
}
public static bool Exists(string strSql)
{
object obj = GetSingle(strSql);
int cmdresult;
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
cmdresult = 0;
}
else
{
cmdresult = int.Parse(obj.ToString());
}
if (cmdresult == 0)
{
return false;
}
else
{
return true;
}
}
public static bool Exists(string strSql, params SQLiteParameter[] cmdParms)
{
object obj = GetSingle(strSql, cmdParms);
int cmdresult;
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
cmdresult = 0;
}
else
{
cmdresult = int.Parse(obj.ToString());
}
if (cmdresult == 0)
{
return false;
}
else
{
return true;
}
}
#endregion
#region 执行简单SQL语句
/// <summary>
/// 执行SQL语句,返回影响的记录数
/// </summary>
/// <param name="SQLString">SQL语句</param>
/// <returns>影响的记录数</returns>
public static int ExecuteSql(string SQLString)
{
using (SQLiteConnection connection = new SQLiteConnection(connectionString))
{
using (SQLiteCommand cmd = new SQLiteCommand(SQLString, connection))
{
try
{
connection.Open();
int rows = cmd.ExecuteNonQuery();
return rows;
}
catch (System.Data.SQLite.SQLiteException E)
{
connection.Close();
throw new Exception(E.Message);
}
}
}
}
/// <summary>
/// 执行多条SQL语句,实现数据库事务。
/// </summary>
/// <param name="SQLStringList">多条SQL语句</param>
public static void ExecuteSqlTran(ArrayList SQLStringList)
{
using (SQLiteConnection conn = new SQLiteConnection(connectionString))
{
conn.Open();
SQLiteCommand cmd = new SQLiteCommand();
cmd.Connection = conn;
SQLiteTransaction tx = conn.BeginTransaction();
cmd.Transaction = tx;
try
{
for (int n = 0; n < SQLStringList.Count; n++)
{
string strsql = SQLStringList[n].ToString();
if (strsql.Trim().Length > 1)
{
cmd.CommandText = strsql;
cmd.ExecuteNonQuery();
}
}
tx.Commit();
}
catch (System.Data.SQLite.SQLiteException E)
{
tx.Rollback();
throw new Exception(E.Message);
}
}
}
/// <summary>
/// 执行带一个存储过程参数的的SQL语句。
/// </summary>
/// <param name="SQLString">SQL语句</param>
/// <param name="content">参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加</param>
/// <returns>影响的记录数</returns>
public static int ExecuteSql(string SQLString, string content)
{
using (SQLiteConnection connection = new SQLiteConnection(connectionString))
{
SQLiteCommand cmd = new SQLiteCommand(SQLString, connection);
SQLiteParameter myParameter = new SQLiteParameter("@content", DbType.String);
myParameter.Value = content;
cmd.Parameters.Add(myParameter);
try
{
connection.Open();
int rows = cmd.ExecuteNonQuery();
return rows;
}
catch (System.Data.SQLite.SQLiteException E)
{
throw new Exception(E.Message);
}
finally
{
cmd.Dispose();
connection.Close();
}
}
}
/// <summary>
/// 向数据库里插入图像格式的字段(和上面情况类似的另一种实例)
/// </summary>
/// <param name="strSQL">SQL语句</param>
/// <param name="fs">图像字节,数据库的字段类型为image的情况</param>
/// <returns>影响的记录数</returns>
public static int ExecuteSqlInsertImg(string strSQL, byte[] fs)
{
using (SQLiteConnection connection = new SQLiteConnection(connectionString))
{
SQLiteCommand cmd = new SQLiteCommand(strSQL, connection);
SQLiteParameter myParameter = new SQLiteParameter("@fs", DbType.Binary);
myParameter.Value = fs;
cmd.Parameters.Add(myParameter);
try
{
connection.Open();
int rows = cmd.ExecuteNonQuery();
return rows;
}
catch (System.Data.SQLite.SQLiteException E)
{
throw new Exception(E.Message);
}
finally
{
cmd.Dispose();
connection.Close();
}
}
}
/// <summary>
/// 执行一条计算查询结果语句,返回查询结果(object)。
/// </summary>
/// <param name="SQLString">计算查询结果语句</param>
/// <returns>查询结果(object)</returns>
public static object GetSingle(string SQLString)
{
using (SQLiteConnection connection = new SQLiteConnection(connectionString))
{
using (SQLiteCommand cmd = new SQLiteCommand(SQLString, connection))
{
try
{
connection.Open();
object obj = cmd.ExecuteScalar();
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
return null;
}
else
{
return obj;
}
}
catch (System.Data.SQLite.SQLiteException e)
{
connection.Close();
throw new Exception(e.Message);
}
}
}
}
/// <summary>
/// 执行查询语句,返回SQLiteDataReader
/// </summary>
/// <param name="strSQL">查询语句</param>
/// <returns>SQLiteDataReader</returns>
public static SQLiteDataReader ExecuteReader(string strSQL)
{
SQLiteConnection connection = new SQLiteConnection(connectionString);
SQLiteCommand cmd = new SQLiteCommand(strSQL, connection);
try
{
connection.Open();
SQLiteDataReader myReader = cmd.ExecuteReader();
return myReader;
}
catch (System.Data.SQLite.SQLiteException e)
{
throw new Exception(e.Message);
}
}
/// <summary>
/// 执行查询语句,返回DataSet
/// </summary>
/// <param name="SQLString">查询语句</param>
/// <returns>DataSet</returns>
public static DataSet Query(string SQLString)
{
using (SQLiteConnection connection = new SQLiteConnection(connectionString))
{
DataSet ds = new DataSet();
try
{
connection.Open();
SQLiteDataAdapter command = new SQLiteDataAdapter(SQLString, connection);
command.Fill(ds, "ds");
}
catch (System.Data.SQLite.SQLiteException ex)
{
throw new Exception(ex.Message);
}
return ds;
}
}
#endregion
#region 执行带参数的SQL语句
/// <summary>
/// 执行SQL语句,返回影响的记录数
/// </summary>
/// <param name="SQLString">SQL语句</param>
/// <returns>影响的记录数</returns>
public static int ExecuteSql(string SQLString, params SQLiteParameter[] cmdParms)
{
using (SQLiteConnection connection = new SQLiteConnection(connectionString))
{
using (SQLiteCommand cmd = new SQLiteCommand())
{
try
{
PrepareCommand(cmd, connection, null, SQLString, cmdParms);
int rows = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
return rows;
}
catch (System.Data.SQLite.SQLiteException E)
{
throw new Exception(E.Message);
}
}
}
}
/// <summary>
/// 执行多条SQL语句,实现数据库事务。
/// </summary>
/// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的SQLiteParameter[])</param>
public static void ExecuteSqlTran(Hashtable SQLStringList)
{
using (SQLiteConnection conn = new SQLiteConnection(connectionString))
{
conn.Open();
using (SQLiteTransaction trans = conn.BeginTransaction())
{
SQLiteCommand cmd = new SQLiteCommand();
try
{
//循环
foreach (DictionaryEntry myDE in SQLStringList)
{
string cmdText = myDE.Key.ToString();
SQLiteParameter[] cmdParms = (SQLiteParameter[])myDE.Value;
PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
int val = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
trans.Commit();
}
}
catch
{
trans.Rollback();
throw;
}
}
}
}
/// <summary>
/// 执行一条计算查询结果语句,返回查询结果(object)。
/// </summary>
/// <param name="SQLString">计算查询结果语句</param>
/// <returns>查询结果(object)</returns>
public static object GetSingle(string SQLString, params SQLiteParameter[] cmdParms)
{
using (SQLiteConnection connection = new SQLiteConnection(connectionString))
{
using (SQLiteCommand cmd = new SQLiteCommand())
{
try
{
PrepareCommand(cmd, connection, null, SQLString, cmdParms);
object obj = cmd.ExecuteScalar();
cmd.Parameters.Clear();
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
return null;
}
else
{
return obj;
}
}
catch (System.Data.SQLite.SQLiteException e)
{
throw new Exception(e.Message);
}
}
}
}
/// <summary>
/// 执行查询语句,返回SQLiteDataReader
/// </summary>
/// <param name="strSQL">查询语句</param>
/// <returns>SQLiteDataReader</returns>
public static SQLiteDataReader ExecuteReader(string SQLString, params SQLiteParameter[] cmdParms)
{
SQLiteConnection connection = new SQLiteConnection(connectionString);
SQLiteCommand cmd = new SQLiteCommand();
try
{
PrepareCommand(cmd, connection, null, SQLString, cmdParms);
SQLiteDataReader myReader = cmd.ExecuteReader();
cmd.Parameters.Clear();
return myReader;
}
catch (System.Data.SQLite.SQLiteException e)
{
throw new Exception(e.Message);
}
}
/// <summary>
/// 执行查询语句,返回DataSet
/// </summary>
/// <param name="SQLString">查询语句</param>
/// <returns>DataSet</returns>
public static DataSet Query(string SQLString, params SQLiteParameter[] cmdParms)
{
using (SQLiteConnection connection = new SQLiteConnection(connectionString))
{
SQLiteCommand cmd = new SQLiteCommand();
PrepareCommand(cmd, connection, null, SQLString, cmdParms);
using (SQLiteDataAdapter da = new SQLiteDataAdapter(cmd))
{
DataSet ds = new DataSet();
try
{
da.Fill(ds, "ds");
cmd.Parameters.Clear();
}
catch (System.Data.SQLite.SQLiteException ex)
{
throw new Exception(ex.Message);
}
return ds;
}
}
}
private static void PrepareCommand(SQLiteCommand cmd, SQLiteConnection conn, SQLiteTransaction trans, string cmdText, SQLiteParameter[] cmdParms)
{
if (conn.State != ConnectionState.Open)
conn.Open();
cmd.Connection = conn;
cmd.CommandText = cmdText;
if (trans != null)
cmd.Transaction = trans;
cmd.CommandType = CommandType.Text;//cmdType;
if (cmdParms != null)
{
foreach (SQLiteParameter parm in cmdParms)
cmd.Parameters.Add(parm);
}
}
#endregion
}
}
| 33.676087 | 153 | 0.447486 | [
"MIT"
] | lovepoco/ZYFW | Code/ZY.Framework.Data.Helper/DbHelperSQLite.cs | 16,289 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.Network.V20180201
{
/// <summary>
/// Express Route Circuit Connection in an ExpressRouteCircuitPeering resource.
/// </summary>
[AzureNextGenResourceType("azure-nextgen:network/v20180201:ExpressRouteCircuitConnection")]
public partial class ExpressRouteCircuitConnection : Pulumi.CustomResource
{
/// <summary>
/// /29 IP address space to carve out Customer addresses for tunnels.
/// </summary>
[Output("addressPrefix")]
public Output<string?> AddressPrefix { get; private set; } = null!;
/// <summary>
/// The authorization key.
/// </summary>
[Output("authorizationKey")]
public Output<string?> AuthorizationKey { get; private set; } = null!;
/// <summary>
/// Express Route Circuit Connection State. Possible values are: 'Connected' and 'Disconnected'.
/// </summary>
[Output("circuitConnectionStatus")]
public Output<string> CircuitConnectionStatus { get; private set; } = null!;
/// <summary>
/// A unique read-only string that changes whenever the resource is updated.
/// </summary>
[Output("etag")]
public Output<string> Etag { get; private set; } = null!;
/// <summary>
/// Reference to Express Route Circuit Private Peering Resource of the circuit initiating connection.
/// </summary>
[Output("expressRouteCircuitPeering")]
public Output<Outputs.SubResourceResponse?> ExpressRouteCircuitPeering { get; private set; } = null!;
/// <summary>
/// Gets name of the resource that is unique within a resource group. This name can be used to access the resource.
/// </summary>
[Output("name")]
public Output<string?> Name { get; private set; } = null!;
/// <summary>
/// Reference to Express Route Circuit Private Peering Resource of the peered circuit.
/// </summary>
[Output("peerExpressRouteCircuitPeering")]
public Output<Outputs.SubResourceResponse?> PeerExpressRouteCircuitPeering { get; private set; } = null!;
/// <summary>
/// Provisioning state of the circuit connection resource. Possible values are: 'Succeeded', 'Updating', 'Deleting', and 'Failed'.
/// </summary>
[Output("provisioningState")]
public Output<string> ProvisioningState { get; private set; } = null!;
/// <summary>
/// Create a ExpressRouteCircuitConnection resource with the given unique name, arguments, and options.
/// </summary>
///
/// <param name="name">The unique name of the resource</param>
/// <param name="args">The arguments used to populate this resource's properties</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public ExpressRouteCircuitConnection(string name, ExpressRouteCircuitConnectionArgs args, CustomResourceOptions? options = null)
: base("azure-nextgen:network/v20180201:ExpressRouteCircuitConnection", name, args ?? new ExpressRouteCircuitConnectionArgs(), MakeResourceOptions(options, ""))
{
}
private ExpressRouteCircuitConnection(string name, Input<string> id, CustomResourceOptions? options = null)
: base("azure-nextgen:network/v20180201:ExpressRouteCircuitConnection", name, null, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
Aliases =
{
new Pulumi.Alias { Type = "azure-nextgen:network:ExpressRouteCircuitConnection"},
new Pulumi.Alias { Type = "azure-nextgen:network/latest:ExpressRouteCircuitConnection"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20180401:ExpressRouteCircuitConnection"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20180601:ExpressRouteCircuitConnection"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20180701:ExpressRouteCircuitConnection"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20180801:ExpressRouteCircuitConnection"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20181001:ExpressRouteCircuitConnection"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20181101:ExpressRouteCircuitConnection"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20181201:ExpressRouteCircuitConnection"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190201:ExpressRouteCircuitConnection"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190401:ExpressRouteCircuitConnection"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190601:ExpressRouteCircuitConnection"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190701:ExpressRouteCircuitConnection"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190801:ExpressRouteCircuitConnection"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190901:ExpressRouteCircuitConnection"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20191101:ExpressRouteCircuitConnection"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20191201:ExpressRouteCircuitConnection"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200301:ExpressRouteCircuitConnection"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200401:ExpressRouteCircuitConnection"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200501:ExpressRouteCircuitConnection"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200601:ExpressRouteCircuitConnection"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200701:ExpressRouteCircuitConnection"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200801:ExpressRouteCircuitConnection"},
},
};
var merged = CustomResourceOptions.Merge(defaultOptions, options);
// Override the ID if one was specified for consistency with other language SDKs.
merged.Id = id ?? merged.Id;
return merged;
}
/// <summary>
/// Get an existing ExpressRouteCircuitConnection resource's state with the given name, ID, and optional extra
/// properties used to qualify the lookup.
/// </summary>
///
/// <param name="name">The unique name of the resulting resource.</param>
/// <param name="id">The unique provider ID of the resource to lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static ExpressRouteCircuitConnection Get(string name, Input<string> id, CustomResourceOptions? options = null)
{
return new ExpressRouteCircuitConnection(name, id, options);
}
}
public sealed class ExpressRouteCircuitConnectionArgs : Pulumi.ResourceArgs
{
/// <summary>
/// /29 IP address space to carve out Customer addresses for tunnels.
/// </summary>
[Input("addressPrefix")]
public Input<string>? AddressPrefix { get; set; }
/// <summary>
/// The authorization key.
/// </summary>
[Input("authorizationKey")]
public Input<string>? AuthorizationKey { get; set; }
/// <summary>
/// The name of the express route circuit.
/// </summary>
[Input("circuitName", required: true)]
public Input<string> CircuitName { get; set; } = null!;
/// <summary>
/// The name of the express route circuit connection.
/// </summary>
[Input("connectionName")]
public Input<string>? ConnectionName { get; set; }
/// <summary>
/// Reference to Express Route Circuit Private Peering Resource of the circuit initiating connection.
/// </summary>
[Input("expressRouteCircuitPeering")]
public Input<Inputs.SubResourceArgs>? ExpressRouteCircuitPeering { get; set; }
/// <summary>
/// Resource ID.
/// </summary>
[Input("id")]
public Input<string>? Id { get; set; }
/// <summary>
/// Gets name of the resource that is unique within a resource group. This name can be used to access the resource.
/// </summary>
[Input("name")]
public Input<string>? Name { get; set; }
/// <summary>
/// Reference to Express Route Circuit Private Peering Resource of the peered circuit.
/// </summary>
[Input("peerExpressRouteCircuitPeering")]
public Input<Inputs.SubResourceArgs>? PeerExpressRouteCircuitPeering { get; set; }
/// <summary>
/// The name of the peering.
/// </summary>
[Input("peeringName", required: true)]
public Input<string> PeeringName { get; set; } = null!;
/// <summary>
/// The name of the resource group.
/// </summary>
[Input("resourceGroupName", required: true)]
public Input<string> ResourceGroupName { get; set; } = null!;
public ExpressRouteCircuitConnectionArgs()
{
}
}
}
| 49.420792 | 172 | 0.633477 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/Network/V20180201/ExpressRouteCircuitConnection.cs | 9,983 | C# |
using BusinessRules.POC.DerivedData.Interface;
using BusinessRules.POC.Extensions;
using BusinessRules.POC.Interfaces;
using DCT.ILR.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BusinessRules.POC.ULN
{
public class ULN_04Rule : IRule<MessageLearner>
{
private readonly IDD01 _dd01;
private readonly IValidationErrorHandler<MessageLearner> _validationErrorHandler;
public ULN_04Rule(IDD01 dd01, IValidationErrorHandler<MessageLearner> validationErrorHandler)
{
_dd01 = dd01;
_validationErrorHandler = validationErrorHandler;
}
public void Validate(MessageLearner objectToValidate)
{
if (ConditionMet(objectToValidate.ULN))
{
_validationErrorHandler.Handle(objectToValidate, "ULN_04");
}
}
public bool ConditionMet(long uln)
{
var dd_01 = _dd01.Derive(uln);
var ulnString = uln.ToString();
if (dd_01 == ValidationConstants.N || (dd_01 != ValidationConstants.Y && ulnString.Length >= 10 && dd_01 != ulnString.ElementAt(9).ToString()))
{
return true;
}
return false;
}
}
}
| 28.87234 | 155 | 0.624908 | [
"MIT"
] | SkillsFundingAgency/DC-Alpha-ValidationService-POC | src/DCT.ValidationService.POC/BusinessRules.POC/ULN/ULN_04Rule.cs | 1,359 | C# |
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Zen.Base.Extension;
using Zen.Base.Module;
using Zen.Storage.Provider.File;
namespace Zen.Storage.Model
{
public class ZenFileBaseDescriptor<T> : Data<T> where T : Data<T>
{
private readonly ZenFileDescriptorAttribute _attribute;
private readonly FileStoragePrimitive _provider;
public ZenFileBaseDescriptor()
{
_attribute = GetType()
.GetCustomAttributes(typeof(ZenFileDescriptorAttribute), false)
.Select(i => (ZenFileDescriptorAttribute) i)
.FirstOrDefault() ?? new ZenFileDescriptorAttribute();
_provider =
_attribute.StorageType == null ? Current.FileStorageProvider : _attribute.StorageType.CreateInstance<FileStoragePrimitive>();
}
public async Task<Stream> Fetch() { return await _provider.Fetch((IFileDescriptor) this); }
public async Task<string> Store(Stream source) { return await _provider.Store((IFileDescriptor) this, source); }
public async Task<bool> Exists() { return await _provider.Exists((IFileDescriptor) this); }
}
} | 40.633333 | 141 | 0.662018 | [
"MIT"
] | bucknellu/zen | Zen.Storage/Model/ZenFileBaseDescriptor.cs | 1,221 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("WindowsService")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("WindowsService")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("5d4f855b-74bf-43cc-9548-953233e0ea7d")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.864865 | 84 | 0.745896 | [
"MIT"
] | AdamHupa/Unified-Work-Solution-.net | WindowsService/Properties/AssemblyInfo.cs | 1,404 | C# |
using DisCatSharp.CommandsNext;
using DisCatSharp.CommandsNext.Attributes;
using DisCatSharp.Entities;
using DisCatSharp.Interactivity;
using DisCatSharp.Interactivity.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MeekPlush.Commands
{
[Group("util")]
class Util : BaseCommandModule
{
[Command("getroleid"),Aliases("rid")]
public async Task GetRoleID(CommandContext ctx, string name)
{
var inter = ctx.Client.GetInteractivity();
var roles = ctx.Guild.Roles.Values.Where(x => x.Name.Contains(name));
var emb = new DiscordEmbedBuilder();
int pi = 1;
List<Page> rL = new List<Page>();
var Grole = await ctx.Guild.GetAllMembersAsync();
if (roles.Count() == 1) {
var Mcount = Grole.Where(x => x.Roles.Any(y => y.Id == roles.First().Id)).Count();
emb.WithTitle(roles.First().Name);
emb.WithDescription($"ID: **{roles.First().Id}**\n" +
$"Mentionable: **{roles.First().IsMentionable}**\n" +
$"Position: **{roles.First().Position}**\n" +
$"Member Count: **{Mcount}**\n" +
$"Color: **{roles.First().Color.Value}**");
emb.WithFooter($"Requested by {ctx.Member.DisplayName ?? ctx.Member.Username}", ctx.User.AvatarUrl);
rL.Add(new Page {
Embed = emb.Build()
});
await ctx.RespondAsync(embed: rL.First().Embed);
return;
} else {
foreach (var r in roles) {
var Mcount = Grole.Where(x => x.Roles.Any(y => y.Id == r.Id)).Count();
emb.WithTitle(r.Name);
emb.WithDescription($"ID: **{r.Id}**\n" +
$"Mentionable: **{r.IsMentionable}**\n" +
$"Position: **{r.Position}**\n" +
$"Member Count: **{Mcount}**\n" +
$"Color: **{r.Color.Value}**");
emb.WithFooter($"Page {pi}/{roles.Count()} || Requested by {ctx.Member.DisplayName ?? ctx.Member.Username}", ctx.User.AvatarUrl);
rL.Add(new Page {
Embed = emb.Build()
});
pi++;
}
}
await inter.SendPaginatedMessageAsync(ctx.Channel, ctx.User, rL);
}
}
}
| 42.316667 | 149 | 0.504529 | [
"MIT"
] | Speyd3r/MeekPlushRW | MeekPlush/Commands/Util.cs | 2,541 | C# |
using System;
using System.Linq;
using System.Text.RegularExpressions;
using ReassureTest.AST;
using ReassureTest.AST.Expected;
namespace ReassureTest.Implementation
{
public class MatchExecutor
{
private readonly Configuration configuration;
public MatchExecutor(Configuration configuration)
{
this.configuration = configuration;
}
public void MatchGraph(IAssertEvaluator expected, IAstNode actual) => Match(expected, actual, "");
string AddPath(string path, string newLevel)
{
if (path == "")
return newLevel;
if (newLevel[0] == '[')
return path + newLevel;
return $"{path}.{newLevel}";
}
void Match(IAssertEvaluator expected, IAstNode actual, string path)
{
if (expected is AstDateTimeMatcher dateTime)
DateTimeMatch(dateTime, actual, path);
else if (expected is AstStringMatcher str)
StringMatch(str, actual, path);
else if (expected is AstGuidMatcher guid)
GuidMatch(guid, actual, path);
else if (expected is AstSimpleMatcher simple)
SimpleMatch(simple, actual, path);
else if (expected is AstComplexMatcher complex)
ComplexMatch(complex, actual, path);
else if (expected is AstArrayMatcher array)
ArrayMatch(array, actual, path);
else if (expected is AstAnyMatcher)
AnyMatch();
else if (expected is AstSomeMatcher)
SomeMatch(actual, path);
else
throw new AssertException($"Internal error. Do not understand '{expected.GetType()}' to be compared with '{actual}'. {PrintablePath(path)}");
}
private void SomeMatch(IAstNode actual, string path)
{
if (actual == AstSimpleValue.Null)
throw new AssertException($"{PrintablePath(path)}Expected: not null\r\nBut was: null");
}
private void AnyMatch()
{
// always true
}
void ArrayMatch(AstArrayMatcher array, IAstNode actual, string path)
{
SomeMatch(actual, path);
if (actual is AstArray arrayActual)
{
string newPath;
for (int i = 0; i < array.Value.Values.Count; i++)
{
newPath = AddPath(path, $"[{i}]");
if (arrayActual.Values.Count - 1 < i)
throw new AssertException($"{PrintablePath(newPath)}Array length mismatch. Expected array lengh: {array.Value.Values.Count} but was: {arrayActual.Values.Count}.");
var theActual = arrayActual.Values[i];
var theExpected = (IAssertEvaluator)array.Value.Values[i];
Match(theExpected, theActual, newPath);
}
newPath = AddPath(path, $"[{array.Value.Values.Count + 1}]");
if (arrayActual.Values.Count > array.Value.Values.Count)
throw new AssertException($"{PrintablePath(newPath)}Array length mismatch. Expected array lengh: {array.Value.Values.Count} but was: {arrayActual.Values.Count}.");
}
else
{
throw new AssertException($"Wrong type of actual value. Expected array got {actual.GetType()}. {PrintablePath(path)}");
}
}
void ComplexMatch(AstComplexMatcher complex, IAstNode actual, string path)
{
SomeMatch(actual, path);
if (actual is AstComplexValue complexActual)
{
foreach (var kv in complexActual.Values)
{
if (complex.Value.Values.TryGetValue(kv.Key, out var matcher))
{
Match((matcher as IAssertEvaluator)!, kv.Value, AddPath(path, kv.Key));
}
else
{
throw new AssertException($"{PrintablePath(path)}Cannot find field '{kv.Key}' in expected values.");
}
}
var inSpecNotInActual = string.Join("', '",
complex.Value.Values.Keys.Where(x => !complexActual.Values.ContainsKey(x)));
if (inSpecNotInActual.Any())
throw new AssertException($"{PrintablePath(path)}Expected fields '{inSpecNotInActual}'\r\nBut fields were not found!");
}
else
{
throw new AssertException($"Wrong type. Expected complex value got {actual.GetType()}. {PrintablePath(path)}");
}
}
private void DateTimeMatch(AstDateTimeMatcher dateTimeMatcher, IAstNode actual, string path)
{
SomeMatch(actual, path);
if (actual is AstSimpleValue simpleActual)
{
if (!(dateTimeMatcher.UnderlyingValue.Value is DateTime expectedDate))
throw new AssertException($"{PrintablePath(path)}Expected: {dateTimeMatcher.UnderlyingValue.Value}\r\nBut was: {simpleActual.Value}");
if (!(simpleActual.Value is DateTime actualDate))
throw new AssertException($"{PrintablePath(path)}Expected: {dateTimeMatcher.UnderlyingValue.Value}\r\nBut was: {simpleActual.Value}");
if (!IsAlmostSame(expectedDate, actualDate, dateTimeMatcher.AcceptedSlack))
Compare(expectedDate, actualDate, path, configuration);
}
else
{
throw new AssertException($"Wrong type. Expected simple value got {actual.GetType()}. {PrintablePath(path)}");
}
}
private void StringMatch(AstStringMatcher str, IAstNode actual, string path)
{
if (actual is AstSimpleValue simpleActual)
{
if (simpleActual.Value == null)
throw new AssertException($"{PrintablePath(path)}Expected: \"{str.UnderlyingValue.Value}\"\r\nBut was: null");
if (!(simpleActual.Value is string actualString))
throw new AssertException($"{PrintablePath(path)}Expected: \"{str.UnderlyingValue.Value}\"\r\nBut was: \"{simpleActual.Value}\"");
if (!(str.UnderlyingValue.Value is string expectedString))
throw new AssertException($"{PrintablePath(path)}Expected: \"{str.UnderlyingValue.Value}\"\r\nBut was: \"{simpleActual.Value}\"");
string regexified = $"^{Regex.Escape(expectedString).Replace("\\*", ".*")}$";
if (!Regex.IsMatch(actualString, regexified, RegexOptions.Singleline))
{
var msg = $@"{PrintablePath(path)}Expected: ""{expectedString.Replace("\r", "\\r").Replace("\n", "\\n")}""
But was: ""{actualString.Replace("\r", "\\r").Replace("\n", "\\n")}""";
throw new AssertException(msg);
}
}
else
{
throw new AssertException($"Wrong type. Expected simple value got {actual.GetType()}. Path: '{path}'");
}
}
private void GuidMatch(AstGuidMatcher guidMatcher, IAstNode actual, string path)
{
if (actual is AstSimpleValue simpleActual)
{
if (!(simpleActual.Value is AstRollingGuid actualRg))
throw new AssertException($"{PrintablePath(path)}Expected: {guidMatcher.UnderlyingValue}\r\nBut was: {simpleActual.Value}");
Compare(guidMatcher.UnderlyingValue, actualRg, path, configuration);
}
else
{
throw new AssertException($"Wrong type. Expected simple value got {actual.GetType()}. Path: '{path}'");
}
}
void SimpleMatch(AstSimpleMatcher simple, IAstNode actual, string path)
{
if (actual is AstSimpleValue simpleActual)
{
Compare(simple.UnderlyingValue.Value, simpleActual.Value, path, configuration);
}
else
{
throw new AssertException($"Wrong type. Expected simple value got {actual.GetType()}. Path: '{path}'");
}
}
public static string PrintablePath(string path) => path == "" ? "" : $"Path: '{path}'.\r\n";
public static void Compare(object? expected, object? actual, string path, Configuration cfg)
{
if (expected == null)
{
if (actual == null)
return;
string actualValue = (actual is string ss ? $"\"{ss}\"" : actual.ToString())!;
throw new AssertException($@"{PrintablePath(path)}Expected: null
But was: {actualValue}");
}
if (actual == null)
{
string expectedValue = (expected is string ss ? $"\"{ss}\"" : expected.ToString())!;
throw new AssertException($@"{PrintablePath(path)}Expected: {expectedValue}
But was: null");
}
string theExpedted = (expected is DateTime de
? de.ToString(cfg.Assertion.DateTimeFormat)
: expected.ToString())!;
string theActual = (actual is DateTime da ? da.ToString(cfg.Assertion.DateTimeFormat) : actual.ToString())!;
if (!theExpedted.Equals(theActual))
throw new AssertException($@"{PrintablePath(path)}Expected: {theExpedted}
But was: {theActual}");
}
public static bool IsAlmostNow(DateTime d1, TimeSpan slack) => IsAlmostSame(d1, DateTime.Now, slack);
public static bool IsAlmostSame(DateTime d1, DateTime d2, TimeSpan slack)
{
return (d1 - d2).Duration() <= slack;
}
}
} | 42.822785 | 188 | 0.547739 | [
"Apache-2.0"
] | kbilsted/ReassureTest.Net | ReassureTest.Net/Implementation/MatchExecutor.cs | 10,151 | C# |
using System;
using System.Reflection;
namespace Configgy.Coercion
{
/// <summary>
/// A base class for any coercer attributes.
/// </summary>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited = true)]
public abstract class ValueCoercerAttributeBase : Attribute, IValueCoercer
{
private static readonly Type NullableType = typeof(Nullable<>);
/// <summary>
/// Coerce the raw string value into the expected result type.
/// </summary>
/// <typeparam name="T">The expected result type after coercion.</typeparam>
/// <param name="value">The raw string value to be coerced.</param>
/// <param name="valueName">The name of the value to be coerced.</param>
/// <param name="property">If this value is directly associated with a property on a <see cref="Config"/> instance this is the reference to that property.</param>
/// <param name="result">The coerced value.</param>
/// <returns>True if the value could be coerced, false otherwise.</returns>
public abstract bool Coerce<T>(string value, string valueName, ICustomAttributeProvider property, out T result);
protected static bool IsNullable<T>()
{
var type = typeof(T);
return type.GetTypeInfo().IsClass || (type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == NullableType);
}
}
}
| 45.0625 | 170 | 0.660194 | [
"MIT"
] | LazyTarget/Configgy | Configgy/Coercion/ValueCoercerAttributeBase.cs | 1,444 | C# |
using System;
namespace InteractiveCommandLine.Parameters
{
internal class StringArrayParameter : Parameter
{
internal int MinSize { get; set; } = 0;
internal int MaxSize { get; set; } = int.MaxValue;
internal string[] Default { get; set; }
internal override string DefaultString => string.Join(',', Default);
internal string[] ParseAndValidate(string value)
{
string[] arrayValue = value.Split(',');
if (arrayValue.Length > MaxSize)
{
throw new Exception($"The array has too many elements! Max: {MaxSize} | Size: {arrayValue.Length}");
}
if (arrayValue.Length < MinSize)
{
throw new Exception($"The array has too few elements! Min: {MinSize} | Size: {arrayValue.Length}");
}
return arrayValue;
}
}
}
| 29.16129 | 116 | 0.565265 | [
"MIT"
] | alex-held/InteractiveCommandLine | InteractiveCommandLine/Parameters/StringArrayParameter.cs | 906 | C# |
using System;
namespace InternetTester.Lib.Tracked
{
public class Shutdown : Item
{
public Shutdown(DateTime t) : base(t)
{
}
public override Type Type => Type.Shutdown;
}
} | 14.384615 | 45 | 0.68984 | [
"MIT"
] | madeso/internet-tester | InternetTester.Lib/Tracked/Shutdown.cs | 189 | C# |
namespace ProjectManager.Core.SeedWork.Interfaces
{
/// <summary>
/// Base contract for map aggregate to dto.
/// <remarks>
/// This is a contract for work with "auto" mappers ( auto-mapper,emit-mapper,value-injector...)
/// or ad-hoc mappers
/// </remarks>
/// </summary>
public interface ITypeAdapter
{
/// <summary>
/// Adapt a source object to an instance of type <typeparamref name="TTarget"/>
/// </summary>
/// <typeparam name="TSource">Type of source item</typeparam>
/// <typeparam name="TTarget">Type of target item</typeparam>
/// <param name="source">Instance to adapt</param>
/// <returns><paramref name="source"/> mapped to <typeparamref name="TTarget"/></returns>
TTarget Adapt<TSource, TTarget>(TSource source)
where TTarget : class
where TSource : class;
/// <summary>
/// Adapt a source object to an instance of type <typeparamref name="TTarget"/>
/// </summary>
/// <typeparam name="TTarget">Type of target item</typeparam>
/// <param name="source">Instance to adapt</param>
/// <returns><paramref name="source"/> mapped to <typeparamref name="TTarget"/></returns>
TTarget Adapt<TTarget>(object source)
where TTarget : class;
}
} | 42.09375 | 101 | 0.604306 | [
"MIT"
] | arsenpellumbi/net-core-project-manager | src/ProjectManager/ProjectManager.Core/SeedWork/Interfaces/ITypeAdapter.cs | 1,349 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using HuaweiCloud.SDK.Core;
namespace HuaweiCloud.SDK.Vpc.V2.Model
{
/// <summary>
/// Request Object
/// </summary>
public class ShowQuotaRequest
{
/// <summary>
/// Defines type
/// </summary>
[JsonConverter(typeof(EnumClassConverter<TypeEnum>))]
public class TypeEnum
{
/// <summary>
/// Enum VPC for value: vpc
/// </summary>
public static readonly TypeEnum VPC = new TypeEnum("vpc");
/// <summary>
/// Enum SUBNET for value: subnet
/// </summary>
public static readonly TypeEnum SUBNET = new TypeEnum("subnet");
/// <summary>
/// Enum SECURITYGROUP for value: securityGroup
/// </summary>
public static readonly TypeEnum SECURITYGROUP = new TypeEnum("securityGroup");
/// <summary>
/// Enum SECURITYGROUPRULE for value: securityGroupRule
/// </summary>
public static readonly TypeEnum SECURITYGROUPRULE = new TypeEnum("securityGroupRule");
/// <summary>
/// Enum PUBLICIP for value: publicIp
/// </summary>
public static readonly TypeEnum PUBLICIP = new TypeEnum("publicIp");
/// <summary>
/// Enum VPN for value: vpn
/// </summary>
public static readonly TypeEnum VPN = new TypeEnum("vpn");
/// <summary>
/// Enum VPNGW for value: vpngw
/// </summary>
public static readonly TypeEnum VPNGW = new TypeEnum("vpngw");
/// <summary>
/// Enum VPCPEER for value: vpcPeer
/// </summary>
public static readonly TypeEnum VPCPEER = new TypeEnum("vpcPeer");
/// <summary>
/// Enum FIREWALL for value: firewall
/// </summary>
public static readonly TypeEnum FIREWALL = new TypeEnum("firewall");
/// <summary>
/// Enum SHAREBANDWIDTH for value: shareBandwidth
/// </summary>
public static readonly TypeEnum SHAREBANDWIDTH = new TypeEnum("shareBandwidth");
/// <summary>
/// Enum SHAREBANDWIDTHIP for value: shareBandwidthIP
/// </summary>
public static readonly TypeEnum SHAREBANDWIDTHIP = new TypeEnum("shareBandwidthIP");
/// <summary>
/// Enum LOADBALANCER for value: loadbalancer
/// </summary>
public static readonly TypeEnum LOADBALANCER = new TypeEnum("loadbalancer");
/// <summary>
/// Enum LISTENER for value: listener
/// </summary>
public static readonly TypeEnum LISTENER = new TypeEnum("listener");
/// <summary>
/// Enum PHYSICALCONNECT for value: physicalConnect
/// </summary>
public static readonly TypeEnum PHYSICALCONNECT = new TypeEnum("physicalConnect");
/// <summary>
/// Enum VIRTUALINTERFACE for value: virtualInterface
/// </summary>
public static readonly TypeEnum VIRTUALINTERFACE = new TypeEnum("virtualInterface");
/// <summary>
/// Enum VPCCONTAINROUTETABLE for value: vpcContainRoutetable
/// </summary>
public static readonly TypeEnum VPCCONTAINROUTETABLE = new TypeEnum("vpcContainRoutetable");
/// <summary>
/// Enum ROUTETABLECONTAINROUTES for value: routetableContainRoutes
/// </summary>
public static readonly TypeEnum ROUTETABLECONTAINROUTES = new TypeEnum("routetableContainRoutes");
public static readonly Dictionary<string, TypeEnum> StaticFields =
new Dictionary<string, TypeEnum>()
{
{"vpc", VPC},
{"subnet", SUBNET},
{"securityGroup", SECURITYGROUP},
{"securityGroupRule", SECURITYGROUPRULE},
{"publicIp", PUBLICIP},
{"vpn", VPN},
{"vpngw", VPNGW},
{"vpcPeer", VPCPEER},
{"firewall", FIREWALL},
{"shareBandwidth", SHAREBANDWIDTH},
{"shareBandwidthIP", SHAREBANDWIDTHIP},
{"loadbalancer", LOADBALANCER},
{"listener", LISTENER},
{"physicalConnect", PHYSICALCONNECT},
{"virtualInterface", VIRTUALINTERFACE},
{"vpcContainRoutetable", VPCCONTAINROUTETABLE},
{"routetableContainRoutes", ROUTETABLECONTAINROUTES},
};
private string Value;
public TypeEnum(string Value)
{
this.Value = Value;
}
public static TypeEnum FromValue(string Value)
{
if(Value == null){
return null;
}
if (StaticFields.ContainsKey(Value))
{
return StaticFields[Value];
}
return null;
}
public override string ToString()
{
return this.Value;
}
public override int GetHashCode()
{
return this.Value.GetHashCode();
}
public override bool Equals(object obj)
{
if (obj == null)
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
if (this.Equals(obj as TypeEnum))
{
return true;
}
return false;
}
public bool Equals(TypeEnum obj)
{
if ((object)obj == null)
{
return false;
}
return StringComparer.OrdinalIgnoreCase.Equals(this.Value, obj.Value);
}
public static bool operator ==(TypeEnum a, TypeEnum b)
{
if (System.Object.ReferenceEquals(a, b))
{
return true;
}
if ((object)a == null)
{
return false;
}
return a.Equals(b);
}
public static bool operator !=(TypeEnum a, TypeEnum b)
{
return !(a == b);
}
}
/// <summary>
///
/// </summary>
[SDKProperty("type", IsQuery = true)]
public TypeEnum Type { get; set; }
/// <summary>
/// Get the string
/// </summary>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class ShowQuotaRequest {\n");
sb.Append(" type: ").Append(Type).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
public override bool Equals(object input)
{
return this.Equals(input as ShowQuotaRequest);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
public bool Equals(ShowQuotaRequest input)
{
if (input == null)
return false;
return
(
this.Type == input.Type ||
(this.Type != null &&
this.Type.Equals(input.Type))
);
}
/// <summary>
/// Get hash code
/// </summary>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.Type != null)
hashCode = hashCode * 59 + this.Type.GetHashCode();
return hashCode;
}
}
}
}
| 31.040892 | 110 | 0.485629 | [
"Apache-2.0"
] | Huaweicloud-SDK/huaweicloud-sdk-net-v3 | Services/Vpc/V2/Model/ShowQuotaRequest.cs | 8,350 | C# |
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Runtime.CompilerServices;
using System.Windows.Media;
using ESME.Database;
using ESME.Locations;
using ESME.Mapping;
using HRC.Aspects;
using HRC.Utility;
using HRC.ViewModels;
using HRC.WPF;
using ThinkGeo.MapSuite.Core;
namespace ESME.Scenarios
{
public class LayerSettings : ViewModelBase, IHaveGuid
{
public static Random Random = new Random();
public LayerSettings()
{
PointSymbolType = new DbPointSymbolType {PointSymbolTypeAsInt = Random.Next(8)};
Color curColor;
while (true)
{
curColor = ColorExtensions.GetRandomNamedColor();
if (LumaChromaColor.FromColor(curColor).Y >= 0.5f) break;
}
LineOrSymbolDbColor = new DbColor(curColor);
AreaDbColor = new DbColor(Colors.Transparent);
}
public LayerSettings(LayerSettings layerSettings)
{
IsChecked = layerSettings.IsChecked;
PointSymbolType = layerSettings.PointSymbolType;
LineOrSymbolDbColor = layerSettings.LineOrSymbolDbColor;
AreaDbColor = layerSettings.AreaDbColor;
LineOrSymbolSize = layerSettings.LineOrSymbolSize;
}
[Key, Initialize] public Guid Guid { get; set; }
bool _isChecked;
public bool IsChecked
{
get { return _isChecked; }
set
{
_isChecked = value;
if (DisplayIfScenarioIsLoadedFunc != null && !DisplayIfScenarioIsLoadedFunc())
{
if (MapLayerViewModel != null) MediatorMessage.Send(MediatorMessage.HideMapLayer, MapLayerViewModel);
return;
}
if (MapLayerViewModel != null) MediatorMessage.Send(_isChecked ? MediatorMessage.ShowMapLayer : MediatorMessage.HideMapLayer, MapLayerViewModel);
}
}
public DbPointSymbolType PointSymbolType { get; set; }
public DbColor LineOrSymbolDbColor { get; set; }
public DbColor AreaDbColor { get; set; }
[Initialize(-1)]
public int LayerOrder { get; set; }
[Initialize(1.0)]
public double LineOrSymbolSize
{
get { return _lineOrSymbolSize; }
set
{
_lineOrSymbolSize = value;
if (MapLayerViewModel == null) return;
MapLayerViewModel.LineWidth = (float)value;
MediatorMessage.Send(MediatorMessage.RefreshMapLayer, MapLayerViewModel);
}
}
double _lineOrSymbolSize;
[NotMapped] public Action LineOrSymbolSizeChanged { get; set; }
[NotMapped] public Func<bool> DisplayIfScenarioIsLoadedFunc { get; set; }
[NotMapped] public PointSymbolType SymbolType
{
get { return _symbolType; }
set
{
_symbolType = value;
if (MapLayerViewModel == null) return;
MapLayerViewModel.PointSymbolType = value;
MediatorMessage.Send(MediatorMessage.RefreshMapLayer, MapLayerViewModel);
}
}
PointSymbolType _symbolType;
[NotMapped] public Action SymbolTypeChanged { get; set; }
[NotMapped]
public Color LineOrSymbolColor
{
get { return LineOrSymbolDbColor.Color; }
set
{
LineOrSymbolDbColor.Color = value;
if (MapLayerViewModel == null) return;
MapLayerViewModel.LineColor = value;
MediatorMessage.Send(MediatorMessage.RefreshMapLayer, MapLayerViewModel);
}
}
[NotMapped] public Action LineOrSymbolColorChanged { get; set; }
[NotMapped]
public Color AreaColor
{
get { return AreaDbColor.Color; }
set
{
AreaDbColor.Color = value;
if (MapLayerViewModel == null) return;
MapLayerViewModel.AreaColor = value;
MediatorMessage.Send(MediatorMessage.RefreshMapLayer, MapLayerViewModel);
}
}
[NotMapped] public Action AreaColorChanged { get; set; }
public void MoveLayerToFront() { if (_mapLayerViewModel != null) MediatorMessage.Send(MediatorMessage.MoveLayerToFront, _mapLayerViewModel); }
public void MoveLayerForward() { if (_mapLayerViewModel != null) MediatorMessage.Send(MediatorMessage.MoveLayerForward, _mapLayerViewModel); }
public void MoveLayerBackward() { if (_mapLayerViewModel != null) MediatorMessage.Send(MediatorMessage.MoveLayerBackward, _mapLayerViewModel); }
public void MoveLayerToBack() { if (_mapLayerViewModel != null) MediatorMessage.Send(MediatorMessage.MoveLayerToBack, _mapLayerViewModel); }
[NotMapped]
public MapLayerViewModel MapLayerViewModel
{
[MethodImpl(MethodImplOptions.Synchronized)]
get { return _mapLayerViewModel; }
[MethodImpl(MethodImplOptions.Synchronized)]
set
{
if (value == null && _mapLayerViewModel != null)
{
MediatorMessage.Send(MediatorMessage.RemoveMapLayer, _mapLayerViewModel);
_mapLayerViewModel.LayerOverlay.MouseIsHovering.Dispose();
}
else if (_mapLayerViewModel == value)
{
MediatorMessage.Send(MediatorMessage.RefreshMapLayer, _mapLayerViewModel);
return;
}
_mapLayerViewModel = value;
if (_mapLayerViewModel == null) return;
MediatorMessage.Send(MediatorMessage.AddMapLayer, _mapLayerViewModel);
MediatorMessage.Send(IsChecked ? MediatorMessage.ShowMapLayer : MediatorMessage.HideMapLayer, _mapLayerViewModel);
_mapLayerViewModel.AreaColor = AreaColor;
_mapLayerViewModel.LineColor = LineOrSymbolColor;
_mapLayerViewModel.PointSymbolType = SymbolType;
_mapLayerViewModel.LineWidth = (float)LineOrSymbolSize;
}
}
MapLayerViewModel _mapLayerViewModel;
public void RefreshMapLayer()
{
if (_mapLayerViewModel == null) return;
MediatorMessage.Send(MediatorMessage.RefreshMapLayer, _mapLayerViewModel);
}
}
} | 40.662651 | 162 | 0.596 | [
"MPL-2.0"
] | AuditoryBiophysicsLab/ESME-Workbench | Libraries/ESME/Scenarios/LayerSettings.cs | 6,750 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TinaX.VFSKitInternal
{
/// <summary>
/// 资源构建信息
/// </summary>
[Serializable]
public struct BuildInfo
{
public string BuildID;
}
}
| 16.388889 | 33 | 0.661017 | [
"MIT"
] | ErQing/TinaX.VFS | Runtime/Scripts/JsonModel/BuildInfo.cs | 309 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.